diff options
author | maximius <none@none> | 2009-10-17 15:51:44 -0700 |
---|---|---|
committer | maximius <none@none> | 2009-10-17 15:51:44 -0700 |
commit | e585187b248f48b3c6e9247b49fa07c6565d65e5 (patch) | |
tree | 637c5b7ddacf41040bef4ea4f75a97da64c6a9bc /src/game/Player.cpp | |
parent | 26b5e033ffde3d161382fc9addbfa99738379641 (diff) |
*Backed out changeset 3be01fb200a5
--HG--
branch : trunk
Diffstat (limited to 'src/game/Player.cpp')
-rw-r--r-- | src/game/Player.cpp | 3380 |
1 files changed, 3376 insertions, 4 deletions
diff --git a/src/game/Player.cpp b/src/game/Player.cpp index 0fb078fc7c6..2d49a7559e9 100644 --- a/src/game/Player.cpp +++ b/src/game/Player.cpp @@ -17,6 +17,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + #include "Common.h" #include "Language.h" #include "Database/DatabaseEnv.h" @@ -64,17 +65,23 @@ #include "GameEventMgr.h" #include "AchievementMgr.h" #include "SpellAuras.h" + #include <cmath> + #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS) + #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3)) #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1) #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2) + #define SKILL_VALUE(x) PAIR32_LOPART(x) #define SKILL_MAX(x) PAIR32_HIPART(x) #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m) + #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x)) #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x)) #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p) + enum CharacterFlags { CHARACTER_FLAG_NONE = 0x00000000, @@ -111,16 +118,21 @@ enum CharacterFlags CHARACTER_FLAG_UNK31 = 0x40000000, CHARACTER_FLAG_UNK32 = 0x80000000 }; + // corpse reclaim times #define DEATH_EXPIRE_STEP (5*MINUTE) #define MAX_DEATH_COUNT 3 + static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 }; + //== PlayerTaxi ================================================ + PlayerTaxi::PlayerTaxi() { // Taxi nodes memset(m_taximask, 0, sizeof(m_taximask)); } + void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level) { // class specific initial known nodes @@ -133,6 +145,7 @@ void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 leve break; } } + // race specific initial known nodes: capital and taxi hub masks switch(race) { @@ -148,6 +161,7 @@ void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 leve case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei } + // new continent starting masks (It will be accessible only at new map) switch(Player::TeamForRace(race)) { @@ -158,9 +172,11 @@ void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 leve if(level>=68) SetTaximaskNode(213); //Shattered Sun Staging Area } + void PlayerTaxi::LoadTaxiMask(const char* data) { Tokens tokens = StrSplit(data, " "); + uint8 index; Tokens::iterator iter; for (iter = tokens.begin(), index = 0; @@ -170,6 +186,7 @@ void PlayerTaxi::LoadTaxiMask(const char* data) m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str())); } } + void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all ) { if(all) @@ -183,20 +200,26 @@ void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all ) data << uint32(m_taximask[i]); // known nodes } } + bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team ) { ClearTaxiDestinations(); + Tokens tokens = StrSplit(values," "); + for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter) { uint32 node = uint32(atol(iter->c_str())); AddTaxiDestination(node); } + if(m_TaxiDestinations.empty()) return true; + // Check integrity if(m_TaxiDestinations.size() < 2) return false; + for(size_t i = 1; i < m_TaxiDestinations.size(); ++i) { uint32 cost; @@ -205,29 +228,40 @@ bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint if(!path) return false; } + // can't load taxi path without mount set (quest taxi path?) if(!objmgr.GetTaxiMountDisplayId(GetTaxiSource(),team,true)) return false; + return true; } + std::string PlayerTaxi::SaveTaxiDestinationsToString() { if(m_TaxiDestinations.empty()) return ""; + std::ostringstream ss; + for(size_t i=0; i < m_TaxiDestinations.size(); ++i) ss << m_TaxiDestinations[i] << " "; + return ss.str(); } + uint32 PlayerTaxi::GetCurrentTaxiPath() const { if(m_TaxiDestinations.size() < 2) return 0; + uint32 path; uint32 cost; + objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost); + return path; } + std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi) { ss << "'"; @@ -236,62 +270,94 @@ std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi) ss << "'"; return ss; } + //== Player ==================================================== + UpdateMask Player::updateVisualBits; + Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this) { m_speakTime = 0; m_speakCount = 0; + m_objectType |= TYPEMASK_PLAYER; m_objectTypeId = TYPEID_PLAYER; + m_valuesCount = PLAYER_END; + m_session = session; + m_divider = 0; + m_ExtraFlags = 0; + m_spellModTakingSpell = NULL; m_pad = 0; + // players always accept if(GetSession()->GetSecurity() == SEC_PLAYER) SetAcceptWhispers(true); + m_curSelection = 0; m_lootGuid = 0; + m_comboTarget = 0; m_comboPoints = 0; + m_usedTalentCount = 0; m_questRewardTalentCount = 0; + m_regenTimer = 0; m_regenTimerCount = 0; m_weaponChangeTimer = 0; + m_zoneUpdateId = 0; m_zoneUpdateTimer = 0; + m_areaUpdateId = 0; + m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE); + clearResurrectRequestData(); + memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT); + m_social = NULL; + // group is initialized in the reference constructor SetGroupInvite(NULL); m_groupUpdateMask = 0; m_auraRaidUpdateMask = 0; + duel = NULL; + m_GuildIdInvited = 0; m_ArenaTeamIdInvited = 0; + m_atLoginFlags = AT_LOGIN_NONE; + mSemaphoreTeleport_Near = false; mSemaphoreTeleport_Far = false; + m_DelayedOperations = 0; m_bCanDelayTeleport = false; m_bHasDelayedTeleport = false; m_teleport_options = 0; + pTrader = 0; ClearTrade(); + m_cinematic = 0; + PlayerTalkClass = new PlayerMenu( GetSession() ); m_currentBuybackSlot = BUYBACK_SLOT_START; + m_DailyQuestChanged = false; m_lastDailyQuestTime = 0; + for (uint8 i=0; i<MAX_TIMERS; i++) m_MirrorTimer[i] = DISABLED_MIRROR_TIMER; + m_MirrorTimerFlags = UNDERWATER_NONE; m_MirrorTimerFlagsLast = UNDERWATER_NONE; m_isInWater = false; @@ -300,13 +366,17 @@ Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputa m_restTime = 0; m_deathTimer = 0; m_deathExpireTime = 0; + m_swingErrorMsg = 0; + m_DetectInvTimer = 1*IN_MILISECONDS; + for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j) { m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE; m_bgBattleGroundQueueID[j].invitedToInstance = 0; } + m_logintime = time(NULL); m_Last_tick = m_logintime; m_WeaponProficiency = 0; @@ -316,12 +386,14 @@ Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputa m_canDualWield = false; m_canTitanGrip = false; m_ammoDPS = 0.0f; + m_temporaryUnsummonedPetNumber = 0; //cache for UNIT_CREATED_BY_SPELL to allow //returning reagents for temporarily removed pets //when dying/logging out m_oldpetspell = 0; m_lastpetnumber = 0; + ////////////////////Rest System///////////////////// time_inn_enter=0; inn_pos_mapid=0; @@ -331,134 +403,187 @@ Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputa m_rest_bonus=0; rest_type=REST_TYPE_NO; ////////////////////Rest System///////////////////// + m_mailsLoaded = false; m_mailsUpdated = false; unReadMails = 0; m_nextMailDelivereTime = 0; + m_resetTalentsCost = 0; m_resetTalentsTime = 0; m_itemUpdateQueueBlocked = false; + for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i) m_forced_speed_changes[i] = 0; + m_stableSlots = 0; + /////////////////// Instance System ///////////////////// + m_HomebindTimer = 0; m_InstanceValid = true; m_dungeonDifficulty = DIFFICULTY_NORMAL; + m_lastPotionId = 0; + m_activeSpec = 0; m_specsCount = 0; + for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i) { for (int g = 0; g < MAX_GLYPH_SLOT_INDEX; ++g) m_Glyphs[i][g] = 0; + m_talents[i] = new PlayerTalentMap(); } + for (int i = 0; i < BASEMOD_END; ++i) { m_auraBaseMod[i][FLAT_MOD] = 0.0f; m_auraBaseMod[i][PCT_MOD] = 1.0f; } + for (uint8 i = 0; i < MAX_COMBAT_RATING; i++) m_baseRatingValue[i] = 0; + m_baseSpellPower = 0; m_baseFeralAP = 0; m_baseManaRegen = 0; + // Honor System m_lastHonorUpdateTime = time(NULL); + // Player summoning m_summon_expire = 0; m_summon_mapid = 0; m_summon_x = 0.0f; m_summon_y = 0.0f; m_summon_z = 0.0f; + //Default movement to run mode //m_unit_movement_flags = 0; + m_mover = this; m_movedPlayer = this; m_seer = this; + m_contestedPvPTimer = 0; + m_declinedname = NULL; + m_isActive = true; + m_runes = NULL; + m_lastFallTime = 0; m_lastFallZ = 0; + m_ControlledByPlayer = true; m_isWorldObject = true; + sWorld.IncreasePlayerCount(); + m_ChampioningFaction = 0; + for(int i = 0; i < MAX_POWERS; ++i) m_powerFraction[i] = 0; } + Player::~Player () { // it must be unloaded already in PlayerLogout and accessed only for loggined player //m_social = NULL; + // Note: buy back item already deleted from DB when player was saved for(uint8 i = 0; i < PLAYER_SLOTS_COUNT; ++i) { if(m_items[i]) delete m_items[i]; } + for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr) delete itr->second; + for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i) { for (PlayerTalentMap::const_iterator itr = m_talents[i]->begin(); itr != m_talents[i]->end(); ++itr) delete itr->second; delete m_talents[i]; } + //all mailed items should be deleted, also all mail should be deallocated for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr) delete *itr; + for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter) delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated + delete PlayerTalkClass; + for(size_t x = 0; x < ItemSetEff.size(); x++) if(ItemSetEff[x]) delete ItemSetEff[x]; + delete m_declinedname; delete m_runes; + sWorld.DecreasePlayerCount(); } + void Player::CleanupsBeforeDelete() { TradeCancel(false); DuelComplete(DUEL_INTERUPTED); + Unit::CleanupsBeforeDelete(); + if (m_transport) m_transport->RemovePassenger(this); + // clean up player-instance binds, may unload some instance saves for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i) for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr) itr->second.save->RemovePlayer(this); } + bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 outfitId ) { //FIXME: outfitId not used in player creating + Object::_Create(guidlow, 0, HIGHGUID_PLAYER); + m_name = name; + PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_); if(!info) { sLog.outError("Player have incorrect race/class pair. Can't be loaded."); return false; } + for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++) m_items[i] = NULL; + Relocate(info->positionX,info->positionY,info->positionZ); + ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_); if(!cEntry) { sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_); return false; } + SetMap(MapManager::Instance().CreateMap(info->mapId, this, 0)); + uint8 powertype = cEntry->powerType; + SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE); SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f); + setFactionForRace(race); + uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 ); + SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) ); InitDisplayIds(); if(sWorld.getConfig(CONFIG_GAME_TYPE) == REALM_TYPE_PVP || sWorld.getConfig(CONFIG_GAME_TYPE) == REALM_TYPE_RPPVP) @@ -469,14 +594,18 @@ bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER); SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3 + // -1 is default value SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1)); + SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24))); SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24))); SetByteValue(PLAYER_BYTES_3, 0, gender); + SetUInt32Value( PLAYER_GUILDID, 0 ); SetUInt32Value( PLAYER_GUILDRANK, 0 ); SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 ); + SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 0 ); // 0=disabled @@ -485,27 +614,34 @@ bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, 0 ); SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 ); SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 ); + // set starting level uint32 start_level = getClass() != CLASS_DEATH_KNIGHT ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL) : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL); + if (GetSession()->GetSecurity() >= SEC_MODERATOR) { uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL); if(gm_level > start_level) start_level = gm_level; } + SetUInt32Value(UNIT_FIELD_LEVEL, start_level); + InitRunes(); + SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY)); SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS)); SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS)); + // start with every map explored if(sWorld.getConfig(CONFIG_START_ALL_EXPLORED)) { for (uint8 i=0; i<64; i++) SetFlag(PLAYER_EXPLORED_ZONES_1+i,0xFFFFFFFF); } + //Reputations if "StartAllReputation" is enabled, -- TODO: Fix this in a better way if(sWorld.getConfig(CONFIG_START_ALL_REP)) { @@ -520,6 +656,7 @@ bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 GetReputationMgr().SetReputation(sFactionStore.LookupEntry(934),42999); GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1038),42999); GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1077),42999); + // Factions depending on team, like cities and some more stuff switch(GetTeam()) { @@ -547,16 +684,19 @@ bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 break; } } + // Played time m_Last_tick = time(NULL); m_Played_time[PLAYED_TIME_TOTAL] = 0; m_Played_time[PLAYED_TIME_LEVEL] = 0; + // base stats and related field values InitStatsForLevel(); InitTaxiNodesForLevel(); InitGlyphsForLevel(); InitTalentForLevel(); InitPrimaryProfessions(); // to max set before any spell added + // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods() UpdateMaxHealth(); // Update max Health (for add bonus from stamina) SetHealth(GetMaxHealth()); @@ -565,6 +705,7 @@ bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect) SetPower(POWER_MANA,GetMaxPower(POWER_MANA)); } + if(getPowerType() == POWER_RUNIC_POWER) { SetPower(POWER_RUNE, 8); @@ -572,11 +713,14 @@ bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 SetPower(POWER_RUNIC_POWER, 0); SetMaxPower(POWER_RUNIC_POWER, 1000); } + // original spells learnDefaultSpells(); + // original action bar for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr) addActionButton(action_itr->button,action_itr->action,action_itr->type); + // original items CharStartOutfitEntry const* oEntry = NULL; for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i) @@ -590,24 +734,30 @@ bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 } } } + if(oEntry) { for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j) { if(oEntry->ItemId[j] <= 0) continue; + uint32 item_id = oEntry->ItemId[j]; + // Hack for not existed item id in dbc 3.0.3 if(item_id==40582) continue; + ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id); if(!iProto) { sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass()); continue; } + // BuyCount by default uint32 count = iProto->BuyCount; + // special amount for food/drink if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD) { @@ -623,11 +773,14 @@ bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 if(iProto->Stackable < count) count = iProto->Stackable; } + StoreNewItemInBestSlots(item_id, count); } } + for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++) StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount); + // bags and main-hand weapon must equipped at this moment // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon) // or ammo not equipped in special bag @@ -653,6 +806,7 @@ bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 RemoveItem(INVENTORY_SLOT_BAG_0, i,true); pItem = StoreItem( sDest, pItem, true); } + // if this is ammo then use it msg = CanUseAmmo( pItem->GetEntry() ); if( msg == EQUIP_ERR_OK ) @@ -661,11 +815,14 @@ bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 } } // all item positions resolved + return true; } + bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount) { sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount); + // attempt equip by one while(titem_amount > 0) { @@ -673,12 +830,15 @@ bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount) uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false ); if( msg != EQUIP_ERR_OK ) break; + EquipNewItem( eDest, titem_id, true); AutoUnequipOffhandIfNeed(); --titem_amount; } + if(titem_amount == 0) return true; // equipped + // attempt store ItemPosCountVec sDest; // store in main bag to simplify second pass (special bags can be not equipped yet at this moment) @@ -688,10 +848,12 @@ bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount) StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) ); return true; // stored } + // item can't be added sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg); return false; } + void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen) { if (int(MaxValue) == DISABLED_MIRROR_TIMER) @@ -709,6 +871,7 @@ void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 Curre data << (uint32)0; // spell id GetSession()->SendPacket( &data ); } + void Player::StopMirrorTimer(MirrorTimerType Type) { m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER; @@ -716,10 +879,12 @@ void Player::StopMirrorTimer(MirrorTimerType Type) data << (uint32)Type; GetSession()->SendPacket( &data ); } + uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage) { if(!isAlive() || isGameMaster()) return 0; + // Absorb, resist some environmental damage type uint32 absorb = 0; uint32 resist = 0; @@ -727,8 +892,11 @@ uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage) CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist); else if (type == DAMAGE_SLIME) CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist); + damage-=absorb+resist; + DealDamageMods(this,damage,&absorb); + WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21)); data << uint64(GetGUID()); data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL); @@ -736,7 +904,9 @@ uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage) data << uint32(absorb); data << uint32(resist); SendMessageToSet(&data, true); + uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + if(!isAlive()) { if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage @@ -747,10 +917,13 @@ uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage) WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0); GetSession()->SendPacket(&data2); } + GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type); } + return final_damage; } + int32 Player::getMaxTimer(MirrorTimerType timer) { switch (timer) @@ -778,16 +951,19 @@ int32 Player::getMaxTimer(MirrorTimerType timer) } return 0; } + void Player::UpdateMirrorTimers() { // Desync flags for update on next HandleDrowning if (m_MirrorTimerFlags) m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags; } + void Player::HandleDrowning(uint32 time_diff) { if (!m_MirrorTimerFlags) return; + // In water if (m_MirrorTimerFlags & UNDERWATER_INWATER) { @@ -823,6 +999,7 @@ void Player::HandleDrowning(uint32 time_diff) else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER) SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10); } + // In dark water if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER) { @@ -860,6 +1037,7 @@ void Player::HandleDrowning(uint32 time_diff) else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER) SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10); } + if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME)) { // Breath timer not activated - activate it @@ -883,6 +1061,7 @@ void Player::HandleDrowning(uint32 time_diff) } else m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER; + // Recheck timers flag m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS; for (uint8 i = 0; i< MAX_TIMERS; ++i) @@ -893,13 +1072,16 @@ void Player::HandleDrowning(uint32 time_diff) } m_MirrorTimerFlagsLast = m_MirrorTimerFlags; } + ///The player sobers by 256 every 10 seconds void Player::HandleSobering() { m_drunkTimer = 0; + uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256); SetDrunkValue(drunk); } + DrunkenState Player::GetDrunkenstateByValue(uint16 value) { if(value >= 23000) @@ -910,37 +1092,48 @@ DrunkenState Player::GetDrunkenstateByValue(uint16 value) return DRUNKEN_TIPSY; return DRUNKEN_SOBER; } + void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId) { uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk); + m_drunk = newDrunkenValue; SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE)); + uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk); + // special drunk invisibility detection if(newDrunkenState >= DRUNKEN_DRUNK) m_detectInvisibilityMask |= (1<<6); else m_detectInvisibilityMask &= ~(1<<6); + if(newDrunkenState == oldDrunkenState) return; + WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4)); data << uint64(GetGUID()); data << uint32(newDrunkenState); data << uint32(itemId); + SendMessageToSet(&data, true); } + void Player::Update( uint32 p_time ) { if(!IsInWorld()) return; + // undelivered mail if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL)) { SendNewMail(); ++unReadMails; + // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated) m_nextMailDelivereTime = 0; } + // If this is set during update SetSpellModTakingSpell call is missing somewhere in the code // Having this would prevent more aura charges to be dropped, so let's crash //assert (!m_spellModTakingSpell); @@ -952,25 +1145,35 @@ void Player::Update( uint32 p_time ) assert(false); m_spellModTakingSpell = NULL; } + //used to implement delayed far teleports SetCanDelayTeleport(true); Unit::Update( p_time ); SetCanDelayTeleport(false); + time_t now = time (NULL); + UpdatePvPFlag(now); + UpdateContestedPvP(p_time); + UpdateDuelFlag(now); + CheckDuelDistance(now); + UpdateAfkReport(now); + if(isCharmed()) { if(Unit *charmer = GetCharmer()) if(charmer->GetTypeId() == TYPEID_UNIT && charmer->isAlive()) UpdateCharmedAI(); } + // Update items that have just a limited lifetime if (now>m_Last_tick) UpdateItemDuration(uint32(now- m_Last_tick)); + if (!m_timedquests.empty()) { std::set<uint32>::iterator iter = m_timedquests.begin(); @@ -991,12 +1194,14 @@ void Player::Update( uint32 p_time ) } } } + if (hasUnitState(UNIT_STAT_MELEE_ATTACKING) && !hasUnitState(UNIT_STAT_CASTING)) { if(Unit *pVictim = getVictim()) { // default combat reach 10 // TODO add weapon,skill check + if (isAttackReady(BASE_ATTACK)) { if(!IsWithinMeleeRange(pVictim)) @@ -1021,6 +1226,7 @@ void Player::Update( uint32 p_time ) else { m_swingErrorMsg = 0; // reset swing error state + // prevent base and off attack in same time, delay attack at 0.2 sec if(haveOffhandWeapon()) { @@ -1032,6 +1238,7 @@ void Player::Update( uint32 p_time ) resetAttackTimer(BASE_ATTACK); } } + if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK)) { if(!IsWithinMeleeRange(pVictim)) @@ -1053,6 +1260,7 @@ void Player::Update( uint32 p_time ) resetAttackTimer(OFF_ATTACK); } } + /*Unit *owner = pVictim->GetOwner(); Unit *u = owner ? owner : pVictim; if(u->IsPvP() && (!duel || duel->opponent != u)) @@ -1062,6 +1270,7 @@ void Player::Update( uint32 p_time ) }*/ } } + if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) { if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update @@ -1076,6 +1285,7 @@ void Player::Update( uint32 p_time ) } } } + if (m_weaponChangeTimer > 0) { if(p_time >= m_weaponChangeTimer) @@ -1083,12 +1293,14 @@ void Player::Update( uint32 p_time ) else m_weaponChangeTimer -= p_time; } + if (m_zoneUpdateTimer > 0) { if(p_time >= m_zoneUpdateTimer) { uint32 newzone, newarea; GetZoneAndAreaId(newzone,newarea); + if( m_zoneUpdateId != newzone ) UpdateZone(newzone,newarea); // also update area else @@ -1097,21 +1309,25 @@ void Player::Update( uint32 p_time ) // needed for free far all arenas for example if( m_areaUpdateId != newarea ) UpdateArea(newarea); + m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL; } } else m_zoneUpdateTimer -= p_time; } + if (isAlive()) { m_regenTimer += p_time; RegenerateAll(); } + if (m_deathState == JUST_DIED) { KillPlayer(); } + if(m_nextSave > 0) { if(p_time >= m_nextSave) @@ -1125,8 +1341,10 @@ void Player::Update( uint32 p_time ) m_nextSave -= p_time; } } + //Handle Water/drowning HandleDrowning(p_time); + //Handle detect stealth players if (m_DetectInvTimer > 0) { @@ -1138,6 +1356,7 @@ void Player::Update( uint32 p_time ) else m_DetectInvTimer -= p_time; } + // Played time if (now > m_Last_tick) { @@ -1146,12 +1365,15 @@ void Player::Update( uint32 p_time ) m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time m_Last_tick = now; } + if (m_drunk) { m_drunkTimer += p_time; + if (m_drunkTimer > 10*IN_MILISECONDS) HandleSobering(); } + // not auto-free ghost from body in instances if(m_deathTimer > 0 && !GetBaseMap()->Instanceable()) { @@ -1164,25 +1386,32 @@ void Player::Update( uint32 p_time ) else m_deathTimer -= p_time; } + UpdateEnchantTime(p_time); UpdateHomebindTime(p_time); + // group update SendUpdateToOutOfRangeGroupMembers(); + Pet* pet = GetPet(); if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && !pet->isPossessed()) //if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID()))) { RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true); } + //we should execute delayed teleports only for alive(!) players //because we don't want player's ghost teleported from graveyard if(IsHasDelayedTeleport() && isAlive()) TeleportTo(m_teleport_dest, m_teleport_options); } + void Player::setDeathState(DeathState s) { uint32 ressSpellId = 0; + bool cur = isAlive(); + if(s == JUST_DIED) { if(!cur) @@ -1190,17 +1419,23 @@ void Player::setDeathState(DeathState s) sLog.outError("setDeathState: attempt to kill a dead player %s(%d)", GetName(), GetGUIDLow()); return; } + // drunken state is cleared on death SetDrunkValue(0); // lost combo points at any target (targeted combo points clear in Unit::setDeathState) ClearComboPoints(); + clearResurrectRequestData(); + // remove form before other mods to prevent incorrect stats calculation RemoveAurasDueToSpell(m_ShapeShiftFormSpellId); + //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD) RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true); + // save value before aura remove in Unit::setDeathState ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL); + // passive spell if(!ressSpellId) ressSpellId = GetResurrectionSpellId(); @@ -1209,18 +1444,22 @@ void Player::setDeathState(DeathState s) GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1); } Unit::setDeathState(s); + // restore resurrection spell id for player after aura remove if(s == JUST_DIED && cur && ressSpellId) SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId); + if(isAlive() && !cur) { //clear aura case after resurrection by another way (spells will be applied before next death) SetUInt32Value(PLAYER_SELF_RES_SPELL, 0); + // restore default warrior stance if(getClass()== CLASS_WARRIOR) CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true); } } + bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data ) { // 0 1 2 3 4 5 6 7 @@ -1229,35 +1468,45 @@ bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data ) // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, " // 15 16 17 18 19 20 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive " + Field *fields = result->Fetch(); + uint32 guid = fields[0].GetUInt32(); uint8 pRace = fields[2].GetUInt8(); uint8 pClass = fields[3].GetUInt8(); + PlayerInfo const *info = objmgr.GetPlayerInfo(pRace, pClass); if(!info) { sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid); return false; } + *p_data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)); *p_data << fields[1].GetString(); // name *p_data << uint8(pRace); // race *p_data << uint8(pClass); // class *p_data << uint8(fields[4].GetUInt8()); // gender + uint32 playerBytes = fields[5].GetUInt32(); *p_data << uint8(playerBytes); // skin *p_data << uint8(playerBytes >> 8); // face *p_data << uint8(playerBytes >> 16); // hair style *p_data << uint8(playerBytes >> 24); // hair color + uint32 playerBytes2 = fields[6].GetUInt32(); *p_data << uint8(playerBytes2 & 0xFF); // facial hair + *p_data << uint8(fields[7].GetUInt8()); // level *p_data << uint32(fields[8].GetUInt32()); // zone *p_data << uint32(fields[9].GetUInt32()); // map + *p_data << fields[10].GetFloat(); // x *p_data << fields[11].GetFloat(); // y *p_data << fields[12].GetFloat(); // z + *p_data << uint32(fields[13].GetUInt32()); // guild id + uint32 char_flags = 0; uint32 playerFlags = fields[14].GetUInt32(); uint32 atLoginFlags = fields[15].GetUInt32(); @@ -1276,15 +1525,18 @@ bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data ) } else char_flags |= CHARACTER_FLAG_DECLINED; + *p_data << uint32(char_flags); // character flags // character customize (flags?) *p_data << uint32(atLoginFlags & AT_LOGIN_CUSTOMIZE ? 1 : 0); *p_data << uint8(1); // unknown + // Pets info { uint32 petDisplayId = 0; uint32 petLevel = 0; uint32 petFamily = 0; + // show pet at selection character in character list only for non-ghost character if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT)) { @@ -1297,12 +1549,15 @@ bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data ) petFamily = cInfo->family; } } + *p_data << uint32(petDisplayId); *p_data << uint32(petLevel); *p_data << uint32(petFamily); } + // TODO: do not access data field here Tokens data = StrSplit(fields[19].GetCppString(), " "); + for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++) { uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2); @@ -1315,7 +1570,9 @@ bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data ) *p_data << uint32(0); continue; } + SpellItemEnchantmentEntry const *enchant = NULL; + uint32 enchants = GetUInt32ValueFromArray(data, visualbase + 1); for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot) { @@ -1323,9 +1580,11 @@ bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data ) uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16); if(!enchantId) continue; + if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))) break; } + *p_data << uint32(proto->DisplayInfoID); *p_data << uint8(proto->InventoryType); *p_data << uint32(enchant ? enchant->aura_id : 0); @@ -1333,22 +1592,30 @@ bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data ) *p_data << uint32(0); // first bag display id *p_data << uint8(0); // first bag inventory type *p_data << uint32(0); // enchant? + return true; } + bool Player::ToggleAFK() { ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK); + bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK); + // afk player not allowed in battleground if(state && InBattleGround()) LeaveBattleground(); + return state; } + bool Player::ToggleDND() { ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND); + return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND); } + uint8 Player::chatTag() const { // it's bitmask @@ -1365,6 +1632,7 @@ uint8 Player::chatTag() const else return 0; } + void Player::SendTeleportAckMsg() { WorldPacket data(MSG_MOVE_TELEPORT_ACK, 41); @@ -1373,16 +1641,21 @@ void Player::SendTeleportAckMsg() BuildMovementPacket(&data); GetSession()->SendPacket(&data); } + // this is not used anywhere void Player::TeleportOutOfMap(Map *oldMap) { while(IsBeingTeleportedFar()) GetSession()->HandleMoveWorldportAckOpcode(); + if(GetMap() != oldMap) return; + TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation()); + while(IsBeingTeleportedFar()) GetSession()->HandleMoveWorldportAckOpcode(); + if(GetMap() == oldMap) { sLog.outCrash("Cannot teleport player out of map!"); @@ -1390,6 +1663,7 @@ void Player::TeleportOutOfMap(Map *oldMap) assert(false); } } + bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options) { if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation)) @@ -1397,33 +1671,43 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid); return false; } + if((GetSession()->GetSecurity() < SEC_GAMEMASTER) && !sWorld.IsAllowedMap(mapid)) { sLog.outError("Player %s tried to enter a forbidden map", GetName()); return false; } + // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later) Pet* pet = GetPet(); + MapEntry const* mEntry = sMapStore.LookupEntry(mapid); + // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)... // don't let gm level > 1 either if(!InBattleGround() && mEntry->IsBattleGroundOrArena()) return false; + // client without expansion support if(GetSession()->Expansion() < mEntry->Expansion()) { sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid); + if(GetTransport()) RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :) + SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion()); + return false; // normal client can't teleport to this map... } else { sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid); } + // reset movement flags at teleport, because player will continue move with these flags after teleport SetUnitMovementFlags(0); + if (m_transport) { if (options & TELE_TO_NOT_LEAVE_TRANSPORT) @@ -1439,6 +1723,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati m_movementInfo.t_time = 0; } } + // The player was ported to another map and looses the duel immediately. // We have to perform this check before the teleport, otherwise the // ObjectAccessor won't find the flag. @@ -1448,6 +1733,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati if (obj) DuelComplete(DUEL_FLED); } + if ((GetMapId() == mapid) && (!m_transport)) { //lets reset far teleport flag if it wasn't reset during chained teleports @@ -1464,17 +1750,21 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati m_teleport_options = options; return true; } + if (!(options & TELE_TO_NOT_UNSUMMON_PET)) { //same map, only remove pet if out of range for new position if(pet && !pet->IsWithinDist3d(x,y,z, OWNER_MAX_DISTANCE)) UnsummonPetTemporaryIfAny(); } + if(!(options & TELE_TO_NOT_LEAVE_COMBAT)) CombatStop(); + // this will be used instead of the current location in SaveToDB m_teleport_dest = WorldLocation(mapid, x, y, z, orientation); SetFallInformation(0, z); + // code for finish transfer called in WorldSession::HandleMovementOpcodes() // at client packet MSG_MOVE_TELEPORT_ACK SetSemaphoreTeleportNear(true); @@ -1493,13 +1783,16 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati if(getClass() == CLASS_DEATH_KNIGHT && GetMapId() == 609 && !isGameMaster() && !HasSpell(SPELL_ID_DEATH_GATE)) return false; + // far teleport to another map Map* oldmap = IsInWorld() ? GetMap() : NULL; // check if we can enter before stopping combat / removing pet / totems / interrupting spells + // Check enter rights before map getting to avoid creating instance copy for player // this check not dependent from map instance copy and same for all instance copies of selected map if (!MapManager::Instance().CanPlayerEnter(mapid, this)) return false; + // If the map is not created, assume it is possible to enter it. // It will be created in the WorldPortAck. Map *map = MapManager::Instance().FindMap(mapid); @@ -1519,9 +1812,13 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati m_teleport_options = options; return true; } + SetSelection(0); + CombatStop(); + ResetContestedPvP(); + // remove player from battleground on far teleport (when changing maps) if(BattleGround const* bg = GetBattleGround()) { @@ -1531,18 +1828,23 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati if(bg->GetMapId() != mapid) LeaveBattleground(false); // don't teleport to entry point } + // remove pet on map change if (pet) UnsummonPetTemporaryIfAny(); + // remove all dyn objects RemoveAllDynObjects(); + // stop spellcasting // not attempt interrupt teleportation spell at caster teleport if(!(options & TELE_TO_SPELL)) if(IsNonMeleeSpellCasted(true)) InterruptNonMeleeSpells(true); + //remove auras before removing from map... RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING); + if(!GetSession()->PlayerLogout()) { // send transfer packets @@ -1553,6 +1855,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati data << m_transport->GetEntry() << GetMapId(); } GetSession()->SendPacket(&data); + data.Initialize(SMSG_NEW_WORLD, (20)); if (m_transport) { @@ -1565,13 +1868,16 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati GetSession()->SendPacket( &data ); SendSavedInstances(); } + // remove from old map now if(oldmap) oldmap->Remove(this, false); + // new final coordinates float final_x = x; float final_y = y; float final_z = z; float final_o = orientation; + if(m_transport) { final_x += m_movementInfo.t_x; @@ -1579,10 +1885,12 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati final_z += m_movementInfo.t_z; final_o += m_movementInfo.t_o; } + m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o); SetFallInformation(0, final_z); // if the player is saved before worldportack (at logout for example) // this will be used instead of the current location in SaveToDB + // move packet sent by client always after far teleport // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet SetSemaphoreTeleportFar(true); @@ -1592,39 +1900,49 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati } return true; } + bool Player::TeleportToBGEntryPoint() { ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE); ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE); return TeleportTo(m_bgData.joinPos); } + void Player::ProcessDelayedOperations() { if(m_DelayedOperations == 0) return; + if(m_DelayedOperations & DELAYED_RESURRECT_PLAYER) { ResurrectPlayer(0.0f, false); + if(GetMaxHealth() > m_resurrectHealth) SetHealth( m_resurrectHealth ); else SetHealth( GetMaxHealth() ); + if(GetMaxPower(POWER_MANA) > m_resurrectMana) SetPower(POWER_MANA, m_resurrectMana ); else SetPower(POWER_MANA, GetMaxPower(POWER_MANA) ); + SetPower(POWER_RAGE, 0 ); SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) ); + SpawnCorpseBones(); } + if(m_DelayedOperations & DELAYED_SAVE_PLAYER) { SaveToDB(); } + if(m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER) { CastSpell(this, SPELL_ID_DESERTER, true); // Deserter } + if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE) { if (m_bgData.mountSpell) @@ -1633,6 +1951,7 @@ void Player::ProcessDelayedOperations() m_bgData.mountSpell = 0; } } + if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE) { if (m_bgData.HasTaxiPath()) @@ -1640,24 +1959,29 @@ void Player::ProcessDelayedOperations() m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]); m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]); m_bgData.ClearTaxiPath(); + ContinueTaxiFlight(); } } + //we have executed ALL delayed ops, so clear the flag m_DelayedOperations = 0; } + void Player::AddToWorld() { ///- Do not add/remove the player from the object storage ///- It will crash when updating the ObjectAccessor ///- The player should only be added when logging in Unit::AddToWorld(); + for(uint8 i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i) { if(m_items[i]) m_items[i]->AddToWorld(); } } + void Player::RemoveFromWorld() { // cleanup @@ -1669,17 +1993,21 @@ void Player::RemoveFromWorld() UnsummonPetTemporaryIfAny(); sOutdoorPvPMgr.HandlePlayerLeaveZone(this, m_zoneUpdateId); } + ///- Do not add/remove the player from the object storage ///- It will crash when updating the ObjectAccessor ///- The player should only be removed when logging out Unit::RemoveFromWorld(); + for(uint8 i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i) { if(m_items[i]) m_items[i]->RemoveFromWorld(); } + for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter) iter->second->RemoveFromWorld(); + if(m_uint32Values) { if(WorldObject *viewpoint = GetViewpoint()) @@ -1689,13 +2017,18 @@ void Player::RemoveFromWorld() } } } + void Player::RegenerateAll() { //if (m_regenTimer <= 500) // return; + m_regenTimerCount += m_regenTimer; + Regenerate( POWER_ENERGY ); + Regenerate( POWER_MANA ); + if(m_regenTimerCount >= 2000) { // Not in combat or they have regeneration @@ -1710,12 +2043,16 @@ void Player::RegenerateAll() Regenerate(POWER_RUNIC_POWER); } } + if(getClass() == CLASS_DEATH_KNIGHT) Regenerate( POWER_RUNE ); + m_regenTimerCount -= 2000; } + m_regenTimer = 0; } + void Player::Regenerate(Powers power) { if(power == POWER_RUNE) @@ -1724,16 +2061,21 @@ void Player::Regenerate(Powers power) if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it... SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec) } + uint32 maxValue = GetMaxPower(power); if(!maxValue) return; + uint32 curValue = GetPower(power); if(curValue == maxValue) return; + // TODO: possible use of miscvalueb instead of amount if (HasAuraTypeWithValue(SPELL_AURA_PREVENT_REGENERATE_POWER, power)) return; + float addvalue = 0.0f; + switch (power) { case POWER_MANA: @@ -1769,6 +2111,7 @@ void Player::Regenerate(Powers power) case POWER_HEALTH: break; } + // Mana regen calculated in Player::UpdateManaRegen() // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras if(power != POWER_MANA) @@ -1778,11 +2121,14 @@ void Player::Regenerate(Powers power) if ((*i)->GetMiscValue() == power) addvalue *= ((*i)->GetAmount() + 100) / 100.0f; } + addvalue += m_powerFraction[power]; uint32 integerValue = (uint32)addvalue; + if (power != POWER_RAGE && power != POWER_RUNIC_POWER) { curValue += integerValue; + if (curValue > maxValue) { curValue = maxValue; @@ -1802,20 +2148,25 @@ void Player::Regenerate(Powers power) { curValue = 0; m_powerFraction[power] = 0; - } + } } if(m_regenTimerCount >= 2000) SetPower(power, curValue); else UpdateUInt32Value(UNIT_FIELD_POWER1 + power, curValue); } + void Player::RegenerateHealth() { uint32 curValue = GetHealth(); uint32 maxValue = GetMaxHealth(); + if (curValue >= maxValue) return; + float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH); + float addvalue = 0.0f; + // polymorphed case if ( IsPolymorphed() ) addvalue = GetMaxHealth()/3; @@ -1831,61 +2182,79 @@ void Player::RegenerateHealth() } else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT)) addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f; + if(!IsStandState()) addvalue *= 1.5; } + // always regeneration bonus (including combat) addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT); + if(addvalue < 0) addvalue = 0; + ModifyHealth(int32(addvalue)); } + bool Player::CanInteractWithNPCs(bool alive) const { if(alive && !isAlive()) return false; if(isInFlight()) return false; + return true; } + Creature* Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask) { // unit checks if (!guid) return NULL; + if(!IsInWorld()) return NULL; + // exist (we need look pets also for some interaction (quest/etc) Creature *unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid); if (!unit) return NULL; + // player check if(!CanInteractWithNPCs(!unit->isSpiritService())) return NULL; + // appropriate npc type if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask )) return NULL; + // alive or spirit healer if(!unit->isAlive() && (!unit->isSpiritService() || isAlive() )) return NULL; + // not allow interaction under control, but allow with own pets if(unit->GetCharmerGUID()) return NULL; + // not enemy if( unit->IsHostileTo(this)) return NULL; + // not unfriendly if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction())) if(factionTemplate->faction) if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction)) if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY) return NULL; + // not too far if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE)) return NULL; + return unit; } + GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const { if(GameObject *go = GetMap()->GetGameObject(guid)) @@ -1908,33 +2277,41 @@ GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes maxdist = INTERACTION_DISTANCE; break; } + if (go->IsWithinDistInMap(this, maxdist)) return go; + sLog.outError("IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go->GetGOInfo()->name, go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this)); } } return NULL; } + bool Player::IsUnderWater() const { return IsInWater() && GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2); } + void Player::SetInWater(bool apply) { if(m_isInWater==apply) return; + //define player in water by opcodes //move player's guid into HateOfflineList of those mobs //which can't swim and move guid back into ThreatList when //on surface. //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water m_isInWater = apply; + // remove auras that need water/land RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER); + getHostilRefManager().updateThreatTables(); } + void Player::SetGameMaster(bool on) { if(on) @@ -1942,15 +2319,19 @@ void Player::SetGameMaster(bool on) m_ExtraFlags |= PLAYER_EXTRA_GM_ON; setFaction(35); SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM); + if (Pet* pet = GetPet()) { pet->setFaction(35); pet->getHostilRefManager().setOnlineOfflineState(false); } + RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP); ResetContestedPvP(); + getHostilRefManager().setOnlineOfflineState(false); CombatStopWithPets(); + SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases } else @@ -1958,29 +2339,37 @@ void Player::SetGameMaster(bool on) // restore phase AuraEffectList const& phases = GetAurasByType(SPELL_AURA_PHASE); SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false); + m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON; setFactionForRace(getRace()); RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM); + if (Pet* pet = GetPet()) { pet->setFaction(getFaction()); pet->getHostilRefManager().setOnlineOfflineState(true); } + // restore FFA PvP Server state if(sWorld.IsFFAPvPRealm()) SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP); + // restore FFA PvP area state, remove not allowed for GM mounts UpdateArea(m_areaUpdateId); + getHostilRefManager().setOnlineOfflineState(true); } + //ObjectAccessor::UpdateVisibilityForPlayer(this); SetToNotify(); } + void Player::SetGMVisible(bool on) { if(on) { m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag + // Reapply stealth/invisibility if active or show if not any if(HasAuraType(SPELL_AURA_MOD_STEALTH)) SetVisibility(VISIBILITY_GROUP_STEALTH); @@ -1992,11 +2381,14 @@ void Player::SetGMVisible(bool on) else { m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag + SetAcceptWhispers(false); SetGameMaster(true); + SetVisibility(VISIBILITY_OFF); } } + bool Player::IsGroupVisibleFor(Player* p) const { switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY)) @@ -2006,12 +2398,14 @@ bool Player::IsGroupVisibleFor(Player* p) const case 2: return GetTeam()==p->GetTeam(); } } + bool Player::IsInSameGroupWith(Player const* p) const { return (p==this || (GetGroup() != NULL && GetGroup() == p->GetGroup() && GetGroup()->SameSubGroup((Player*)this, (Player*)p))); } + ///- If the player is invited, remove him. If the group if then only 1 person, disband the group. /// \todo Shouldn't we also check if there is no other invitees before disbanding the group? void Player::UninviteFromGroup() @@ -2019,7 +2413,9 @@ void Player::UninviteFromGroup() Group* group = GetGroupInvite(); if(!group) return; + group->RemoveInvite(this); + if(group->GetMembersCount() <= 1) // group has just 1 member => disband { if(group->IsCreated()) @@ -2029,9 +2425,11 @@ void Player::UninviteFromGroup() } else group->RemoveAllInvites(); + delete group; } } + void Player::RemoveFromGroup(Group* group, uint64 guid) { if(group) @@ -2045,6 +2443,7 @@ void Player::RemoveFromGroup(Group* group, uint64 guid) } } } + void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP) { WorldPacket data(SMSG_LOG_XPGAIN, 21); @@ -2059,49 +2458,64 @@ void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP) data << uint8(0); // new 2.4.0 GetSession()->SendPacket(&data); } + void Player::GiveXP(uint32 xp, Unit* victim) { if ( xp < 1 ) return; + if(!isAlive()) return; + uint32 level = getLevel(); + // Favored experience increase START uint32 zone = GetZoneId(); float favored_exp_mult = 0; if( (HasAura(32096) || HasAura(32098)) && (zone == 3483 || zone == 3562 || zone == 3836 || zone == 3713 || zone == 3714) ) favored_exp_mult = 0.05; // Thrallmar's Favor and Honor Hold's Favor xp *= (1 + favored_exp_mult); // Favored experience increase END + // XP to money conversion processed in Player::RewardQuest if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)) return; + // XP resting bonus for kill uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0; + SendLogXPGain(xp,victim,rested_bonus_xp); + uint32 curXP = GetUInt32Value(PLAYER_XP); uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP); uint32 newXP = curXP + xp + rested_bonus_xp; + while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) ) { newXP -= nextLvlXP; + if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) ) GiveLevel(level + 1); + level = getLevel(); nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP); } newXP = GetSession()->HandleOnGetXP(newXP); SetUInt32Value(PLAYER_XP, newXP); } + // Update player to next level // Current player experience not update (must be update by caller) void Player::GiveLevel(uint32 level) { if ( level == getLevel() ) return; + PlayerLevelInfo info; objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info); + PlayerClassLevelInfo classInfo; objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo); + // send levelup info to client WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4)); data << uint32(level); @@ -2117,24 +2531,36 @@ void Player::GiveLevel(uint32 level) // end for for(uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4) data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i))); + GetSession()->SendPacket(&data); + SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level)); + //update level, max level of skills m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset + _ApplyAllLevelScaleItemMods(false); + SetLevel(level); + UpdateSkillsForLevel (); + // save base values (bonuses already included in stored stats for(uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) SetCreateStat(Stats(i), info.stats[i]); + SetCreateHealth(classInfo.basehealth); SetCreateMana(classInfo.basemana); + InitTalentForLevel(); InitTaxiNodesForLevel(); InitGlyphsForLevel(); + UpdateAllStats(); + if(sWorld.getConfig(CONFIG_ALWAYS_MAXSKILL)) // Max weapon skill when leveling up UpdateSkillsToMaxSkillsForLevel(); + // set current level health and mana/energy to maximum after applying all mods. SetHealth(GetMaxHealth()); SetPower(POWER_MANA, GetMaxPower(POWER_MANA)); @@ -2143,12 +2569,16 @@ void Player::GiveLevel(uint32 level) SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE)); SetPower(POWER_FOCUS, 0); SetPower(POWER_HAPPINESS, 0); + _ApplyAllLevelScaleItemMods(true); + // update level to hunter/summon pet if (Pet* pet = GetPet()) pet->SynchronizeLevelWithOwner(); + GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL); } + void Player::InitTalentForLevel() { uint32 level = getLevel(); @@ -2169,7 +2599,9 @@ void Player::InitTalentForLevel() m_specsCount = 1; m_activeSpec = 0; } + uint32 talentPointsForLevel = CalculateTalentsPoints(); + // if used more that have then reset if(m_usedTalentCount > talentPointsForLevel) { @@ -2182,37 +2614,53 @@ void Player::InitTalentForLevel() else SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount); } + if(!GetSession()->PlayerLoading()) SendTalentsInfoData(false); // update at client } + void Player::InitStatsForLevel(bool reapplyMods) { if(reapplyMods) //reapply stats values only on .reset stats (level) command _RemoveAllStatBonuses(); + PlayerClassLevelInfo classInfo; objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo); + PlayerLevelInfo info; objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info); + SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) ); SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel())); + UpdateSkillsForLevel (); + // set default cast time multiplier SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); + // reset size before reapply auras SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f); + // save base values (bonuses already included in stored stats for(uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) SetCreateStat(Stats(i), info.stats[i]); + for(uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) SetStat(Stats(i), info.stats[i]); + SetCreateHealth(classInfo.basehealth); + //set create powers SetCreateMana(classInfo.basemana); + SetArmor(int32(m_createStats[STAT_AGILITY]*2)); + InitStatBuffMods(); + //reset rating fields values for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index) SetUInt32Value(index, 0); + SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0); for (uint8 i = 0; i < 7; i++) { @@ -2220,34 +2668,42 @@ void Player::InitStatsForLevel(bool reapplyMods) SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0); SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f); } + //reset attack power, damage and attack speed fields SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f ); SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f ); + SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f ); SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f ); SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f ); SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f ); SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f ); SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f ); + SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 ); SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 ); SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f); SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 ); SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 ); SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f); + // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f); SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f); SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f); + // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset for (uint8 i = 0; i < 7; ++i) SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f); + SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f); SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f); SetUInt32Value(PLAYER_SHIELD_BLOCK, 0); + // Dodge percentage SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f); + // set armor (resistance 0) to original value (create_agility*2) SetArmor(int32(m_createStats[STAT_AGILITY]*2)); SetResistanceBuffMods(SpellSchools(0), true, 0.0f); @@ -2259,6 +2715,7 @@ void Player::InitStatsForLevel(bool reapplyMods) SetResistanceBuffMods(SpellSchools(i), true, 0.0f); SetResistanceBuffMods(SpellSchools(i), false, 0.0f); } + SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0); SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0); for(uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i) @@ -2271,12 +2728,16 @@ void Player::InitStatsForLevel(bool reapplyMods) SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0); // Init data for form but skip reapply item mods for form InitDataForForm(reapplyMods); + // save new stats for (uint8 i = POWER_MANA; i < MAX_POWERS; i++) SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i)))); + SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later + // cleanup mounted state (it will set correctly at aura loading if player saved at mount. SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0); + // cleanup unit flags (will be re-applied if need at aura load). RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 | @@ -2285,15 +2746,21 @@ void Player::InitStatsForLevel(bool reapplyMods) UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT ); SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set + SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set + // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example. RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_ALLOW_ONLY_ABILITY); + RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY); + // restore if need some important flags SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default + if(reapplyMods) //reapply stats values only on .reset stats (level) command _ApplyAllStatBonuses(); + // set current level health and mana/energy to maximum after applying all mods. SetHealth(GetMaxHealth()); SetPower(POWER_MANA, GetMaxPower(POWER_MANA)); @@ -2303,30 +2770,41 @@ void Player::InitStatsForLevel(bool reapplyMods) SetPower(POWER_FOCUS, 0); SetPower(POWER_HAPPINESS, 0); SetPower(POWER_RUNIC_POWER, 0); + // update level to hunter/summon pet if (Pet* pet = GetPet()) pet->SynchronizeLevelWithOwner(); } + void Player::SendInitialSpells() { time_t curTime = time(NULL); time_t infTime = curTime + infinityCooldownDelayCheck; + uint16 spellCount = 0; + WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4))); data << uint8(0); + size_t countPos = data.wpos(); data << uint16(spellCount); // spell count placeholder + for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr) { if(itr->second->state == PLAYERSPELL_REMOVED) continue; + if(!itr->second->active || itr->second->disabled) continue; + data << uint32(itr->first); data << uint16(0); // it's not slot id + spellCount +=1; } + data.put<uint16>(countPos,spellCount); // write real count value + uint16 spellCooldowns = m_spellCooldowns.size(); data << uint16(spellCooldowns); for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr) @@ -2334,9 +2812,12 @@ void Player::SendInitialSpells() SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first); if(!sEntry) continue; + data << uint32(itr->first); + data << uint16(itr->second.itemid); // cast item id data << uint16(sEntry->Category); // spell category + // send infinity cooldown in special format if(itr->second.end >= infTime) { @@ -2344,7 +2825,9 @@ void Player::SendInitialSpells() data << uint32(0x80000000); // category cooldown continue; } + time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILISECONDS : 0; + if(sEntry->Category) // may be wrong, but anyway better than nothing... { data << uint32(0); // cooldown @@ -2356,9 +2839,12 @@ void Player::SendInitialSpells() data << uint32(0); // category cooldown } } + GetSession()->SendPacket(&data); + sLog.outDetail( "CHARACTER: Sent Initial Spells" ); } + void Player::RemoveMail(uint32 id) { for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr) @@ -2371,6 +2857,7 @@ void Player::RemoveMail(uint32 id) } } } + void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count) { WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0)))); @@ -2386,6 +2873,7 @@ void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResp } GetSession()->SendPacket(&data); } + void Player::SendNewMail() { // deliver undelivered mail @@ -2393,6 +2881,7 @@ void Player::SendNewMail() data << (uint32) 0; GetSession()->SendPacket(&data); } + void Player::UpdateNextMailTimeAndUnreads() { // calculate next delivery time (min. from non-delivered mails @@ -2411,6 +2900,7 @@ void Player::UpdateNextMailTimeAndUnreads() ++unReadMails; } } + void Player::AddNewMailDeliverTime(time_t deliver_time) { if(deliver_time <= time(NULL)) // ready now @@ -2424,6 +2914,7 @@ void Player::AddNewMailDeliverTime(time_t deliver_time) m_nextMailDelivereTime = deliver_time; } } + bool Player::AddTalent(uint32 spell_id, uint8 spec, bool learning) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id); @@ -2437,8 +2928,10 @@ bool Player::AddTalent(uint32 spell_id, uint8 spec, bool learning) } else sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id); + return false; } + if(!SpellMgr::IsSpellValid(spellInfo,this,false)) { // do character spell book cleanup (all characters) @@ -2449,8 +2942,10 @@ bool Player::AddTalent(uint32 spell_id, uint8 spec, bool learning) } else sLog.outError("Player::addTalent: Broken spell #%u learning not allowed.",spell_id); + return false; } + PlayerTalentMap::iterator itr = m_talents[spec]->find(spell_id); if (itr != m_talents[spec]->end()) { @@ -2466,6 +2961,7 @@ bool Player::AddTalent(uint32 spell_id, uint8 spec, bool learning) uint32 rankSpellId = talentInfo->RankID[rank]; if(!rankSpellId || rankSpellId == spell_id) continue; + PlayerTalentMap::iterator itr = m_talents[spec]->find(rankSpellId); if (itr != m_talents[spec]->end()) { @@ -2473,15 +2969,19 @@ bool Player::AddTalent(uint32 spell_id, uint8 spec, bool learning) } } } + PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED; PlayerTalent *newtalent = new PlayerTalent(); + newtalent->state = state; newtalent->spec = spec; + (*m_talents[spec])[spell_id] = newtalent; return true; } return false; } + bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id); @@ -2495,8 +2995,10 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen } else sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id); + return false; } + if(!SpellMgr::IsSpellValid(spellInfo,this,false)) { // do character spell book cleanup (all characters) @@ -2507,13 +3009,18 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen } else sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id); + return false; } + PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED; + bool dependent_set = false; bool disabled_case = false; bool superceded_old = false; + PlayerSpellMap::iterator itr = m_spells.find(spell_id); + // Remove temporary spell if found to prevent conflicts if (itr != m_spells.end() && itr->second->state == PLAYERSPELL_TEMPORARY) RemoveTemporarySpell(spell_id); @@ -2533,14 +3040,17 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen } } } + // not do anything if already known in expected state if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active && itr->second->dependent == dependent && itr->second->disabled == disabled) { if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly itr->second->state = PLAYERSPELL_UNCHANGED; + return false; } + // dependent spell known as not dependent, overwrite state if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent) { @@ -2549,14 +3059,17 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen itr->second->state = PLAYERSPELL_CHANGED; dependent_set = true; } + // update active state for known spell if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled) { itr->second->active = active; + if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly itr->second->state = PLAYERSPELL_UNCHANGED; else if(itr->second->state != PLAYERSPELL_NEW) itr->second->state = PLAYERSPELL_CHANGED; + if(active) { if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo)) @@ -2579,15 +3092,19 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen GetSession()->SendPacket(&data); } } + return active; // learn (show in spell book if active now) } + if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED) { if(itr->second->state != PLAYERSPELL_NEW) itr->second->state = PLAYERSPELL_CHANGED; itr->second->disabled = disabled; + if(disabled) return false; + disabled_case = true; } else switch(itr->second->state) @@ -2606,10 +3123,12 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen // can be in case spell loading but learned at some previous spell loading if(!IsInWorld() && !learning && !dependent_set) itr->second->state = PLAYERSPELL_UNCHANGED; + return false; } } } + if(!disabled_case) // skip new spell adding if spell already known (disabled spells case) { // talent: unlearn all other talent ranks (high and low) @@ -2623,6 +3142,7 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen uint32 rankSpellId = talentInfo->RankID[rank]; if(!rankSpellId || rankSpellId == spell_id) continue; + removeSpell(rankSpellId,false,false); } } @@ -2635,11 +3155,13 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen else // at normal learning learnSpell(prev_spell,true); } + PlayerSpell *newspell = new PlayerSpell; newspell->state = state; newspell->active = active; newspell->dependent = dependent; newspell->disabled = disabled; + // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0) { @@ -2648,6 +3170,7 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen if(itr2->second->state == PLAYERSPELL_REMOVED) continue; SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first); if(!i_spellInfo) continue; + if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) ) { if(itr2->second->active) @@ -2661,6 +3184,7 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen data << uint32(spell_id); GetSession()->SendPacket( &data ); } + // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new) itr2->second->active = false; if(itr2->second->state != PLAYERSPELL_NEW) @@ -2676,6 +3200,7 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen data << uint32(itr2->first); GetSession()->SendPacket( &data ); } + // mark new spell as disable (not learned yet for client and will not learned) newspell->active = false; if(newspell->state != PLAYERSPELL_NEW) @@ -2685,12 +3210,16 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen } } } + m_spells[spell_id] = newspell; + // return false if spell disabled if (newspell->disabled) return false; } + uint32 talentCost = GetTalentSpellCost(spell_id); + // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned) // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive if (talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL)) @@ -2709,27 +3238,37 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen CastSpell(this, spell_id, true); return false; } + // update used talent points count m_usedTalentCount += talentCost; + // update free primary prof.points (if any, can be none in case GM .learn prof. learning) if (uint32 freeProfs = GetFreePrimaryProfessionPoints()) { if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id)) SetFreePrimaryProfessions(freeProfs-1); } + // add dependent skills uint16 maxskill = GetMaxSkillValueForLevel(); + SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id); + SkillLineAbilityMapBounds skill_bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id); + if (spellLearnSkill) { uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill); uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill); + if (skill_value < spellLearnSkill->value) skill_value = spellLearnSkill->value; + uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue; + if (skill_max_value < new_skill_max_value) skill_max_value = new_skill_max_value; + SetSkill(spellLearnSkill->skill,skill_value,skill_max_value); } else @@ -2740,8 +3279,10 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId); if (!pSkill) continue; + if (HasSkill(pSkill->id)) continue; + if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL || // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0)) @@ -2763,8 +3304,10 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen } } } + // learn dependent spells SpellLearnSpellMapBounds spell_bounds = spellmgr.GetSpellLearnSpellMapBounds(spell_id); + for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2) { if (!itr2->second.autoLearned) @@ -2775,6 +3318,7 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen learnSpell(itr2->second.spell,true); } } + if (!GetSession()->PlayerLoading()) { // not ranked skills @@ -2783,11 +3327,14 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId); } + GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id); } + // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell return active && !disabled && !superceded_old; } + void Player::AddTemporarySpell(uint32 spellId) { PlayerSpellMap::iterator itr = m_spells.find(spellId); @@ -2801,6 +3348,7 @@ void Player::AddTemporarySpell(uint32 spellId) newspell->disabled = false; m_spells[spellId] = newspell; } + void Player::RemoveTemporarySpell(uint32 spellId) { PlayerSpellMap::iterator itr = m_spells.find(spellId); @@ -2813,20 +3361,26 @@ void Player::RemoveTemporarySpell(uint32 spellId) delete itr->second; m_spells.erase(itr); } + bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const { // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell // talent dependent passives activated at form apply have proper stance data bool need_cast = (!spellInfo->Stances || (m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))))); + //Check CasterAuraStates return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState))); } + void Player::learnSpell(uint32 spell_id, bool dependent) { PlayerSpellMap::iterator itr = m_spells.find(spell_id); + bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false; bool active = disabled ? itr->second->active : true; + bool learning = addSpell(spell_id,active,true,dependent,false); + // learn all disabled higher ranks (recursive) if(disabled) { @@ -2838,20 +3392,25 @@ void Player::learnSpell(uint32 spell_id, bool dependent) learnSpell(node->next,false); } } + // prevent duplicated entires in spell book, also not send if not in world (loading) if(!learning || !IsInWorld ()) return; + WorldPacket data(SMSG_LEARNED_SPELL, 4); data << uint32(spell_id); GetSession()->SendPacket(&data); } + void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank) { PlayerSpellMap::iterator itr = m_spells.find(spell_id); if (itr == m_spells.end()) return; + if (itr->second->state == PLAYERSPELL_REMOVED || (disabled && itr->second->disabled) || itr->second->state == PLAYERSPELL_TEMPORARY) return; + // unlearn non talent higher ranks (recursive) SpellChainNode const* node = spellmgr.GetSpellChainNode(spell_id); if (node) @@ -2864,12 +3423,15 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank) SpellsRequiringSpellMap::const_iterator itr2 = reqMap.find(spell_id); for (uint32 i=reqMap.count(spell_id);i>0;i--,itr2++) removeSpell(itr2->second,disabled,false); + // re-search, it can be corrupted in prev loop itr = m_spells.find(spell_id); if (itr == m_spells.end()) return; // already unleared + bool cur_active = itr->second->active; bool cur_dependent = itr->second->dependent; + if (disabled) { itr->second->disabled = disabled; @@ -2886,11 +3448,14 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank) else itr->second->state = PLAYERSPELL_REMOVED; } + RemoveAurasDueToSpell(spell_id); + // remove pet auras for(int i = 0; i < MAX_SPELL_EFFECTS; ++i) if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id, i)) RemovePetAura(petSpell); + // free talent points uint32 talentCosts = GetTalentSpellCost(spell_id); if(talentCosts > 0) @@ -2900,6 +3465,7 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank) else m_usedTalentCount = 0; } + // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning) if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id)) { @@ -2907,6 +3473,7 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank) if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL)) SetFreePrimaryProfessions(freeProfs); } + // remove dependent skill SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id); if(spellLearnSkill) @@ -2923,30 +3490,38 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank) prev_spell = spellmgr.GetPrevSpellInChain(prev_spell); prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell)); } + if (!prevSkill) // not found prev skill setting, remove skill SetSkill(spellLearnSkill->skill,0,0); else // set to prev. skill setting values { uint32 skill_value = GetPureSkillValue(prevSkill->skill); uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill); + if (skill_value > prevSkill->value) skill_value = prevSkill->value; + uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue; + if (skill_max_value > new_skill_max_value) skill_max_value = new_skill_max_value; + SetSkill(prevSkill->skill,skill_value,skill_max_value); } } + } else { // not ranked skills SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id); + for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx) { SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId); if (!pSkill) continue; + if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL && pSkill->categoryId != SKILL_CATEGORY_CLASS ||// not unlearn class skills (spellbook/talent pages) // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL @@ -2956,19 +3531,25 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank) if ((pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) && (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0)) continue; + SetSkill(pSkill->id, 0, 0 ); } } } + // remove dependent spells SpellLearnSpellMapBounds spell_bounds = spellmgr.GetSpellLearnSpellMapBounds(spell_id); + for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2) removeSpell(itr2->second.spell, disabled); + // activate lesser rank in spellbook/action bar, and cast it if need bool prev_activate = false; + if (uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id)) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id); + // if talent then lesser rank also talent and need learn if (talentCosts) { @@ -2989,6 +3570,7 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank) if (prev_itr->second->state != PLAYERSPELL_NEW) prev_itr->second->state = PLAYERSPELL_CHANGED; } + // now re-learn if need re-activate if (cur_active && !prev_itr->second->active && learn_low_rank) { @@ -3005,10 +3587,13 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank) } } } + if(spell_id == 46917 && m_canTitanGrip) SetCanTitanGrip(false); + if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_SPELL_UNLEARN)) AutoUnequipOffhandIfNeed(); + // remove from spell book if not replaced by lesser rank if(!prev_activate) { @@ -3017,12 +3602,15 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank) GetSession()->SendPacket(&data); } } + void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ ) { m_spellCooldowns.erase(spell_id); + if(update) SendClearCooldown(spell_id, this); } + // I am not sure which one is more efficient void Player::RemoveCategoryCooldown( uint32 cat ) { @@ -3031,11 +3619,13 @@ void Player::RemoveCategoryCooldown( uint32 cat ) for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset) RemoveSpellCooldown(*i_scset, true); } + void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */) { SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat); if (ct == sSpellCategoryStore.end()) return; + const SpellCategorySet& ct_set = ct->second; for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();) { @@ -3045,6 +3635,7 @@ void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */) ++i; } } + void Player::RemoveArenaSpellCooldowns() { // remove cooldowns on spells that has < 15 min CD @@ -3065,48 +3656,63 @@ void Player::RemoveArenaSpellCooldowns() } } } + void Player::RemoveAllSpellCooldown() { if(!m_spellCooldowns.empty()) { for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr) SendClearCooldown(itr->first, this); + m_spellCooldowns.clear(); } } + void Player::_LoadSpellCooldowns(QueryResult *result) { // some cooldowns can be already set at aura loading... + //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow()); + if(result) { time_t curTime = time(NULL); + do { Field *fields = result->Fetch(); + uint32 spell_id = fields[0].GetUInt32(); uint32 item_id = fields[1].GetUInt32(); time_t db_time = (time_t)fields[2].GetUInt64(); + if(!sSpellStore.LookupEntry(spell_id)) { sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id); continue; } + // skip outdated cooldown if(db_time <= curTime) continue; + AddSpellCooldown(spell_id, item_id, db_time); + sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime)); } while( result->NextRow() ); + delete result; } } + void Player::_SaveSpellCooldowns() { CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow()); + time_t curTime = time(NULL); time_t infTime = curTime + infinityCooldownDelayCheck; + // remove outdated and save active for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();) { @@ -3121,6 +3727,7 @@ void Player::_SaveSpellCooldowns() ++itr; } } + uint32 Player::resetTalentsCost() const { // The first time reset costs 1 gold @@ -3153,39 +3760,51 @@ uint32 Player::resetTalentsCost() const } } } + bool Player::resetTalents(bool no_cost) { // not need after this call if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS)) RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true); + uint32 talentPointsForLevel = CalculateTalentsPoints(); + if (m_usedTalentCount == 0) { SetFreeTalentPoints(talentPointsForLevel); return false; } + uint32 cost = 0; + if(!no_cost && !sWorld.getConfig(CONFIG_NO_RESET_TALENT_COST)) { cost = resetTalentsCost(); + if (GetMoney() < cost) { SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0); return false; } } + for (uint32 i = 0; i < sTalentStore.GetNumRows(); i++) { TalentEntry const *talentInfo = sTalentStore.LookupEntry(i); + if (!talentInfo) continue; + TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab ); + if(!talentTabInfo) continue; + // unlearn only talents for character class // some spell learned by one class as normal spells or know at creation but another class learn it as talent, // to prevent unexpected lost normal learned spell skip another class talents if( (getClassMask() & talentTabInfo->ClassMask) == 0 ) continue; + // Re-use pre-dual talent way of resetting talents, to ensure talents aren't being stored in spell storage. for(uint8 rank = 0; rank < MAX_TALENT_RANK; ++rank) { @@ -3196,8 +3815,10 @@ bool Player::resetTalents(bool no_cost) ++itr; continue; } + // remove learned spells (all ranks) uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first); + // unlearn if first rank is talent or learned by talent if (itrFirstId == talentInfo->RankID[rank]) { @@ -3215,21 +3836,26 @@ bool Player::resetTalents(bool no_cost) ++itr; } } + for (PlayerTalentMap::iterator itr2 = m_talents[m_activeSpec]->begin(); itr2 != m_talents[m_activeSpec]->end(); ++itr2) { removeSpell(itr2->first, !IsPassiveSpell(itr2->first),false); itr2->second->state = PLAYERSPELL_REMOVED; } } + SetFreeTalentPoints(talentPointsForLevel); + if(!no_cost) { ModifyMoney(-(int32)cost); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1); + m_resetTalentsCost = cost; m_resetTalentsTime = time(NULL); } + //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true); /* when prev line will dropped use next line @@ -3239,8 +3865,10 @@ bool Player::resetTalents(bool no_cost) RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true); } */ + return true; } + Mail* Player::GetMail(uint32 id) { for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr) @@ -3252,6 +3880,7 @@ Mail* Player::GetMail(uint32 id) } return NULL; } + void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const { if(target == this) @@ -3267,6 +3896,7 @@ void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const } } } + void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const { if(target == this) @@ -3279,9 +3909,11 @@ void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const *updateMask &= updateVisualBits; } } + void Player::InitVisibleBits() { updateVisualBits.SetCount(PLAYER_END); + updateVisualBits.SetBit(OBJECT_FIELD_GUID); updateVisualBits.SetBit(OBJECT_FIELD_TYPE); updateVisualBits.SetBit(OBJECT_FIELD_ENTRY); @@ -3337,6 +3969,7 @@ void Player::InitVisibleBits() updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA); updateVisualBits.SetBit(UNIT_FIELD_BYTES_2); updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT); + updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0); updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1); updateVisualBits.SetBit(PLAYER_FLAGS); @@ -3347,134 +3980,169 @@ void Player::InitVisibleBits() updateVisualBits.SetBit(PLAYER_BYTES_3); updateVisualBits.SetBit(PLAYER_DUEL_TEAM); updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP); + // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)... for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4) updateVisualBits.SetBit(i); + // Players visible items are not inventory stuff for(uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i) { uint16 offset = i * 2; + // item entry updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset); // enchant updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset); } + updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE); } + void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const { for(uint8 i = 0; i < EQUIPMENT_SLOT_END; i++) { if(m_items[i] == NULL) continue; + m_items[i]->BuildCreateUpdateBlockForPlayer( data, target ); } + if(target == this) { for(uint8 i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++) { if(m_items[i] == NULL) continue; + m_items[i]->BuildCreateUpdateBlockForPlayer( data, target ); } for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) { if(m_items[i] == NULL) continue; + m_items[i]->BuildCreateUpdateBlockForPlayer( data, target ); } } + Unit::BuildCreateUpdateBlockForPlayer( data, target ); } + void Player::DestroyForPlayer( Player *target, bool anim ) const { Unit::DestroyForPlayer( target, anim ); + for(uint8 i = 0; i < INVENTORY_SLOT_BAG_END; i++) { if(m_items[i] == NULL) continue; + m_items[i]->DestroyForPlayer( target ); } + if(target == this) { for(uint8 i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++) { if(m_items[i] == NULL) continue; + m_items[i]->DestroyForPlayer( target ); } for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) { if(m_items[i] == NULL) continue; + m_items[i]->DestroyForPlayer( target ); } } } + bool Player::HasSpell(uint32 spell) const { PlayerSpellMap::const_iterator itr = m_spells.find(spell); return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled); } + bool Player::HasTalent(uint32 spell, uint8 spec) const { PlayerTalentMap::const_iterator itr = m_talents[spec]->find(spell); return (itr != m_talents[spec]->end() && itr->second->state != PLAYERSPELL_REMOVED); } + bool Player::HasActiveSpell(uint32 spell) const { PlayerSpellMap::const_iterator itr = m_spells.find(spell); return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && itr->second->active && !itr->second->disabled); } + TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const { if (!trainer_spell) return TRAINER_SPELL_RED; + if (!trainer_spell->learnedSpell) return TRAINER_SPELL_RED; + // known spell if(HasSpell(trainer_spell->learnedSpell)) return TRAINER_SPELL_GRAY; + // check race/class requirement if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell)) return TRAINER_SPELL_RED; + // check level requirement if(getLevel() < trainer_spell->reqLevel) return TRAINER_SPELL_RED; + if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell)) { // check prev.rank requirement if(spell_chain->prev && !HasSpell(spell_chain->prev)) return TRAINER_SPELL_RED; } + if(uint32 spell_req = spellmgr.GetSpellRequired(trainer_spell->spell)) { // check additional spell requirement if(!HasSpell(spell_req)) return TRAINER_SPELL_RED; } + // check skill requirement if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue) return TRAINER_SPELL_RED; + // exist, already checked at loading SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell); + // secondary prof. or not prof. spell uint32 skill = spell->EffectMiscValue[1]; + if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill)) return TRAINER_SPELL_GREEN; + // check primary prof. limit if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0) return TRAINER_SPELL_GREEN_DISABLED; + return TRAINER_SPELL_GREEN; } + void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars) { uint32 guid = GUID_LOPART(playerguid); + // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry) // bones will be deleted by corpse/bones deleting thread shortly ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid); + // remove from guild uint32 guildId = GetGuildIdFromDB(playerguid); if(guildId != 0) @@ -3483,8 +4151,10 @@ void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmC if(guild) guild->DelMember(guid); } + // remove from arena teams LeaveAllArenaTeams(playerguid); + // the player was uninvited already on logout so just remove from group QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid); if(resultGroup) @@ -3497,8 +4167,10 @@ void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmC RemoveFromGroup(group, playerguid); } } + // remove signs from petitions (also remove petitions if owner); RemovePetitionsAndSigns(playerguid, 10); + // return back all mails with COD and Item 0 1 2 3 4 5 6 QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,mailTemplateId,sender,subject,itemTextId,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid); if(resultMail) @@ -3506,6 +4178,7 @@ void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmC do { Field *fields = resultMail->Fetch(); + uint32 mail_id = fields[0].GetUInt32(); uint16 mailTemplateId= fields[1].GetUInt16(); uint32 sender = fields[2].GetUInt32(); @@ -3513,9 +4186,11 @@ void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmC uint32 itemTextId = fields[4].GetUInt32(); uint32 money = fields[5].GetUInt32(); bool has_items = fields[6].GetBool(); + //we can return mail now //so firstly delete the old one CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id); + MailItemsInfo mi; if(has_items) { @@ -3526,14 +4201,17 @@ void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmC do { Field *fields2 = resultItems->Fetch(); + uint32 item_guidlow = fields2[1].GetUInt32(); uint32 item_template = fields2[2].GetUInt32(); + ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template); if(!itemProto) { CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow); continue; } + Item *pItem = NewItemOrBag(itemProto); if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems)) { @@ -3541,22 +4219,30 @@ void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmC pItem->SaveToDB(); // it also deletes item object ! continue; } + mi.AddItem(item_guidlow, item_template, pItem); } while (resultItems->NextRow()); + delete resultItems; } } + CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id); + uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)); + WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId); } while (resultMail->NextRow()); + delete resultMail; } + // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet. // Get guids of character's pets, will deleted in transaction QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid); + // NOW we can finally clear other DB data related to character CharacterDatabase.BeginTransaction(); if (resultPets) @@ -3569,6 +4255,7 @@ void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmC } while (resultPets->NextRow()); delete resultPets; } + CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid); CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid); CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid); @@ -3597,9 +4284,11 @@ void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmC CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid); CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid); CharacterDatabase.CommitTransaction(); + //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID); if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId); } + void Player::SetMovement(PlayerMovementType pType) { WorldPacket data; @@ -3617,6 +4306,7 @@ void Player::SetMovement(PlayerMovementType pType) data << uint32(0); GetSession()->SendPacket( &data ); } + /* Preconditions: - a resurrectable corpse must not be loaded for the player (only bones) - the player must be in world @@ -3626,18 +4316,22 @@ void Player::BuildPlayerRepop() WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size()); data.append(GetPackGUID()); GetSession()->SendPacket(&data); + if(getRace() == RACE_NIGHTELF) CastSpell(this, SPELL_ID_NE_GHOST, true); CastSpell(this, SPELL_ID_GHOST, true); + // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK // there must be SMSG.STOP_MIRROR_TIMER // there we must send 888 opcode + // the player cannot have a corpse already, only bones which are not returned by GetCorpse if(GetCorpse()) { sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow()); assert(false); } + // create a corpse and place it at the player's location CreateCorpse(); Corpse *corpse = GetCorpse(); @@ -3647,21 +4341,30 @@ void Player::BuildPlayerRepop() return; } GetMap()->Add(corpse); + // convert player body to ghost SetHealth( 1 ); + SetMovement(MOVE_WATER_WALK); if(!GetSession()->isLogingOut()) SetMovement(MOVE_UNROOT); + // BG - remove insignia related RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); + // SendCorpseReclaimDelay(); + // to prevent cheating corpse->ResetGhostTime(); + StopMirrorTimers(); //disable timers(bars) + SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player? + // set and clear other SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND); } + void Player::SendDelayResponse(const uint32 ml_seconds) { //FIXME: is this delay time arg really need? 50msec by default in code @@ -3670,6 +4373,7 @@ void Player::SendDelayResponse(const uint32 ml_seconds) data << (uint32)0; GetSession()->SendPacket( &data ); } + void Player::ResurrectPlayer(float restore_percent, bool applySickness) { WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position @@ -3678,16 +4382,22 @@ void Player::ResurrectPlayer(float restore_percent, bool applySickness) data << float(0); data << float(0); GetSession()->SendPacket(&data); + // speed change, land walk + // remove death flag + set aura SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00); if(getRace() == RACE_NIGHTELF) RemoveAurasDueToSpell(SPELL_ID_NE_GHOST); // speed bonuses RemoveAurasDueToSpell(SPELL_ID_GHOST); // SPELL_AURA_GHOST + setDeathState(ALIVE); + SetMovement(MOVE_LAND_WALK); SetMovement(MOVE_UNROOT); + m_deathTimer = 0; + // set health/powers (0- will be set in caller) if(restore_percent>0.0f) { @@ -3696,28 +4406,35 @@ void Player::ResurrectPlayer(float restore_percent, bool applySickness) SetPower(POWER_RAGE, 0); SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent)); } + // trigger update zone for alive state zone updates uint32 newzone, newarea; GetZoneAndAreaId(newzone,newarea); UpdateZone(newzone,newarea); + // update visibility //ObjectAccessor::UpdateVisibilityForPlayer(this); SetToNotify(); + if(!applySickness) return; + //Characters from level 1-10 are not affected by resurrection sickness. //Characters from level 11-19 will suffer from one minute of sickness //for each level they are above 10. //Characters level 20 and up suffer from ten minutes of sickness. int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL); + if(int32(getLevel()) >= startLevel) { // set resurrection sickness CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true); + // not full duration if(int32(getLevel()) < startLevel+9) { int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE; + if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS, GetGUID())) { Aur->SetAuraDuration(delta*IN_MILISECONDS); @@ -3725,6 +4442,7 @@ void Player::ResurrectPlayer(float restore_percent, bool applySickness) } } } + /** * FallMode = 0 implies that the player is dying, or already dead, and the proper death state will be set. * = 1 simply causes the player to plummet towards the ground, and not suffer any damage. @@ -3736,13 +4454,16 @@ bool Player::FallGround(uint8 FallMode) // Let's abort after we called this function one time if (getDeathState() == DEAD_FALLING && FallMode == 0) return false; + float x, y, z; GetPosition(x, y, z); float ground_Z = GetMap()->GetVmapHeight(x, y, z, true); float z_diff = 0.0f; if ((z_diff = fabs(ground_Z - z)) < 0.1f) return false; + GetMotionMaster()->MoveFall(ground_Z, EVENT_FALL_GROUND); + // Below formula for falling damage is from Player::HandleFall if(FallMode == 2 && z_diff >= 14.57f) { @@ -3753,48 +4474,66 @@ bool Player::FallGround(uint8 FallMode) Unit::setDeathState(DEAD_FALLING); return true; } + void Player::KillPlayer() { if(IsFlying() && !GetTransport()) FallGround(); + SetMovement(MOVE_ROOT); + StopMirrorTimers(); //disable timers(bars) + setDeathState(CORPSE); //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP ); + SetFlag(UNIT_DYNAMIC_FLAGS, 0x00); ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable()); + // 6 minutes until repop at graveyard m_deathTimer = 6*MINUTE*IN_MILISECONDS; + UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill SendCorpseReclaimDelay(); + // don't create corpse at this moment, player might be falling + // update visibility ObjectAccessor::UpdateObjectVisibility(this); } + void Player::CreateCorpse() { // prevent existence 2 corpse for player SpawnCorpseBones(); + uint32 _uf, _pb, _pb2, _cfb1, _cfb2; + Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE ); SetPvPDeath(false); + if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this)) { delete corpse; return; } + _uf = GetUInt32Value(UNIT_FIELD_BYTES_0); _pb = GetUInt32Value(PLAYER_BYTES); _pb2 = GetUInt32Value(PLAYER_BYTES_2); + uint8 race = (uint8)(_uf); uint8 skin = (uint8)(_pb); uint8 face = (uint8)(_pb >> 8); uint8 hairstyle = (uint8)(_pb >> 16); uint8 haircolor = (uint8)(_pb >> 24); uint8 facialhair = (uint8)(_pb2); + _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24)); _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24)); + corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 ); corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 ); + uint32 flags = CORPSE_FLAG_UNK2; if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM)) flags |= CORPSE_FLAG_HIDE_HELM; @@ -3803,8 +4542,11 @@ void Player::CreateCorpse() if(InBattleGround() && !InArena()) flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags ); + corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() ); + corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() ); + uint32 iDisplayID; uint16 iIventoryType; uint32 _cfi; @@ -3814,41 +4556,51 @@ void Player::CreateCorpse() { iDisplayID = m_items[i]->GetProto()->DisplayInfoID; iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType; + _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24; corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi); } } + // we don't SaveToDB for players in battlegrounds so don't do it for corpses either const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId()); assert(entry); if(entry->map_type != MAP_BATTLEGROUND) corpse->SaveToDB(); + // register for player, but not show ObjectAccessor::Instance().AddCorpse(corpse); } + void Player::SpawnCorpseBones() { if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID())) SaveToDB(); // prevent loading as ghost without corpse } + Corpse* Player::GetCorpse() const { return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID()); } + void Player::DurabilityLossAll(double percent, bool inventory) { for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++) if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) DurabilityLoss(pItem,percent); + if(inventory) { // bags not have durability // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) + for(uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++) if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) DurabilityLoss(pItem,percent); + // keys not have durability //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++) + for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) for(uint32 j = 0; j < pBag->GetBagSize(); j++) @@ -3856,32 +4608,43 @@ void Player::DurabilityLossAll(double percent, bool inventory) DurabilityLoss(pItem,percent); } } + void Player::DurabilityLoss(Item* item, double percent) { if(!item ) return; + uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY); + if(!pMaxDurability) return; + uint32 pDurabilityLoss = uint32(pMaxDurability*percent); + if(pDurabilityLoss < 1 ) pDurabilityLoss = 1; + DurabilityPointsLoss(item,pDurabilityLoss); } + void Player::DurabilityPointsLossAll(int32 points, bool inventory) { for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++) if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) DurabilityPointsLoss(pItem,points); + if(inventory) { // bags not have durability // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) + for(uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++) if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) DurabilityPointsLoss(pItem,points); + // keys not have durability //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++) + for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) for(uint32 j = 0; j < pBag->GetBagSize(); j++) @@ -3889,67 +4652,84 @@ void Player::DurabilityPointsLossAll(int32 points, bool inventory) DurabilityPointsLoss(pItem,points); } } + void Player::DurabilityPointsLoss(Item* item, int32 points) { int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY); int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY); int32 pNewDurability = pOldDurability - points; + if (pNewDurability < 0) pNewDurability = 0; else if (pNewDurability > pMaxDurability) pNewDurability = pMaxDurability; + if (pOldDurability != pNewDurability) { // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped()) _ApplyItemMods(item,item->GetSlot(), false); + item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability); + // modify item stats _after_ restore durability to pass _ApplyItemMods internal check if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped()) _ApplyItemMods(item,item->GetSlot(), true); + item->SetState(ITEM_CHANGED, this); } } + void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot) { if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot )) DurabilityPointsLoss(pItem,1); } + uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank) { uint32 TotalCost = 0; // equipped, backpack, bags itself for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++) TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank); + // bank, buyback and keys not repaired + // items in inventory bags for(uint8 j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++) for(uint8 i = 0; i < MAX_BAG_SIZE; i++) TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank); return TotalCost; } + uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank) { Item* item = GetItemByPos(pos); + uint32 TotalCost = 0; if(!item) return TotalCost; + uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY); if(!maxDurability) return TotalCost; + uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY); + if(cost) { uint32 LostDurability = maxDurability - curDurability; if(LostDurability>0) { ItemPrototype const *ditemProto = item->GetProto(); + DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel); if(!dcost) { sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel); return TotalCost; } + uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2; DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId); if(!dQualitymodEntry) @@ -3957,11 +4737,15 @@ uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool g sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId); return TotalCost; } + uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)]; uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod)); + costs = uint32(costs * discountMod) * sWorld.getRate(RATE_REPAIRCOST); + if (costs==0) //fix for ITEM_QUALITY_ARTIFACT costs = 1; + if (guildBank) { if (GetGuildId()==0) @@ -3969,24 +4753,29 @@ uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool g DEBUG_LOG("You are not member of a guild"); return TotalCost; } + Guild *pGuild = objmgr.GetGuildById(GetGuildId()); if (!pGuild) return TotalCost; + if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR)) { DEBUG_LOG("You do not have rights to withdraw for repairs"); return TotalCost; } + if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs) { DEBUG_LOG("You do not have enough money withdraw amount remaining"); return TotalCost; } + if (pGuild->GetGuildBankMoney() < costs) { DEBUG_LOG("There is not enough money in bank"); return TotalCost; } + pGuild->MemberMoneyWithdraw(costs, GetGUIDLow()); TotalCost = costs; } @@ -3999,32 +4788,41 @@ uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool g ModifyMoney( -int32(costs) ); } } + item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability); item->SetState(ITEM_CHANGED, this); + // reapply mods for total broken and repaired item if equipped if(IsEquipmentPos(pos) && !curDurability) _ApplyItemMods(item,pos & 255, true); return TotalCost; } + void Player::RepopAtGraveyard() { // note: this can be called also when the player is alive // for example from WorldSession::HandleMovementOpcodes + AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId()); + // Such zones are considered unreachable as a ghost and the player must be automatically revived if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport() || GetPositionZ() < -500.0f) { ResurrectPlayer(0.5f); SpawnCorpseBones(); } + WorldSafeLocsEntry const *ClosestGrave = NULL; + // Special handle for battleground maps if( BattleGround *bg = GetBattleGround() ) ClosestGrave = bg->GetClosestGraveYard(this); else ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() ); + // stop countdown until repop m_deathTimer = 0; + // if no grave found, stay at the current location // and don't show spirit healer location if(ClosestGrave) @@ -4043,14 +4841,17 @@ void Player::RepopAtGraveyard() else if(GetPositionZ() < -500.0f) TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation()); } + void Player::JoinedChannel(Channel *c) { m_channels.push_back(c); } + void Player::LeftChannel(Channel *c) { m_channels.remove(c); } + void Player::CleanupChannels() { while(!m_channels.empty()) @@ -4060,38 +4861,50 @@ void Player::CleanupChannels() ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list if (ChannelMgr* cMgr = channelMgr(GetTeam())) cMgr->LeftChannel(ch->GetName()); // deleted channel if empty + } sLog.outDebug("Player: channels cleaned up!"); } + void Player::UpdateLocalChannels(uint32 newZone ) { if(m_channels.empty()) return; + AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone); if(!current_zone) return; + ChannelMgr* cMgr = channelMgr(GetTeam()); if(!cMgr) return; + std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()]; + for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next) { next = i; ++next; + // skip non built-in channels if(!(*i)->IsConstant()) continue; + ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId()); if(!ch) continue; + if((ch->flags & 4) == 4) // global channel without zone name in pattern continue; + // new channel char new_channel_name_buf[100]; snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str()); Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID); + if((*i)!=new_channel) { new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name + // leave old channel (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel @@ -4101,6 +4914,7 @@ void Player::UpdateLocalChannels(uint32 newZone ) } sLog.outDebug("Player: channels cleaned up!"); } + void Player::LeaveLFGChannel() { for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i ) @@ -4112,15 +4926,18 @@ void Player::LeaveLFGChannel() } } } + void Player::UpdateDefense() { uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE); + if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain)) { // update dependent from defense skill part UpdateDefenseBonusesMod(); } } + void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply) { if(modGroup >= BASEMOD_END || modType >= MOD_END) @@ -4128,7 +4945,9 @@ void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, floa sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!"); return; } + float val = 1.0f; + switch(modType) { case FLAT_MOD: @@ -4137,12 +4956,15 @@ void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, floa case PCT_MOD: if(amount <= -100.0f) amount = -200.0f; + val = (100.0f + amount) / 100.0f; m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val); break; } + if(!CanModifyStats()) return; + switch(modGroup) { case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break; @@ -4152,6 +4974,7 @@ void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, floa default: break; } } + float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const { if(modGroup >= BASEMOD_END || modType > MOD_END) @@ -4159,10 +4982,13 @@ float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!"); return 0.0f; } + if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f) return 0.0f; + return m_auraBaseMod[modGroup][modType]; } + float Player::GetTotalBaseModValue(BaseModGroup modGroup) const { if(modGroup >= BASEMOD_END) @@ -4170,28 +4996,38 @@ float Player::GetTotalBaseModValue(BaseModGroup modGroup) const sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!"); return 0.0f; } + if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f) return 0.0f; + return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD]; } + uint32 Player::GetShieldBlockValue() const { float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD]; + value = (value < 0) ? 0 : value; + return uint32(value); } + float Player::GetMeleeCritFromAgility() { uint32 level = getLevel(); uint32 pclass = getClass(); + if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL; + GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1); GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); if (critBase==NULL || critRatio==NULL) return 0.0f; + float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio; return crit*100.0f; } + float Player::GetDodgeFromAgility() { // Table for base dodge values @@ -4222,53 +5058,69 @@ float Player::GetDodgeFromAgility() 0.0f, // ?? 1.7f // Druid }; + uint32 level = getLevel(); uint32 pclass = getClass(); + if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL; + // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier) GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); if (dodgeRatio==NULL || pclass > MAX_CLASSES) return 0.0f; + float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1]; return dodge*100.0f; } + float Player::GetSpellCritFromIntellect() { uint32 level = getLevel(); uint32 pclass = getClass(); + if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL; + GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1); GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); if (critBase==NULL || critRatio==NULL) return 0.0f; + float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio; return crit*100.0f; } + float Player::GetRatingCoefficient(CombatRating cr) const { uint32 level = getLevel(); + if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL; + GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1); if (Rating == NULL) return 1.0f; // By default use minimum coefficient (not must be called) + return Rating->ratio; } + float Player::GetRatingBonusValue(CombatRating cr) const { return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr); } + uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const { float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f; if (melee>33.0f) melee = 33.0f; return uint32 (melee * damage /100.0f); } + uint32 Player::GetRangedCritDamageReduction(uint32 damage) const { float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f; if (ranged>33.0f) ranged=33.0f; return uint32 (ranged * damage /100.0f); } + uint32 Player::GetSpellCritDamageReduction(uint32 damage) const { float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f; @@ -4277,6 +5129,7 @@ uint32 Player::GetSpellCritDamageReduction(uint32 damage) const spell = 33.0f; return uint32 (spell * damage / 100.0f); } + uint32 Player::GetDotDamageReduction(uint32 damage) const { float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL); @@ -4285,6 +5138,7 @@ uint32 Player::GetDotDamageReduction(uint32 damage) const spellDot = 100.0f; return uint32 (spellDot * damage / 100.0f); } + float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const { switch (attType) @@ -4298,15 +5152,19 @@ float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const } return 0.0f; } + float Player::OCTRegenHPPerSpirit() { uint32 level = getLevel(); uint32 pclass = getClass(); + if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL; + GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); if (baseRatio==NULL || moreRatio==NULL) return 0.0f; + // Formula from PaperDollFrame script float spirit = GetStat(STAT_SPIRIT); float baseSpirit = spirit; @@ -4315,23 +5173,29 @@ float Player::OCTRegenHPPerSpirit() float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio; return regen; } + float Player::OCTRegenMPPerSpirit() { uint32 level = getLevel(); uint32 pclass = getClass(); + if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL; + // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); if (moreRatio==NULL) return 0.0f; + // Formula get from PaperDollFrame script float spirit = GetStat(STAT_SPIRIT); float regen = spirit * moreRatio->ratio; return regen; } + void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply) { m_baseRatingValue[cr]+=(apply ? value : -value); + int32 amount = uint32(m_baseRatingValue[cr]); // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT // stat used stored in miscValueB for this aura @@ -4342,9 +5206,12 @@ void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply) if (amount < 0) amount = 0; SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount)); + float RatingCoeffecient = GetRatingCoefficient(cr); float RatingChange = 0.0f; + bool affectStats = CanModifyStats(); + switch (cr) { case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst @@ -4424,6 +5291,7 @@ void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply) break; } } + void Player::SetRegularAttackTime() { for(uint8 i = 0; i < MAX_ATTACK; ++i) @@ -4439,33 +5307,42 @@ void Player::SetRegularAttackTime() } } } + //skill+step, checking for max value bool Player::UpdateSkill(uint32 skill_id, uint32 step) { if(!skill_id) return false; + uint16 i=0; for (; i < PLAYER_MAX_SKILLS; i++) if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id) break; + if(i>=PLAYER_MAX_SKILLS) return false; + uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)); uint32 value = SKILL_VALUE(data); uint32 max = SKILL_MAX(data); + if ((!max) || (!value) || (value >= max)) return false; + if (value < max) { uint32 new_value = value+step; if(new_value > max) new_value = max; + SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max)); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id); return true; } + return false; } + inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel) { if ( SkillValue >= GrayLevel ) @@ -4476,15 +5353,19 @@ inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLeve return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10; return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10; } + bool Player::UpdateCraftSkill(uint32 spellid) { sLog.outDebug("UpdateCraftSkill spellid %d", spellid); + SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spellid); + for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx) { if (_spell_idx->second->skillId) { uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId); + // Alchemy Discoveries here SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid); if (spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY) @@ -4492,7 +5373,9 @@ bool Player::UpdateCraftSkill(uint32 spellid) if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this)) learnSpell(discoveredSpell,false); } + uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING); + return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue, _spell_idx->second->max_value, (_spell_idx->second->max_value + _spell_idx->second->min_value)/2, @@ -4502,10 +5385,13 @@ bool Player::UpdateCraftSkill(uint32 spellid) } return false; } + bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator ) { sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel); + uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING); + // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times switch (SkillId) { @@ -4527,44 +5413,58 @@ bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLeve } return false; } + bool Player::UpdateFishingSkill() { sLog.outDebug("UpdateFishingSkill"); + uint32 SkillValue = GetPureSkillValue(SKILL_FISHING); + int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50); + uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING); + return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain); } + // levels sync. with spell requirement for skill levels to learn // bonus abilities in sSkillLineAbilityStore // Used only to avoid scan DBC at each skill grow static uint32 bonusSkillLevels[] = {75,150,225,300,375,450}; + bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step) { sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0); if ( !SkillId ) return false; + if(Chance <= 0) // speedup in 0 chance case { sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0); return false; } + uint16 i=0; for (; i < PLAYER_MAX_SKILLS; i++) if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break; if ( i >= PLAYER_MAX_SKILLS ) return false; + uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)); uint16 SkillValue = SKILL_VALUE(data); uint16 MaxValue = SKILL_MAX(data); + if ( !MaxValue || !SkillValue || SkillValue >= MaxValue ) return false; + int32 Roll = irand(1,1000); + if ( Roll <= Chance ) { uint32 new_value = SkillValue+step; if(new_value > MaxValue) new_value = MaxValue; + SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue)); for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl) { @@ -4578,27 +5478,35 @@ bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step) sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0); return true; } + sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0); return false; } + void Player::UpdateWeaponSkill (WeaponAttackType attType) { // no skill gain in pvp Unit *pVictim = getVictim(); if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER) return; + if(IsInFeralForm()) return; // always maximized SKILL_FERAL_COMBAT in fact + if(m_form == FORM_TREE) return; // use weapon but not skill up + if(pVictim && pVictim->GetTypeId() == TYPEID_UNIT && (((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_SKILLGAIN)) return; + uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON); + switch(attType) { case BASE_ATTACK: { Item *tmpitem = GetWeaponForAttack(attType,true); + if (!tmpitem) UpdateSkill(SKILL_UNARMED,weapon_skill_gain); else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE) @@ -4616,6 +5524,7 @@ void Player::UpdateWeaponSkill (WeaponAttackType attType) } UpdateAllCritPercentages(); } + void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence) { uint32 plevel = getLevel(); // if defense than pVictim == attacker @@ -4623,21 +5532,27 @@ void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool de uint32 moblevel = pVictim->getLevelForTarget(this); if(moblevel < greylevel) return; + if (moblevel > plevel + 5) moblevel = plevel + 5; + uint32 lvldif = moblevel - greylevel; if(lvldif < 3) lvldif = 3; + uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType)); if(skilldif <= 0) return; + float chance = float(3 * lvldif * skilldif) / plevel; if(!defence) { if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE) chance += chance * 0.02f * GetStat(STAT_INTELLECT); } + chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1% + if(roll_chance_f(chance)) { if(defence) @@ -4648,6 +5563,7 @@ void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool de else return; } + void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent) { for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++) @@ -4656,6 +5572,7 @@ void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent) uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)); int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val); int16 perm_bonus = SKILL_PERM_BONUS(bonus_val); + if(talent) // permanent bonus stored in high part SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val)); else // temporary/item bonus stored in low part @@ -4663,23 +5580,30 @@ void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent) return; } } + void Player::UpdateSkillsForLevel() { uint16 maxconfskill = sWorld.GetConfigMaxSkillValue(); uint32 maxSkill = GetMaxSkillValueForLevel(); + bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL); + for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++) if (GetUInt32Value(PLAYER_SKILL_INDEX(i))) { uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF; + SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill); if(!pSkill) continue; + if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL) continue; + uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)); uint32 max = SKILL_MAX(data); uint32 val = SKILL_VALUE(data); + /// update only level dependent max skill values if(max!=1) { @@ -4692,6 +5616,7 @@ void Player::UpdateSkillsForLevel() } } } + void Player::UpdateSkillsToMaxSkillsForLevel() { for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++) @@ -4701,22 +5626,28 @@ void Player::UpdateSkillsToMaxSkillsForLevel() if( IsProfessionOrRidingSkill(pskill)) continue; uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)); + uint32 max = SKILL_MAX(data); + if(max > 1) SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max)); + if(pskill == SKILL_DEFENSE) UpdateDefenseBonusesMod(); } } + // This functions sets a skill line value (and adds if doesn't exist yet) // To "remove" a skill line, set it's values to zero void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal) { if(!id) return; + uint16 i=0; for (; i < PLAYER_MAX_SKILLS; i++) if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break; + if(i<PLAYER_MAX_SKILLS) //has skill { if(currVal) @@ -4732,6 +5663,7 @@ void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal) SetUInt32Value(PLAYER_SKILL_INDEX(i),0); SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0); SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0); + // remove all spells that related to this skill for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j) if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j)) @@ -4758,24 +5690,29 @@ void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal) SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal)); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id); + // apply skill bonuses SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0); + // temporary bonuses AuraEffectList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL); for(AuraEffectList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j) if ((*j)->GetMiscValue() == int32(id)) (*j)->ApplyModifier(true); + // permanent bonuses AuraEffectList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT); for(AuraEffectList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j) if ((*j)->GetMiscValue() == int32(id)) (*j)->ApplyModifier(true); + // Learn all spells for skill learnSkillRewardedSpells(id, currVal); return; } } } + bool Player::HasSkill(uint32 skill) const { if(!skill)return false; @@ -4788,15 +5725,18 @@ bool Player::HasSkill(uint32 skill) const } return false; } + uint16 Player::GetSkillValue(uint32 skill) const { if(!skill) return 0; + for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++) { if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill) { uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)); + int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)))); result += SKILL_TEMP_BONUS(bonus); result += SKILL_PERM_BONUS(bonus); @@ -4805,6 +5745,7 @@ uint16 Player::GetSkillValue(uint32 skill) const } return 0; } + uint16 Player::GetMaxSkillValue(uint32 skill) const { if(!skill)return 0; @@ -4813,6 +5754,7 @@ uint16 Player::GetMaxSkillValue(uint32 skill) const if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill) { uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)); + int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)))); result += SKILL_TEMP_BONUS(bonus); result += SKILL_PERM_BONUS(bonus); @@ -4821,6 +5763,7 @@ uint16 Player::GetMaxSkillValue(uint32 skill) const } return 0; } + uint16 Player::GetPureMaxSkillValue(uint32 skill) const { if(!skill)return 0; @@ -4833,6 +5776,7 @@ uint16 Player::GetPureMaxSkillValue(uint32 skill) const } return 0; } + uint16 Player::GetBaseSkillValue(uint32 skill) const { if(!skill)return 0; @@ -4847,6 +5791,7 @@ uint16 Player::GetBaseSkillValue(uint32 skill) const } return 0; } + uint16 Player::GetPureSkillValue(uint32 skill) const { if(!skill)return 0; @@ -4859,10 +5804,12 @@ uint16 Player::GetPureSkillValue(uint32 skill) const } return 0; } + int16 Player::GetSkillPermBonusValue(uint32 skill) const { if(!skill) return 0; + for (uint8 i = 0; i < PLAYER_MAX_SKILLS; i++) { if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill) @@ -4870,12 +5817,15 @@ int16 Player::GetSkillPermBonusValue(uint32 skill) const return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i))); } } + return 0; } + int16 Player::GetSkillTempBonusValue(uint32 skill) const { if(!skill) return 0; + for (uint8 i = 0; i < PLAYER_MAX_SKILLS; i++) { if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill) @@ -4883,11 +5833,14 @@ int16 Player::GetSkillTempBonusValue(uint32 skill) const return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i))); } } + return 0; } + void Player::SendActionButtons(uint32 state) const { sLog.outDetail( "Sending Action Buttons for '%u' spec '%u'", GetGUIDLow(), m_activeSpec); + WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4)); data << uint8(state); // can be 0, 1, 2 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button) @@ -4898,9 +5851,11 @@ void Player::SendActionButtons(uint32 state) const else data << uint32(0); } + GetSession()->SendPacket( &data ); sLog.outDetail( "Action Buttons for '%u' spec '%u' Sent", GetGUIDLow(), m_activeSpec ); } + ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type) { if(button >= MAX_ACTION_BUTTONS) @@ -4908,11 +5863,13 @@ ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type) sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() ); return NULL; } + if(action >= MAX_ACTION_BUTTON_ACTION_VALUE) { sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, GetName(), MAX_ACTION_BUTTON_ACTION_VALUE ); return NULL; } + switch(type) { case ACTION_BUTTON_SPELL: @@ -4921,6 +5878,7 @@ ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type) sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() ); return NULL; } + if(!HasSpell(action)) { sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() ); @@ -4938,29 +5896,36 @@ ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type) break; // pther cases not checked at this moment } + // it create new button (NEW state) if need or return existed ActionButton& ab = m_actionButtons[button]; + // set data and update to CHANGED if not NEW ab.SetActionAndType(action,ActionButtonType(type)); + sLog.outDetail( "Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUIDLow(), action, uint32(type), button ); return &ab; } + void Player::removeActionButton(uint8 button) { ActionButtonList::iterator buttonItr = m_actionButtons.find(button); if (buttonItr==m_actionButtons.end()) return; + if (!buttonItr->second.canRemoveByClient) { - buttonItr->second.canRemoveByClient = true; + buttonItr->second.canRemoveByClient = true; return; - } + } if(buttonItr->second.uState==ACTIONBUTTON_NEW) m_actionButtons.erase(buttonItr); // new and not saved else buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save + sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() ); } + bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport) { // prevent crash when a bad coord is sent by the client @@ -4969,35 +5934,46 @@ bool Player::SetPosition(float x, float y, float z, float orientation, bool tele sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow()); return false; } + //if(movementInfo.flags & MOVEMENTFLAG_MOVING) // mover->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE); //if(movementInfo.flags & MOVEMENTFLAG_TURNING) // mover->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING); //AURA_INTERRUPT_FLAG_JUMP not sure + bool turn = (GetOrientation() != orientation); bool move2d = (teleport || GetPositionX() != x || GetPositionY() != y); + if(turn) RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING); + if(move2d || GetPositionZ() != z) { RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE); + // move and update visible state if need GetMap()->PlayerRelocation(this, x, y, z, orientation); + // reread after Map::Relocation GetPosition(x, y, z); + // group update if(move2d && GetGroup()) SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION); + // code block for underwater state update UpdateUnderwaterState(GetMap(), x, y, z); + CheckExploreSystem(); } else if(turn) { SetOrientation(orientation); } + return true; } + void Player::SaveRecallPosition() { m_recallMap = GetMapId(); @@ -5006,51 +5982,63 @@ void Player::SaveRecallPosition() m_recallZ = GetPositionZ(); m_recallO = GetOrientation(); } + void Player::SendMessageToSet(WorldPacket *data, bool self) { if(self) GetSession()->SendPacket(data); + // we use World::GetMaxVisibleDistance() because i cannot see why not use a distance // update: replaced by GetMap()->GetVisibilityDistance() Trinity::MessageDistDeliverer notifier(this, data, GetMap()->GetVisibilityDistance()); VisitNearbyWorldObject(GetMap()->GetVisibilityDistance(), notifier); } + void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self) { if(self) GetSession()->SendPacket(data); + Trinity::MessageDistDeliverer notifier(this, data, dist); VisitNearbyWorldObject(dist, notifier); } + void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only) { if(self) GetSession()->SendPacket(data); + Trinity::MessageDistDeliverer notifier(this, data, dist, own_team_only); VisitNearbyWorldObject(dist, notifier); } + void Player::SendDirectMessage(WorldPacket *data) { GetSession()->SendPacket(data); } + void Player::SendCinematicStart(uint32 CinematicSequenceId) { WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4); data << uint32(CinematicSequenceId); SendDirectMessage(&data); } + void Player::SendMovieStart(uint32 MovieId) { WorldPacket data(SMSG_TRIGGER_MOVIE, 4); data << uint32(MovieId); SendDirectMessage(&data); } + void Player::CheckExploreSystem() { if (!isAlive()) return; + if (isInFlight()) return; + if(!m_AreaID) m_AreaID = GetAreaId(); if(m_AreaID != GetAreaId()) @@ -5058,21 +6046,27 @@ void Player::CheckExploreSystem() m_AreaID = GetAreaId(); GetSession()->HandleOnAreaChange(GetAreaEntryByAreaID(m_AreaID)); } + uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ()); if(areaFlag==0xffff) return; int offset = areaFlag / 32; + if(offset >= 128) { sLog.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset); return; } + uint32 val = (uint32)(1 << (areaFlag % 32)); uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset); + if( !(currFields & val) ) { SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val)); + GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA); + AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId()); if(!p) { @@ -5100,12 +6094,14 @@ void Player::CheckExploreSystem() exploration_percent = 100; else if (exploration_percent < 0) exploration_percent = 0; + XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE)); } else { XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE)); } + GiveXP( XP, NULL ); SendExplorationExperience(area,XP); } @@ -5113,6 +6109,7 @@ void Player::CheckExploreSystem() } } } + uint32 Player::TeamForRace(uint8 race) { ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race); @@ -5121,14 +6118,17 @@ uint32 Player::TeamForRace(uint8 race) sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race)); return ALLIANCE; } + switch(rEntry->TeamID) { case 7: return ALLIANCE; case 1: return HORDE; } + sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID); return ALLIANCE; } + uint32 Player::getFactionForRace(uint8 race) { ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race); @@ -5137,51 +6137,70 @@ uint32 Player::getFactionForRace(uint8 race) sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race)); return 0; } + return rEntry->FactionID; } + void Player::setFactionForRace(uint8 race) { m_team = TeamForRace(race); setFaction( getFactionForRace(race) ); } + ReputationRank Player::GetReputationRank(uint32 faction) const { FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction); return GetReputationMgr().GetRank(factionEntry); } + //Calculate total reputation percent player gain with quest/creature level int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest) { float percent = 100.0f; + float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL); + if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel())) percent *= rate; + float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN); + if (!for_quest) repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction); + percent += rep > 0 ? repMod : -repMod; + if (percent <= 0.0f) return 0; + return int32(rep*percent/100); } + //Calculates how many reputation points player gains in victim's enemy factions void Player::RewardReputation(Unit *pVictim, float rate) { if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER) return; + if(((Creature*)pVictim)->IsReputationGainDisabled()) return; + ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry); + if(!Rep) return; + uint32 ChampioningFaction = 0; + if(GetChampioningFaction()) { // support for: Championing - http://www.wowwiki.com/Championing + Map const *pMap = GetMap(); if(pMap && pMap->IsDungeon()) { bool Heroic = pMap->IsHeroic(); + InstanceTemplate const *pInstance = objmgr.GetInstanceTemplate(pMap->GetId()); if(pInstance) { @@ -5194,14 +6213,18 @@ void Player::RewardReputation(Unit *pVictim, float rate) } } } + // Favored reputation increase START uint32 zone = GetZoneId(); uint32 team = GetTeam(); float favored_rep_mult = 0; + if( (HasAura(32096) || HasAura(32098)) && (zone == 3483 || zone == 3562 || zone == 3836 || zone == 3713 || zone == 3714) ) favored_rep_mult = 0.25; // Thrallmar's Favor and Honor Hold's Favor else if( HasAura(30754) && (Rep->repfaction1 == 609 || Rep->repfaction2 == 609) && !ChampioningFaction ) favored_rep_mult = 0.25; // Cenarion Favor + if(favored_rep_mult > 0) favored_rep_mult *= 2; // Multiplied by 2 because the reputation is divided by 2 for some reason (See "donerep1 / 2" and "donerep2 / 2") -- if you know why this is done, please update/explain :) // Favored reputation increase END + if(Rep->repfaction1 && (!Rep->team_dependent || team == ALLIANCE)) { int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, ChampioningFaction ? ChampioningFaction : Rep->repfaction1, false); @@ -5210,6 +6233,7 @@ void Player::RewardReputation(Unit *pVictim, float rate) uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1); if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1) GetReputationMgr().ModifyReputation(factionEntry1, donerep1); + // Wiki: Team factions value divided by 2 -- Deprecated, see ModifyReputation /*if (factionEntry1 && Rep->is_teamaward1) { @@ -5218,6 +6242,7 @@ void Player::RewardReputation(Unit *pVictim, float rate) GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2); }*/ } + if(Rep->repfaction2 && (!Rep->team_dependent || team == HORDE)) { int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, ChampioningFaction ? ChampioningFaction : Rep->repfaction2, false); @@ -5226,6 +6251,7 @@ void Player::RewardReputation(Unit *pVictim, float rate) uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2); if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2) GetReputationMgr().ModifyReputation(factionEntry2, donerep2); + // Wiki: Team factions value divided by 2 -- Deprecated, see ModifyReputation /*if (factionEntry2 && Rep->is_teamaward2) { @@ -5235,6 +6261,7 @@ void Player::RewardReputation(Unit *pVictim, float rate) }*/ } } + //Calculate how many reputation points player gain with the quest void Player::RewardReputation(Quest const *pQuest) { @@ -5249,25 +6276,32 @@ void Player::RewardReputation(Quest const *pQuest) GetReputationMgr().ModifyReputation(factionEntry, rep); } } + // TODO: implement reputation spillover } + void Player::UpdateArenaFields(void) { /* arena calcs go here */ } + void Player::UpdateHonorFields() { /// called when rewarding honor and at each save uint64 now = time(NULL); uint64 today = uint64(time(NULL) / DAY) * DAY; + if(m_lastHonorUpdateTime < today) { uint64 yesterday = today - DAY; + uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS)); + // update yesterday's contribution if(m_lastHonorUpdateTime >= yesterday ) { SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION)); + // this is the first update today, reset today's contribution SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0); SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today)); @@ -5279,8 +6313,10 @@ void Player::UpdateHonorFields() SetUInt32Value(PLAYER_FIELD_KILLS, 0); } } + m_lastHonorUpdateTime = now; } + ///Calculate the amount of honor gained based on the victim ///and the size of the group for which the honor is divided ///An exact honor value can also be given (overriding the calcs) @@ -5291,35 +6327,47 @@ bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor, bool pvpt { if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER) return false; + if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() ) return false; + return true; } + // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens if(HasAura(SPELL_AURA_PLAYER_INACTIVE)) return false; + uint64 victim_guid = 0; uint32 victim_rank = 0; time_t now = time(NULL); + // need call before fields update to have chance move yesterday data to appropriate fields before today data change. UpdateHonorFields(); + // do not reward honor in arenas, but return true to enable onkill spellproc if(InBattleGround() && GetBattleGround() && GetBattleGround()->isArena()) return true; + if(honor <= 0) { if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT)) return false; + victim_guid = uVictim->GetGUID(); + if( uVictim->GetTypeId() == TYPEID_PLAYER ) { Player *pVictim = (Player *)uVictim; + if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() ) return false; + float f = 1; //need for total kills (?? need more info) uint32 k_grey = 0; uint32 k_level = getLevel(); uint32 v_level = pVictim->getLevel(); + { // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION // [0] Just name @@ -5342,13 +6390,19 @@ bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor, bool pvpt else victim_guid = 0; // Don't show HK: <rank> message, only log. } + k_grey = Trinity::XP::GetGrayLevel(k_level); + if(v_level<=k_grey) return false; + float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey))); + int32 v_rank =1; //need more info + honor = ((f * diff_level * (190 + v_rank*10))/6); honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer + // count the number of playerkills in one day ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true); // and those in a lifetime @@ -5360,21 +6414,27 @@ bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor, bool pvpt else { Creature *cVictim = (Creature *)uVictim; + if (!cVictim->isRacialLeader()) return false; + honor = 100; // ??? need more info victim_rank = 19; // HK: Leader } } + if (uVictim != NULL) { honor *= sWorld.getRate(RATE_HONOR); + if(groupsize > 1) honor /= groupsize; + // apply honor multiplier from aura (not stacking-get highest) honor = int32(float(honor) * (float(GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN_PCT))+100.0f)/100.0f); honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor } + // honor - for show honor points in log // victim_guid - for show victim name in log // victim_rank [1..4] HK: <dishonored rank> @@ -5384,14 +6444,19 @@ bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor, bool pvpt data << (uint32) honor; data << (uint64) victim_guid; data << (uint32) victim_rank; + GetSession()->SendPacket(&data); + // add honor points ModifyHonorPoints(int32(honor)); + ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true); + if( sWorld.getConfig(CONFIG_PVP_TOKEN_ENABLE) && pvptoken ) { if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT)) return true; + if(uVictim->GetTypeId() == TYPEID_PLAYER) { // Check if allowed to receive it in current map @@ -5400,27 +6465,33 @@ bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor, bool pvpt || (MapType == 2 && !HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP)) || (MapType == 3 && !InBattleGround()) ) return true; + uint32 noSpaceForCount = 0; uint32 itemId = sWorld.getConfig(CONFIG_PVP_TOKEN_ID); int32 count = sWorld.getConfig(CONFIG_PVP_TOKEN_COUNT); + // check space and find places ItemPosCountVec dest; uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, count, &noSpaceForCount ); if( msg != EQUIP_ERR_OK ) // convert to possible store amount count = noSpaceForCount; + if( count == 0 || dest.empty()) // can't add any { // -- TODO: Send to mailbox if no space ChatHandler(this).PSendSysMessage("You don't have any space in your bags for a token."); return true; } + Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId)); SendNewItem(item,count,true,false); ChatHandler(this).PSendSysMessage("You have been awarded a token for slaying another player."); } } + return true; } + void Player::ModifyHonorPoints( int32 value ) { if(value < 0) @@ -5433,6 +6504,7 @@ void Player::ModifyHonorPoints( int32 value ) else SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS)); } + void Player::ModifyArenaPoints( int32 value ) { if(value < 0) @@ -5445,15 +6517,18 @@ void Player::ModifyArenaPoints( int32 value ) else SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS)); } + uint32 Player::GetGuildIdFromDB(uint64 guid) { QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid)); if(!result) return 0; + uint32 id = result->Fetch()[0].GetUInt32(); delete result; return id; } + uint32 Player::GetRankFromDB(uint64 guid) { QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) ); @@ -5466,15 +6541,18 @@ uint32 Player::GetRankFromDB(uint64 guid) else return 0; } + uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type) { QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u' AND type='%u' LIMIT 1", GUID_LOPART(guid), type); if(!result) return 0; + uint32 id = (*result)[0].GetUInt32(); delete result; return id; } + uint32 Player::GetZoneIdFromDB(uint64 guid) { uint32 guidLow = GUID_LOPART(guid); @@ -5484,6 +6562,7 @@ uint32 Player::GetZoneIdFromDB(uint64 guid) Field* fields = result->Fetch(); uint32 zone = fields[0].GetUInt32(); delete result; + if (!zone) { // stored zone is zero, use generic and slow zone detection @@ -5496,32 +6575,42 @@ uint32 Player::GetZoneIdFromDB(uint64 guid) float posy = fields[2].GetFloat(); float posz = fields[3].GetFloat(); delete result; + zone = MapManager::Instance().GetZoneId(map,posx,posy,posz); + if (zone > 0) CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow); } + return zone; } + uint32 Player::GetLevelFromDB(uint64 guid) { QueryResult *result = CharacterDatabase.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid) ); if (!result) return 0; + Field* fields = result->Fetch(); uint32 level = fields[0].GetUInt32(); delete result; + return level; } + void Player::UpdateArea(uint32 newArea) { // FFA_PVP flags are area and not zone id dependent // so apply them accordingly m_areaUpdateId = newArea; + AreaTableEntry const* area = GetAreaEntryByAreaID(newArea); pvpInfo.inFFAPvPArea = area && (area->flags & AREA_FLAG_ARENA); UpdatePvPState(true); + UpdateAreaDependentAuras(newArea); } + void Player::UpdateZone(uint32 newZone, uint32 newArea) { if(m_zoneUpdateId != newZone) @@ -5530,13 +6619,17 @@ void Player::UpdateZone(uint32 newZone, uint32 newArea) sOutdoorPvPMgr.HandlePlayerEnterZone(this, newZone); SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange... } + m_zoneUpdateId = newZone; m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL; + // zone changed, so area changed as well, update it UpdateArea(newArea); + AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone); if(!zone) return; + if (sWorld.getConfig(CONFIG_WEATHER)) { Weather *wth = sWorld.FindWeather(zone->ID); @@ -5553,6 +6646,7 @@ void Player::UpdateZone(uint32 newZone, uint32 newArea) } } } + // in PvP, any not controlled zone (except zone->team == 6, default case) // in PvE, only opposition team capital switch(zone->team) @@ -5571,6 +6665,7 @@ void Player::UpdateZone(uint32 newZone, uint32 newArea) pvpInfo.inHostileArea = false; break; } + pvpInfo.inNoPvPArea = false; if(zone->IsSanctuary()) // in sanctuary { @@ -5582,6 +6677,7 @@ void Player::UpdateZone(uint32 newZone, uint32 newArea) { RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY); } + if(zone->flags & AREA_FLAG_CAPITAL) // in capital city { SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING); @@ -5608,34 +6704,44 @@ void Player::UpdateZone(uint32 newZone, uint32 newArea) } } } + UpdatePvPState(); + // remove items with area/map limitations (delete only for alive player to allow back in ghost mode) // if player resurrected at teleport this will be applied in resurrect code if(isAlive()) DestroyZoneLimitedItem( true, newZone ); + // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example) AutoUnequipOffhandIfNeed(); + // recent client version not send leave/join channel packets for built-in local channels UpdateLocalChannels( newZone ); + // group update if(GetGroup()) SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE); + UpdateZoneDependentAuras(newZone); } + //If players are too far way of duel flag... then player loose the duel void Player::CheckDuelDistance(time_t currTime) { if(!duel) return; + uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER); GameObject* obj = GetMap()->GetGameObject(duelFlagGUID); if(!obj) return; + if(duel->outOfBound == 0) { if(!IsWithinDistInMap(obj, 50)) { duel->outOfBound = currTime; + WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0); GetSession()->SendPacket(&data); } @@ -5645,6 +6751,7 @@ void Player::CheckDuelDistance(time_t currTime) if(IsWithinDistInMap(obj, 40)) { duel->outOfBound = 0; + WorldPacket data(SMSG_DUEL_INBOUNDS, 0); GetSession()->SendPacket(&data); } @@ -5654,20 +6761,25 @@ void Player::CheckDuelDistance(time_t currTime) } } } + bool Player::IsOutdoorPvPActive() { return (isAlive() && !HasInvisibilityAura() && !HasStealthAura() && (IsPvP() || sWorld.IsPvPRealm()) && !HasUnitMovementFlag(MOVEMENTFLAG_FLYING) && !isInFlight()); } + void Player::DuelComplete(DuelCompleteType type) { // duel not requested if(!duel) return; + sLog.outDebug("Duel Complete %s %s", GetName(), duel->opponent->GetName()); + WorldPacket data(SMSG_DUEL_COMPLETE, (1)); data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0); GetSession()->SendPacket(&data); duel->opponent->GetSession()->SendPacket(&data); + if(type != DUEL_INTERUPTED) { data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size @@ -5676,21 +6788,25 @@ void Player::DuelComplete(DuelCompleteType type) data << GetName(); SendMessageToSet(&data,true); } + if (type == DUEL_WON) { GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1); if (duel->opponent) { duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1); + //Credit for quest Death's Challenge if (getClass() == CLASS_DEATH_KNIGHT && duel->opponent->GetQuestStatus(12733) == QUEST_STATUS_INCOMPLETE) duel->opponent->CastSpell(duel->opponent, 52994, true); } } + //Remove Duel Flag object GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER)); if(obj) duel->initiator->RemoveGameObject(obj,true); + /* remove auras */ AuraMap &itsAuras = duel->opponent->GetAuras(); for(AuraMap::iterator i = itsAuras.begin(); i != itsAuras.end();) @@ -5702,6 +6818,7 @@ void Player::DuelComplete(DuelCompleteType type) else ++i; } + AuraMap &myAuras = GetAuras(); for(AuraMap::iterator i = myAuras.begin(); i != myAuras.end();) { @@ -5712,69 +6829,93 @@ void Player::DuelComplete(DuelCompleteType type) else ++i; } + // cleanup combo points if(GetComboTarget()==duel->opponent->GetGUID()) ClearComboPoints(); else if(GetComboTarget()==duel->opponent->GetPetGUID()) ClearComboPoints(); + if(duel->opponent->GetComboTarget()==GetGUID()) duel->opponent->ClearComboPoints(); else if(duel->opponent->GetComboTarget()==GetPetGUID()) duel->opponent->ClearComboPoints(); + // Honor points after duel (the winner) - ImpConfig if(uint32 amount = sWorld.getConfig(CONFIG_HONOR_AFTER_DUEL)) duel->opponent->RewardHonor(NULL,1,amount); + //cleanups SetUInt64Value(PLAYER_DUEL_ARBITER, 0); SetUInt32Value(PLAYER_DUEL_TEAM, 0); duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0); duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0); + delete duel->opponent->duel; duel->opponent->duel = NULL; delete duel; duel = NULL; } + //---------------------------------------------------------// + void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply) { if(slot >= INVENTORY_SLOT_BAG_END || !item) return; + // not apply mods for broken item if(item->IsBroken()) return; + ItemPrototype const *proto = item->GetProto(); + if(!proto) return; + sLog.outDetail("applying mods for item %u ",item->GetGUIDLow()); + uint8 attacktype = Player::GetAttackBySlot(slot); + //check disarm only on mod apply to allow remove item mods if (!CanUseAttackType(attacktype) ) return; + if(attacktype < MAX_ATTACK) _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply); + _ApplyItemBonuses(proto,slot,apply); + if( slot==EQUIPMENT_SLOT_RANGED ) _ApplyAmmoBonuses(); + ApplyItemEquipSpell(item,apply); ApplyEnchantment(item, apply); + if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items CorrectMetaGemEnchants(slot, apply); + sLog.outDebug("_ApplyItemMods complete."); } + void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/) { if (slot >= INVENTORY_SLOT_BAG_END || !proto) return; + ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL; if (only_level_scale && !ssd) return; + // req. check at equip, but allow use for extended range if range limit max level, set proper level uint32 ssd_level = getLevel(); if (ssd && ssd_level > ssd->MaxLevel) ssd_level = ssd->MaxLevel; + ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL; if (only_level_scale && !ssv) return; + for (uint8 i = 0; i < MAX_ITEM_PROTO_STATS; ++i) { uint32 statType = 0; @@ -5794,8 +6935,10 @@ void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool appl statType = proto->ItemStat[i].ItemStatType; val = proto->ItemStat[i].ItemStatValue; } + if(val == 0) continue; + switch (statType) { case ITEM_MOD_MANA: @@ -5939,12 +7082,14 @@ void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool appl break; } } + // Apply Spell Power from ScalingStatValue if set if(ssv) { if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue)) ApplySpellPowerBonus(spellbonus, apply); } + // If set ScalingStatValue armor get it or use item armor uint32 armor = proto->Armor; if (ssv) @@ -5955,24 +7100,34 @@ void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool appl // Add armor bonus from ArmorDamageModifier if > 0 if (proto->ArmorDamageModifier > 0) armor += uint32(proto->ArmorDamageModifier); + if (armor) HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply); + if (proto->Block) HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply); + if (proto->HolyRes) HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply); + if (proto->FireRes) HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply); + if (proto->NatureRes) HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply); + if (proto->FrostRes) HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply); + if (proto->ShadowRes) HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply); + if (proto->ArcaneRes) HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply); + WeaponAttackType attType = BASE_ATTACK; float damage = 0.0f; + if( slot == EQUIPMENT_SLOT_RANGED && ( proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN || proto->InventoryType == INVTYPE_RANGEDRIGHT )) @@ -5983,6 +7138,7 @@ void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool appl { attType = OFF_ATTACK; } + float minDamage = proto->Damage[0].DamageMin; float maxDamage = proto->Damage[0].DamageMax; int32 extraDPS = 0; @@ -6002,11 +7158,13 @@ void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool appl SetBaseWeaponDamage(attType, MINDAMAGE, damage); //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE)); } + if (maxDamage > 0 ) { damage = apply ? maxDamage : BASE_MAXDAMAGE; SetBaseWeaponDamage(attType, MAXDAMAGE, damage); } + // Apply feral bonus from ScalingStatValue if set if (ssv) { @@ -6020,8 +7178,10 @@ void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool appl if (feral_bonus > 0) ApplyFeralAPBonus(feral_bonus, apply); } + if(IsInFeralForm() || !CanUseAttackType(attType)) return; + if (proto->Delay) { if(slot == EQUIPMENT_SLOT_RANGED) @@ -6031,26 +7191,32 @@ void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool appl else if(slot==EQUIPMENT_SLOT_OFFHAND) SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME); } + if(CanModifyStats() && (damage || proto->Delay)) UpdateDamagePhysical(attType); } + void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply) { AuraEffectList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT); for(AuraEffectList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr) _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply); + AuraEffectList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE); for(AuraEffectList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr) _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply); + AuraEffectList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE); for(AuraEffectList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr) _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply); } + void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, AuraEffect* aura, bool apply) { // generic not weapon specific case processes in aura code if(aura->GetSpellProto()->EquippedItemClass == -1) return; + BaseModGroup mod = BASEMOD_END; switch(attackType) { @@ -6059,19 +7225,23 @@ void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attac case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break; default: return; } + if (item->IsFitToSpellRequirements(aura->GetSpellProto())) { HandleBaseModValue(mod, FLAT_MOD, float (aura->GetAmount()), apply); } } + void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, AuraEffect* aura, bool apply) { // ignore spell mods for not wands if((aura->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0) return; + // generic not weapon specific case processes in aura code if(aura->GetSpellProto()->EquippedItemClass == -1) return; + UnitMods unitMod = UNIT_MOD_END; switch(attackType) { @@ -6080,6 +7250,7 @@ void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType att case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break; default: return; } + UnitModifierType unitModType = TOTAL_VALUE; switch(aura->GetAuraName()) { @@ -6087,34 +7258,43 @@ void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType att case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break; default: return; } + if (item->IsFitToSpellRequirements(aura->GetSpellProto())) { HandleStatModifier(unitMod, unitModType, float(aura->GetAmount()),apply); } } + void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change) { if(!item) return; + ItemPrototype const *proto = item->GetProto(); if(!proto) return; + for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) { _Spell const& spellData = proto->Spells[i]; + // no spell if(!spellData.SpellId ) continue; + // wrong triggering type if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP) continue; + // check if it is valid spell SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId); if(!spellproto) continue; + ApplyEquipSpell(spellproto,item,apply,form_change); } } + void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change) { if(apply) @@ -6122,6 +7302,7 @@ void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply // Cannot be used in this stance/form if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK) return; + if(form_change) // check aura active state from other form { AuraMap const& auras = GetAuras(); @@ -6129,7 +7310,9 @@ void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply if(!item || itr->second->GetCastItemGUID()==item->GetGUID()) return; } + DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id); + CastSpell(this,spellInfo,true,item); } else @@ -6140,12 +7323,14 @@ void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK) return; // and remove only not compatible at form change } + if(item) RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped else RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case) } } + void Player::UpdateEquipSpellsAtFormChange() { for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; i++) @@ -6156,17 +7341,20 @@ void Player::UpdateEquipSpellsAtFormChange() ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active } } + // item set bonuses not dependent from item broken state for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex) { ItemSetEffect* eff = ItemSetEff[setindex]; if(!eff) continue; + for(uint32 y=0;y<8; ++y) { SpellEntry const* spellInfo = eff->spells[y]; if(!spellInfo) continue; + ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active } @@ -6176,6 +7364,7 @@ void Player::CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 { if(!target || !target->isAlive() || target == this) return; + for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++) { // If usable, try to cast item spell @@ -6208,6 +7397,7 @@ void Player::CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 } } } + void Player::CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 procVictim, uint32 procEx, Item *item, ItemPrototype const * proto) { // Can do effect if any damage done to target @@ -6217,22 +7407,28 @@ void Player::CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 for (int i = 0; i < 5; i++) { _Spell const& spellData = proto->Spells[i]; + // no spell if(!spellData.SpellId ) continue; + // wrong triggering type if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT) continue; + SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId); if(!spellInfo) { sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId); continue; } + // not allow proc extra attack spell at extra attack if( m_extraAttacks && IsSpellHaveEffect(spellInfo, SPELL_EFFECT_ADD_EXTRA_ATTACKS) ) return; + float chance = spellInfo->procChance; + if(spellData.SpellPPMRate) { if(spellData.SpellId == 52781) // Persuasive Strike @@ -6254,10 +7450,12 @@ void Player::CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 { chance = GetWeaponProcChance(); } + if (roll_chance_f(chance)) CastSpell(target, spellInfo->Id, true, item); } } + // item combat enchantments for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot) { @@ -6268,7 +7466,9 @@ void Player::CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 { if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL) continue; + SpellEnchantProcEntry const* entry = spellmgr.GetSpellEnchantProcEvent(enchant_id); + if (entry && entry->procEx) { // Check hit/crit/dodge/parry requirement @@ -6282,13 +7482,16 @@ void Player::CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 //if (!(damageInfo->procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE)) continue; } + SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]); if (!spellInfo) { sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]); continue; } + float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance(); + if (entry) { if(entry->PPMChance) @@ -6296,8 +7499,10 @@ void Player::CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 else if(entry->customChance) chance = entry->customChance; } + // Apply spell mods ApplySpellMod(pEnchant->spellid[s],SPELLMOD_CHANCE_OF_SUCCESS,chance); + if (roll_chance_f(chance)) { if(IsPositiveSpell(pEnchant->spellid[s])) @@ -6308,6 +7513,7 @@ void Player::CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 } } } + void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex) { ItemPrototype const* proto = item->GetProto(); @@ -6316,6 +7522,7 @@ void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 c { uint32 learn_spell_id = proto->Spells[0].SpellId; uint32 learning_spell_id = proto->Spells[1].SpellId; + SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id); if(!spellInfo) { @@ -6323,6 +7530,7 @@ void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 c SendEquipError(EQUIP_ERR_NONE,item,NULL); return; } + Spell *spell = new Spell(this, spellInfo,false); spell->m_CastItem = item; spell->m_cast_count = cast_count; //set count of casts @@ -6330,31 +7538,39 @@ void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 c spell->prepare(&targets); return; } + // use triggered flag only for items with many spell casts and for not first cast int count = 0; + // item spells casted at use for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) { _Spell const& spellData = proto->Spells[i]; + // no spell if(!spellData.SpellId) continue; + // wrong triggering type if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE) continue; + SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId); if(!spellInfo) { sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId); continue; } + Spell *spell = new Spell(this, spellInfo, (count > 0)); spell->m_CastItem = item; spell->m_cast_count = cast_count; // set count of casts spell->m_glyphIndex = glyphIndex; // glyph index spell->prepare(&targets); + ++count; } + // Item enchantments spells casted at use for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot) { @@ -6365,24 +7581,29 @@ void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 c { if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL) continue; + SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]); if (!spellInfo) { sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]); continue; } + Spell *spell = new Spell(this, spellInfo, (count > 0)); spell->m_CastItem = item; spell->m_cast_count = cast_count; // set count of casts spell->m_glyphIndex = glyphIndex; // glyph index spell->prepare(&targets); + ++count; } } } + void Player::_RemoveAllItemMods() { sLog.outDebug("_RemoveAllItemMods start."); + for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; i++) { if(m_items[i]) @@ -6390,15 +7611,19 @@ void Player::_RemoveAllItemMods() ItemPrototype const *proto = m_items[i]->GetProto(); if(!proto) continue; + // item set bonuses not dependent from item broken state if(proto->ItemSet) RemoveItemsSetItem(this,proto); + if(m_items[i]->IsBroken()) continue; + ApplyItemEquipSpell(m_items[i],false); ApplyEnchantment(m_items[i], false); } } + for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; i++) { if(m_items[i]) @@ -6408,36 +7633,47 @@ void Player::_RemoveAllItemMods() ItemPrototype const *proto = m_items[i]->GetProto(); if(!proto) continue; + uint32 attacktype = Player::GetAttackBySlot(i); if(attacktype < MAX_ATTACK) _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false); + _ApplyItemBonuses(proto,i, false); + if( i == EQUIPMENT_SLOT_RANGED ) _ApplyAmmoBonuses(); } } + sLog.outDebug("_RemoveAllItemMods complete."); } + void Player::_ApplyAllItemMods() { sLog.outDebug("_ApplyAllItemMods start."); + for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; i++) { if(m_items[i]) { if(m_items[i]->IsBroken()) continue; + ItemPrototype const *proto = m_items[i]->GetProto(); if(!proto) continue; + uint32 attacktype = Player::GetAttackBySlot(i); if(attacktype < MAX_ATTACK) _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true); + _ApplyItemBonuses(proto,i, true); + if( i == EQUIPMENT_SLOT_RANGED ) _ApplyAmmoBonuses(); } } + for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; i++) { if(m_items[i]) @@ -6445,17 +7681,22 @@ void Player::_ApplyAllItemMods() ItemPrototype const *proto = m_items[i]->GetProto(); if(!proto) continue; + // item set bonuses not dependent from item broken state if(proto->ItemSet) AddItemsSetItem(this,m_items[i]); + if(m_items[i]->IsBroken()) continue; + ApplyItemEquipSpell(m_items[i],true); ApplyEnchantment(m_items[i], true); } } + sLog.outDebug("_ApplyAllItemMods complete."); } + void Player::_ApplyAllLevelScaleItemMods(bool apply) { for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i) @@ -6464,42 +7705,54 @@ void Player::_ApplyAllLevelScaleItemMods(bool apply) { if(m_items[i]->IsBroken()) continue; + ItemPrototype const *proto = m_items[i]->GetProto(); if(!proto) continue; + _ApplyItemBonuses(proto,i, apply, true); } } } + void Player::_ApplyAmmoBonuses() { // check ammo uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID); if(!ammo_id) return; + float currentAmmoDPS; + ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id ); if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto)) currentAmmoDPS = 0.0f; else currentAmmoDPS = ( ammo_proto->Damage[0].DamageMin + ammo_proto->Damage[0].DamageMax ) / 2; + if(currentAmmoDPS == GetAmmoDPS()) return; + m_ammoDPS = currentAmmoDPS; + if(CanModifyStats()) UpdateDamagePhysical(RANGED_ATTACK); } + bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const { if(!ammo_proto) return false; + // check ranged weapon Item *weapon = GetWeaponForAttack( RANGED_ATTACK ); if(!weapon || weapon->IsBroken() ) return false; + ItemPrototype const* weapon_proto = weapon->GetProto(); if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON ) return false; + // check ammo ws. weapon compatibility switch(weapon_proto->SubClass) { @@ -6515,14 +7768,17 @@ bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const default: return false; } + return true; } + /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable Called by remove insignia spell effect */ void Player::RemovedInsignia(Player* looterPlr) { if (!GetBattleGroundId()) return; + // If not released spirit, do it ! if(m_deathTimer > 0) { @@ -6530,39 +7786,48 @@ void Player::RemovedInsignia(Player* looterPlr) BuildPlayerRepop(); RepopAtGraveyard(); } + Corpse *corpse = GetCorpse(); if (!corpse) return; + // We have to convert player corpse to bones, not to be able to resurrect there // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true); if (!bones) return; + // Now we must make bones lootable, and send player loot bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE); + // We store the level of our player in the gold field // We retrieve this information at Player::SendLoot() bones->loot.gold = getLevel(); bones->lootRecipient = looterPlr; looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA); } + void Player::SendLootRelease( uint64 guid ) { WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) ); data << uint64(guid) << uint8(1); SendDirectMessage( &data ); } + void Player::SendLoot(uint64 guid, LootType loot_type) { if (uint64 lguid = GetLootGUID()) m_session->DoLootRelease(lguid); + Loot *loot = 0; PermissionTypes permission = ALL_PERMISSION; + sLog.outDebug("Player::SendLoot"); if (IS_GAMEOBJECT_GUID(guid)) { sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)"); GameObject *go = GetMap()->GetGameObject(guid); + // not check distance for GO in case owned GO (fishing bobber case, for example) // And permit out of range GO with no owner in case fishing hole if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE))) @@ -6570,10 +7835,13 @@ void Player::SendLoot(uint64 guid, LootType loot_type) SendLootRelease(guid); return; } + loot = &go->loot; + if (go->getLootState() == GO_READY) { uint32 lootid = go->GetGOInfo()->GetLootId(); + //TODO: fix this big hack if((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S)) if( BattleGround *bg = GetBattleGround()) @@ -6583,30 +7851,37 @@ void Player::SendLoot(uint64 guid, LootType loot_type) SendLootRelease(guid); return; } + if (lootid) { sLog.outDebug(" if(lootid)"); loot->clear(); loot->FillLoot(lootid, LootTemplates_Gameobject, this, false); } + if (loot_type == LOOT_FISHING) go->getFishLoot(loot,this); + go->SetLootState(GO_ACTIVATED); } } else if (IS_ITEM_GUID(guid)) { Item *item = GetItemByGuid( guid ); + if (!item) { SendLootRelease(guid); return; } + loot = &item->loot; + if (!item->m_lootGenerated) { item->m_lootGenerated = true; loot->clear(); + switch(loot_type) { case LOOT_DISENCHANTING: @@ -6628,12 +7903,15 @@ void Player::SendLoot(uint64 guid, LootType loot_type) else if (IS_CORPSE_GUID(guid)) // remove insignia { Corpse *bones = ObjectAccessor::GetCorpse(*this, guid); + if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) ) { SendLootRelease(guid); return; } + loot = &bones->loot; + if (!bones->lootForBody) { bones->lootForBody = true; @@ -6646,32 +7924,39 @@ void Player::SendLoot(uint64 guid, LootType loot_type) // Now it works like this: lvl10: ~6copper, lvl70: ~9silver bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) ); } + if (bones->lootRecipient != this) permission = NONE_PERMISSION; } else { Creature *creature = GetMap()->GetCreature(guid); + // must be in range and creature must be alive for pickpocket and must be dead for another loot if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE)) { SendLootRelease(guid); return; } + if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature)) { SendLootRelease(guid); return; } + loot = &creature->loot; + if (loot_type == LOOT_PICKPOCKETING) { if (!creature->lootForPickPocketed) { creature->lootForPickPocketed = true; loot->clear(); + if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId) loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false); + // Generate extra money for pick pocket loot const uint32 a = urand(0, creature->getLevel()/2); const uint32 b = urand(0, getLevel()/2); @@ -6687,21 +7972,27 @@ void Player::SendLoot(uint64 guid, LootType loot_type) creature->SetLootRecipient(this); recipient = this; } + if (creature->lootForPickPocketed) { creature->lootForPickPocketed = false; loot->clear(); } + if (!creature->lootForBody) { creature->lootForBody = true; loot->clear(); + if (uint32 lootid = creature->GetCreatureInfo()->lootid) loot->FillLoot(lootid, LootTemplates_Creature, recipient, false); + loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold); + if (Group* group = recipient->GetGroup()) { group->UpdateLooterGuid(creature,true); + switch (group->GetLootMethod()) { case GROUP_LOOT: @@ -6719,6 +8010,7 @@ void Player::SendLoot(uint64 guid, LootType loot_type) } } } + // possible only if creature->lootForBody && loot->empty() at spell cast check if (loot_type == LOOT_SKINNING) { @@ -6754,7 +8046,9 @@ void Player::SendLoot(uint64 guid, LootType loot_type) } } } + SetLootGUID(guid); + // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client switch(loot_type) { @@ -6762,30 +8056,39 @@ void Player::SendLoot(uint64 guid, LootType loot_type) case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break; default: break; } + // need know merged fishing/corpse loot type for achievements loot->loot_type = loot_type; + WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size + data << uint64(guid); data << uint8(loot_type); data << LootView(*loot, this, permission); + SendDirectMessage(&data); + // add 'this' player as one of the players that are looting 'loot' if (permission != NONE_PERMISSION) loot->AddLooter(GetGUID()); + if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid)) SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING); } + void Player::SendNotifyLootMoneyRemoved() { WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0); GetSession()->SendPacket( &data ); } + void Player::SendNotifyLootItemRemoved(uint8 lootSlot) { WorldPacket data(SMSG_LOOT_REMOVED, 1); data << uint8(lootSlot); GetSession()->SendPacket( &data ); } + void Player::SendUpdateWorldState(uint32 Field, uint32 Value) { WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8); @@ -6793,6 +8096,7 @@ void Player::SendUpdateWorldState(uint32 Field, uint32 Value) data << Value; GetSession()->SendPacket(&data); } + void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) { // data depends on zoneid/mapid... @@ -6800,7 +8104,9 @@ void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) uint16 NumberOfFields = 0; uint32 mapid = GetMapId(); OutdoorPvP * pvp = sOutdoorPvPMgr.GetOutdoorPvPToZoneId(zoneid); + sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid); + // may be exist better way to do this... switch(zoneid) { @@ -6863,6 +8169,7 @@ void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) NumberOfFields = 12; break; } + WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8))); data << uint32(mapid); // mapid data << uint32(zoneid); // zone id @@ -7169,25 +8476,31 @@ void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) data << uint32(2502) << uint32(0x0); // 11 data << uint32(2493) << uint32(0x0); // 12 data << uint32(2491) << uint32(0x0); // 13 + data << uint32(2495) << uint32(0x0); // 14 data << uint32(2494) << uint32(0x0); // 15 data << uint32(2497) << uint32(0x0); // 16 + data << uint32(2762) << uint32(0x0); // 17 data << uint32(2662) << uint32(0x0); // 18 data << uint32(2663) << uint32(0x0); // 19 data << uint32(2664) << uint32(0x0); // 20 + data << uint32(2760) << uint32(0x0); // 21 data << uint32(2670) << uint32(0x0); // 22 data << uint32(2668) << uint32(0x0); // 23 data << uint32(2669) << uint32(0x0); // 24 + data << uint32(2761) << uint32(0x0); // 25 data << uint32(2667) << uint32(0x0); // 26 data << uint32(2665) << uint32(0x0); // 27 data << uint32(2666) << uint32(0x0); // 28 + data << uint32(2763) << uint32(0x0); // 29 data << uint32(2659) << uint32(0x0); // 30 data << uint32(2660) << uint32(0x0); // 31 data << uint32(2661) << uint32(0x0); // 32 + data << uint32(2671) << uint32(0x0); // 33 data << uint32(2676) << uint32(0x0); // 34 data << uint32(2677) << uint32(0x0); // 35 @@ -7308,21 +8621,27 @@ void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) } GetSession()->SendPacket(&data); } + uint32 Player::GetXPRestBonus(uint32 xp) { uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus + if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp rested_bonus = xp; + SetRestBonus( GetRestBonus() - rested_bonus); + sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus()); return rested_bonus; } + void Player::SetBindPoint(uint64 guid) { WorldPacket data(SMSG_BINDER_CONFIRM, 8); data << uint64(guid); GetSession()->SendPacket( &data ); } + void Player::SendTalentWipeConfirm(uint64 guid) { WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4)); @@ -7331,6 +8650,7 @@ void Player::SendTalentWipeConfirm(uint64 guid) data << cost; GetSession()->SendPacket( &data ); } + void Player::SendPetSkillWipeConfirm() { Pet* pet = GetPet(); @@ -7341,9 +8661,11 @@ void Player::SendPetSkillWipeConfirm() data << uint32(pet->resetTalentsCost()); GetSession()->SendPacket( &data ); } + /*********************************************************/ /*** STORAGE SYSTEM ***/ /*********************************************************/ + void Player::SetVirtualItemSlot( uint8 i, Item* item) { assert(i < 3); @@ -7363,6 +8685,7 @@ void Player::SetVirtualItemSlot( uint8 i, Item* item) } } } + void Player::SetSheath( SheathState sheathed ) { switch (sheathed) @@ -7391,9 +8714,11 @@ void Player::SetSheath( SheathState sheathed ) } Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players... } + uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const { uint8 pClass = getClass(); + uint8 slots[4]; slots[0] = NULL_SLOT; slots[1] = NULL_SLOT; @@ -7448,6 +8773,7 @@ uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap case INVTYPE_WEAPON: { slots[0] = EQUIPMENT_SLOT_MAINHAND; + // suggest offhand slot only if know dual wielding // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ... if(CanDualWield()) @@ -7519,6 +8845,7 @@ uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap default : return NULL_SLOT; } + if( slot != NULL_SLOT ) { if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) ) @@ -7542,6 +8869,7 @@ uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap return slots[i]; } } + // if not found free and can swap return first appropriate from used for (uint8 i = 0; i < 4; i++) { @@ -7549,14 +8877,18 @@ uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap return slots[i]; } } + // no free position return NULL_SLOT; } + uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const { Item *pItem; uint32 tempcount = 0; + uint8 res = EQUIP_ERR_OK; + for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++) { pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); @@ -7611,9 +8943,11 @@ uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const } } } + // not found req. item count and have unequippable items return res; } + uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const { uint32 count = 0; @@ -7635,6 +8969,7 @@ uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) cons if( pBag ) count += pBag->GetItemCount(item,skipItem); } + if(skipItem && skipItem->GetProto()->GemProperties) { for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++) @@ -7644,6 +8979,7 @@ uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) cons count += pItem->GetGemCountWithID(item); } } + if(inBankAlso) { for(uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++) @@ -7658,6 +8994,7 @@ uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) cons if( pBag ) count += pBag->GetItemCount(item,skipItem); } + if(skipItem && skipItem->GetProto()->GemProperties) { for(uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++) @@ -7668,8 +9005,10 @@ uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) cons } } } + return count; } + Item* Player::GetItemByGuid( uint64 guid ) const { for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++) @@ -7684,6 +9023,7 @@ Item* Player::GetItemByGuid( uint64 guid ) const if( pItem && pItem->GetGUID() == guid ) return pItem; } + for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) { Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ); @@ -7710,14 +9050,17 @@ Item* Player::GetItemByGuid( uint64 guid ) const } } } + return NULL; } + Item* Player::GetItemByPos( uint16 pos ) const { uint8 bag = pos >> 8; uint8 slot = pos & 255; return GetItemByPos( bag, slot ); } + Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const { if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END )) ) @@ -7731,6 +9074,7 @@ Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const } return NULL; } + Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const { uint16 slot; @@ -7741,26 +9085,35 @@ Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) cons case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break; default: return NULL; } + Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, slot); if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON) return NULL; + if(!useable) return item; + if( item->IsBroken() || IsInFeralForm()) return NULL; + return item; } + Item* Player::GetShield(bool useable) const { Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR) return NULL; + if(!useable) return item; + if( item->IsBroken()) return NULL; + return item; } + uint8 Player::GetAttackBySlot( uint8 slot ) { switch(slot) @@ -7771,6 +9124,7 @@ uint8 Player::GetAttackBySlot( uint8 slot ) default: return MAX_ATTACK; } } + bool Player::IsInventoryPos( uint8 bag, uint8 slot ) { if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT ) @@ -7783,6 +9137,7 @@ bool Player::IsInventoryPos( uint8 bag, uint8 slot ) return true; return false; } + bool Player::IsEquipmentPos( uint8 bag, uint8 slot ) { if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) ) @@ -7791,6 +9146,7 @@ bool Player::IsEquipmentPos( uint8 bag, uint8 slot ) return true; return false; } + bool Player::IsBankPos( uint8 bag, uint8 slot ) { if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) ) @@ -7801,6 +9157,7 @@ bool Player::IsBankPos( uint8 bag, uint8 slot ) return true; return false; } + bool Player::IsBagPos( uint16 pos ) { uint8 bag = pos >> 8; @@ -7811,62 +9168,79 @@ bool Player::IsBagPos( uint16 pos ) return true; return false; } + bool Player::IsValidPos( uint8 bag, uint8 slot ) { // post selected if(bag == NULL_BAG) return true; + if (bag == INVENTORY_SLOT_BAG_0) { // any post selected if (slot == NULL_SLOT) return true; + // equipment if (slot < EQUIPMENT_SLOT_END) return true; + // bag equip slots if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END) return true; + // backpack slots if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END) return true; + // keyring slots if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END) return true; + // bank main slots if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END) return true; + // bank bag slots if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END) return true; + return false; } + // bag content slots if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END) { Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag); if(!pBag) return false; + // any post selected if (slot == NULL_SLOT) return true; + return slot < pBag->GetBagSize(); } + // bank bag content slots if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END ) { Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag); if(!pBag) return false; + // any post selected if (slot == NULL_SLOT) return true; + return slot < pBag->GetBagSize(); } + // where this? return false; } + bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const { uint32 tempcount = 0; @@ -7906,6 +9280,7 @@ bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const } } } + if(inBankAlso) { for(uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++) @@ -7935,8 +9310,10 @@ bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const } } } + return false; } + bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const { uint32 tempcount = 0; @@ -7944,6 +9321,7 @@ bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except { if(i == except_slot) continue; + Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if( pItem && pItem->GetEntry() == item) { @@ -7952,6 +9330,7 @@ bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except return true; } } + ItemPrototype const *pProto = objmgr.GetItemPrototype(item); if (pProto && pProto->GemProperties) { @@ -7959,6 +9338,7 @@ bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except { if(i == except_slot) continue; + Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if( pItem && pItem->GetProto()->Socket[0].Color) { @@ -7968,8 +9348,10 @@ bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except } } } + return false; } + bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const { uint32 tempcount = 0; @@ -7977,18 +9359,22 @@ bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 { if(i == except_slot) continue; + Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); if (!pItem) continue; + ItemPrototype const *pProto = pItem->GetProto(); if (!pProto) continue; + if (pProto->ItemLimitCategory == limitCategory) { tempcount += pItem->GetCount(); if( tempcount >= count ) return true; } + if( pProto->Socket[0].Color) { tempcount += pItem->GetGemCountWithLimitCategory(limitCategory); @@ -7996,8 +9382,10 @@ bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 return true; } } + return false; } + uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const { ItemPrototype const *pProto = objmgr.GetItemPrototype(entry); @@ -8007,18 +9395,23 @@ uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, *no_space_count = count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } + // no maximum if(pProto->MaxCount <= 0 || pProto->MaxCount == 2147483647) return EQUIP_ERR_OK; + uint32 curcount = GetItemCount(pProto->ItemId,true,pItem); + if (curcount + count > uint32(pProto->MaxCount)) { if(no_space_count) *no_space_count = count +curcount - pProto->MaxCount; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } + return EQUIP_ERR_OK; } + bool Player::HasItemTotemCategory( uint32 TotemCategory ) const { Item *pItem; @@ -8048,13 +9441,17 @@ bool Player::HasItemTotemCategory( uint32 TotemCategory ) const } return false; } + uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const { Item* pItem2 = GetItemByPos( bag, slot ); + // ignore move item (this slot will be empty at move) if (pItem2==pSrcItem) pItem2 = NULL; + uint32 need_space; + // empty specific slot - check item fit to slot if (!pItem2 || swap) { @@ -8063,9 +9460,11 @@ uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountV // keyring case if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; + // currencytoken case if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; + // prevent cheating if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; @@ -8075,14 +9474,18 @@ uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountV Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ); if (!pBag) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; + ItemPrototype const* pBagProto = pBag->GetProto(); if (!pBagProto) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; + if (slot >= pBagProto->ContainerSlots) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; + if (!ItemCanGoIntoBag(pProto,pBagProto)) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; } + // non empty stack with space need_space = pProto->GetMaxStackSize(); } @@ -8092,14 +9495,18 @@ uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountV // check item type if (pItem2->GetEntry() != pProto->ItemId) return EQUIP_ERR_ITEM_CANT_STACK; + // check free space if (pItem2->GetCount() >= pProto->GetMaxStackSize()) return EQUIP_ERR_ITEM_CANT_STACK; + // free stack space or infinity need_space = pProto->GetMaxStackSize() - pItem2->GetCount(); } + if (need_space > count) need_space = count; + ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space); if (!newPosition.isContainedIn(dest)) { @@ -8108,34 +9515,44 @@ uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountV } return EQUIP_ERR_OK; } + uint8 Player::_CanStoreItem_InBag( uint8 bag, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const { // skip specific bag already processed in first called _CanStoreItem_InBag if (bag==skip_bag) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; + Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ); if (!pBag) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; + ItemPrototype const* pBagProto = pBag->GetProto(); if (!pBagProto) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; + // specialized bag mode or non-specilized if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER)) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; + if (!ItemCanGoIntoBag(pProto,pBagProto)) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; + for(uint32 j = 0; j < pBag->GetBagSize(); j++) { // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot if (j==skip_slot) continue; + Item* pItem2 = GetItemByPos( bag, j ); + // ignore move item (this slot will be empty at move) if (pItem2==pSrcItem) pItem2 = NULL; + // if merge skip empty, if !merge skip non-empty if ((pItem2!=NULL)!=merge) continue; + if (pItem2) { if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize()) @@ -8143,11 +9560,13 @@ uint8 Player::_CanStoreItem_InBag( uint8 bag, ItemPosCountVec &dest, ItemPrototy uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount(); if(need_space > count) need_space = count; + ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space); if (!newPosition.isContainedIn(dest)) { dest.push_back(newPosition); count -= need_space; + if (count==0) return EQUIP_ERR_OK; } @@ -8158,11 +9577,13 @@ uint8 Player::_CanStoreItem_InBag( uint8 bag, ItemPosCountVec &dest, ItemPrototy uint32 need_space = pProto->GetMaxStackSize(); if (need_space > count) need_space = count; + ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space); if (!newPosition.isContainedIn(dest)) { dest.push_back(newPosition); count -= need_space; + if (count==0) return EQUIP_ERR_OK; } @@ -8170,6 +9591,7 @@ uint8 Player::_CanStoreItem_InBag( uint8 bag, ItemPosCountVec &dest, ItemPrototy } return EQUIP_ERR_OK; } + uint8 Player::_CanStoreItem_InInventorySlots( uint8 slot_begin, uint8 slot_end, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const { for(uint32 j = slot_begin; j < slot_end; j++) @@ -8177,13 +9599,17 @@ uint8 Player::_CanStoreItem_InInventorySlots( uint8 slot_begin, uint8 slot_end, // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot) continue; + Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j ); + // ignore move item (this slot will be empty at move) if (pItem2==pSrcItem) pItem2 = NULL; + // if merge skip empty, if !merge skip non-empty if ((pItem2!=NULL)!=merge) continue; + if (pItem2) { if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize()) @@ -8196,6 +9622,7 @@ uint8 Player::_CanStoreItem_InInventorySlots( uint8 slot_begin, uint8 slot_end, { dest.push_back(newPosition); count -= need_space; + if (count==0) return EQUIP_ERR_OK; } @@ -8206,11 +9633,13 @@ uint8 Player::_CanStoreItem_InInventorySlots( uint8 slot_begin, uint8 slot_end, uint32 need_space = pProto->GetMaxStackSize(); if (need_space > count) need_space = count; + ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space); if (!newPosition.isContainedIn(dest)) { dest.push_back(newPosition); count -= need_space; + if (count==0) return EQUIP_ERR_OK; } @@ -8218,9 +9647,11 @@ uint8 Player::_CanStoreItem_InInventorySlots( uint8 slot_begin, uint8 slot_end, } return EQUIP_ERR_OK; } + uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const { sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count); + ItemPrototype const *pProto = objmgr.GetItemPrototype(entry); if (!pProto) { @@ -8228,12 +9659,14 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 *no_space_count = count; return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND; } + if (pItem && pItem->IsBindedNotWith(this)) { if (no_space_count) *no_space_count = count; return EQUIP_ERR_DONT_OWN_THAT_ITEM; } + // check count of items (skip for auto move for same player from bank) uint32 no_similar_count = 0; // can't store this amount similar items uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count); @@ -8247,6 +9680,7 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 } count -= no_similar_count; } + // in specific slot if (bag != NULL_BAG && slot != NULL_SLOT) { @@ -8257,16 +9691,20 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } + // not specific slot or have space for partly store only in specific slot + // in specific bag if (bag != NULL_BAG) { @@ -8282,14 +9720,17 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } + res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot); if (res!=EQUIP_ERR_OK) { @@ -8297,10 +9738,12 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; @@ -8312,22 +9755,26 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot); if (res!=EQUIP_ERR_OK) res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot); + if (res!=EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } } + // search free slot in bag for place to if(bag == INVENTORY_SLOT_BAG_0) // inventory { @@ -8342,14 +9789,17 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } + res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot); if (res!=EQUIP_ERR_OK) { @@ -8357,10 +9807,12 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; @@ -8375,15 +9827,18 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } + res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot); if (res!=EQUIP_ERR_OK) { @@ -8391,10 +9846,12 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; @@ -8405,23 +9862,28 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot); if (res!=EQUIP_ERR_OK) res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot); + if (res!=EQUIP_ERR_OK) { if (no_space_count) *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } } + // not specific bag or have space for partly store only in specific bag + // search stack for merge to if (pProto->Stackable != 1) { @@ -8432,14 +9894,17 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } + res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot); if (res!=EQUIP_ERR_OK) { @@ -8447,14 +9912,17 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } + if (pProto->BagFamily) { for(uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) @@ -8462,31 +9930,37 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot); if (res!=EQUIP_ERR_OK) continue; + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } } + for(uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) { res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot); if (res!=EQUIP_ERR_OK) continue; + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } } + // search free slot - special bag case if (pProto->BagFamily) { @@ -8500,10 +9974,12 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; @@ -8518,30 +9994,36 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } + for(uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) { res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot); if (res!=EQUIP_ERR_OK) continue; + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } } + // search free slot res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot); if (res!=EQUIP_ERR_OK) @@ -8550,69 +10032,86 @@ uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint3 *no_space_count = count + no_similar_count; return res; } + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } + for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) { res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot); if (res!=EQUIP_ERR_OK) continue; + if (count==0) { if (no_similar_count==0) return EQUIP_ERR_OK; + if (no_space_count) *no_space_count = count + no_similar_count; return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } + if (no_space_count) *no_space_count = count + no_similar_count; + return EQUIP_ERR_INVENTORY_FULL; } + ////////////////////////////////////////////////////////////////////////// uint8 Player::CanStoreItems( Item **pItems,int count) const { Item *pItem2; + // fill space table int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START]; int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE]; int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START]; int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START]; + memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START)); memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE); memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START)); memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START)); + for(uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++) { pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); + if (pItem2 && !pItem2->IsInTrade()) { inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount(); } } + for(uint8 i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++) { pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); + if (pItem2 && !pItem2->IsInTrade()) { inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount(); } } + for(uint8 i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++) { pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i ); + if (pItem2 && !pItem2->IsInTrade()) { inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount(); } } + for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) { if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) @@ -8627,30 +10126,39 @@ uint8 Player::CanStoreItems( Item **pItems,int count) const } } } + // check free space for all items for (int k = 0; k < count; ++k) { Item *pItem = pItems[k]; + // no item if (!pItem) continue; + sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount()); ItemPrototype const *pProto = pItem->GetProto(); + // strange item if( !pProto ) return EQUIP_ERR_ITEM_NOT_FOUND; + // item it 'bind' if(pItem->IsBindedNotWith(this)) return EQUIP_ERR_DONT_OWN_THAT_ITEM; + Bag *pBag; ItemPrototype const *pBagProto; + // item is 'one item only' uint8 res = CanTakeMoreSimilarItems(pItem); if(res != EQUIP_ERR_OK) return res; + // search stack for merge to if( pProto->Stackable != 1 ) { bool b_found = false; + for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t) { pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t ); @@ -8662,6 +10170,7 @@ uint8 Player::CanStoreItems( Item **pItems,int count) const } } if (b_found) continue; + for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t) { pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t ); @@ -8673,6 +10182,7 @@ uint8 Player::CanStoreItems( Item **pItems,int count) const } } if (b_found) continue; + for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t) { pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t ); @@ -8684,6 +10194,7 @@ uint8 Player::CanStoreItems( Item **pItems,int count) const } } if (b_found) continue; + for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t) { pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t ); @@ -8703,6 +10214,7 @@ uint8 Player::CanStoreItems( Item **pItems,int count) const } if (b_found) continue; } + // special bag case if( pProto->BagFamily ) { @@ -8720,7 +10232,9 @@ uint8 Player::CanStoreItems( Item **pItems,int count) const } } } + if (b_found) continue; + if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS) { for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t) @@ -8733,13 +10247,16 @@ uint8 Player::CanStoreItems( Item **pItems,int count) const } } } + if (b_found) continue; + for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t) { pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t ); if( pBag ) { pBagProto = pBag->GetProto(); + // not plain container check if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) && ItemCanGoIntoBag(pProto,pBagProto) ) @@ -8758,6 +10275,7 @@ uint8 Player::CanStoreItems( Item **pItems,int count) const } if (b_found) continue; } + // search free slot bool b_found = false; for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t) @@ -8770,6 +10288,7 @@ uint8 Player::CanStoreItems( Item **pItems,int count) const } } if (b_found) continue; + // search free slot in bags for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t) { @@ -8777,9 +10296,11 @@ uint8 Player::CanStoreItems( Item **pItems,int count) const if( pBag ) { pBagProto = pBag->GetProto(); + // special bag already checked if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER)) continue; + for(uint32 j = 0; j < pBag->GetBagSize(); j++) { if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 ) @@ -8791,12 +10312,15 @@ uint8 Player::CanStoreItems( Item **pItems,int count) const } } } + // no free slot found? if (!b_found) return EQUIP_ERR_INVENTORY_FULL; } + return EQUIP_ERR_OK; } + ////////////////////////////////////////////////////////////////////////// uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const { @@ -8808,8 +10332,10 @@ uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap delete pItem; return result; } + return EQUIP_ERR_ITEM_NOT_FOUND; } + uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const { dest = 0; @@ -8821,10 +10347,12 @@ uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bo { if(pItem->IsBindedNotWith(this)) return EQUIP_ERR_DONT_OWN_THAT_ITEM; + // check count of items (skip for auto move for same player from bank) uint8 res = CanTakeMoreSimilarItems(pItem); if(res != EQUIP_ERR_OK) return res; + // check this only in game if(not_loading) { @@ -8832,6 +10360,7 @@ uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bo // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked. if (hasUnitState(UNIT_STAT_STUNNED)) return EQUIP_ERR_YOU_ARE_STUNNED; + // do not allow equipping gear except weapons, offhands, projectiles, relics in // - combat // - in-progress arenas @@ -8839,30 +10368,38 @@ uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bo { if( isInCombat() ) return EQUIP_ERR_NOT_IN_COMBAT; + if(BattleGround* bg = GetBattleGround()) if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS ) return EQUIP_ERR_NOT_DURING_ARENA_MATCH; } + if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0) return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err + if(IsNonMeleeSpellCasted(false)) return EQUIP_ERR_CANT_DO_RIGHT_NOW; } + ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0; // check allowed level (extend range to upper values if MaxLevel more or equal max player level, this let GM set high level with 1...max range items) if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel()) return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED; + uint8 eslot = FindEquipSlot( pProto, slot, swap ); if (eslot == NULL_SLOT) return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED; + uint8 msg = CanUseItem(pItem , not_loading); if (msg != EQUIP_ERR_OK) return msg; if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot)) return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE; + // if swap ignore item (equipped also) if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT)) return res2; + // check unique-equipped special item classes if (pProto->Class == ITEM_CLASS_QUIVER) { @@ -8883,7 +10420,9 @@ uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bo } } } + uint32 type = pProto->InventoryType; + if (eslot == EQUIPMENT_SLOT_OFFHAND) { if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND) @@ -8896,9 +10435,11 @@ uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bo if (!CanDualWield() || !CanTitanGrip()) return EQUIP_ERR_CANT_DUAL_WIELD; } + if (IsTwoHandUsed()) return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED; } + // equip two-hand weapon case (with possible unequip 2 items) if (type == INVTYPE_2HWEAPON) { @@ -8909,6 +10450,7 @@ uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bo } else if (eslot != EQUIPMENT_SLOT_MAINHAND) return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED; + if (!CanTitanGrip()) { // offhand item must can be stored in inventory for offhand item and it also must be unequipped @@ -8924,21 +10466,28 @@ uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bo return EQUIP_ERR_OK; } } + return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED; } + uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const { // Applied only to equipped items and bank bags if(!IsEquipmentPos(pos) && !IsBagPos(pos)) return EQUIP_ERR_OK; + Item* pItem = GetItemByPos(pos); + // Applied only to existed equipped item if( !pItem ) return EQUIP_ERR_OK; + sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount()); + ItemPrototype const *pProto = pItem->GetProto(); if( !pProto ) return EQUIP_ERR_ITEM_NOT_FOUND; + // do not allow unequipping gear except weapons, offhands, projectiles, relics in // - combat // - in-progress arenas @@ -8946,29 +10495,38 @@ uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const { if( isInCombat() ) return EQUIP_ERR_NOT_IN_COMBAT; + if(BattleGround* bg = GetBattleGround()) if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS ) return EQUIP_ERR_NOT_DURING_ARENA_MATCH; } + if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty()) return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS; + return EQUIP_ERR_OK; } + uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const { if (!pItem) return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND; + uint32 count = pItem->GetCount(); + sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount()); ItemPrototype const *pProto = pItem->GetProto(); if (!pProto) return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND; + if (pItem->IsBindedNotWith(this)) return EQUIP_ERR_DONT_OWN_THAT_ITEM; + // check count of items (skip for auto move for same player from bank) uint8 res = CanTakeMoreSimilarItems(pItem); if (res != EQUIP_ERR_OK) return res; + // in specific slot if (bag != NULL_BAG && slot != NULL_SLOT) { @@ -8976,18 +10534,24 @@ uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *p { if (!pItem->IsBag()) return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT; + if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount()) return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT; + if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK) return cantuse; } + res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem); if (res!=EQUIP_ERR_OK) return res; + if (count==0) return EQUIP_ERR_OK; } + // not specific slot or have space for partly store only in specific slot + // in specific bag if( bag != NULL_BAG ) { @@ -8997,6 +10561,7 @@ uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *p if( pBag && !pBag->IsEmpty() ) return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG; } + // search stack in bag for merge to if( pProto->Stackable != 1 ) { @@ -9005,6 +10570,7 @@ uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *p res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot); if(res!=EQUIP_ERR_OK) return res; + if(count==0) return EQUIP_ERR_OK; } @@ -9013,18 +10579,22 @@ uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *p res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot); if(res!=EQUIP_ERR_OK) res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot); + if(res!=EQUIP_ERR_OK) return res; + if(count==0) return EQUIP_ERR_OK; } } + // search free slot in bag if( bag == INVENTORY_SLOT_BAG_0 ) { res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot); if(res!=EQUIP_ERR_OK) return res; + if(count==0) return EQUIP_ERR_OK; } @@ -9033,13 +10603,17 @@ uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *p res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot); if(res != EQUIP_ERR_OK) res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot); + if(res != EQUIP_ERR_OK) return res; + if(count == 0) return EQUIP_ERR_OK; } } + // not specific bag or have space for partly store only in specific bag + // search stack for merge to if( pProto->Stackable != 1 ) { @@ -9047,8 +10621,10 @@ uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *p res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot); if(res != EQUIP_ERR_OK) return res; + if(count == 0) return EQUIP_ERR_OK; + // in special bags if( pProto->BagFamily ) { @@ -9057,19 +10633,23 @@ uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *p res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot); if(res!=EQUIP_ERR_OK) continue; + if(count==0) return EQUIP_ERR_OK; } } + for(uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++) { res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot); if(res!=EQUIP_ERR_OK) continue; + if(count==0) return EQUIP_ERR_OK; } } + // search free place in special bag if( pProto->BagFamily ) { @@ -9078,68 +10658,87 @@ uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *p res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot); if(res!=EQUIP_ERR_OK) continue; + if(count==0) return EQUIP_ERR_OK; } } + // search free space res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot); if(res!=EQUIP_ERR_OK) return res; + if(count==0) return EQUIP_ERR_OK; + for(uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++) { res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot); if(res!=EQUIP_ERR_OK) continue; + if(count==0) return EQUIP_ERR_OK; } return EQUIP_ERR_BANK_FULL; } + uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const { if (pItem) { sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry()); + if (!isAlive() && not_loading) return EQUIP_ERR_YOU_ARE_DEAD; + //if (isStunned()) // return EQUIP_ERR_YOU_ARE_STUNNED; + ItemPrototype const *pProto = pItem->GetProto(); if (pProto) { if (pItem->IsBindedNotWith(this)) return EQUIP_ERR_DONT_OWN_THAT_ITEM; + if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0) return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM; + if (pItem->GetSkill() != 0) { if (GetSkillValue( pItem->GetSkill() ) == 0) return EQUIP_ERR_NO_REQUIRED_PROFICIENCY; } + if (pProto->RequiredSkill != 0) { if (GetSkillValue( pProto->RequiredSkill ) == 0) return EQUIP_ERR_NO_REQUIRED_PROFICIENCY; + if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank) return EQUIP_ERR_ERR_CANT_EQUIP_SKILL; } + if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell)) return EQUIP_ERR_NO_REQUIRED_PROFICIENCY; + if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank) return EQUIP_ERR_CANT_EQUIP_REPUTATION; + if (getLevel() < pProto->RequiredLevel) return EQUIP_ERR_CANT_EQUIP_LEVEL_I; + return EQUIP_ERR_OK; } } return EQUIP_ERR_ITEM_NOT_FOUND; } + bool Player::CanUseItem( ItemPrototype const *pProto ) { // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player + if( pProto ) { if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 ) @@ -9159,6 +10758,7 @@ bool Player::CanUseItem( ItemPrototype const *pProto ) } return false; } + uint8 Player::CanUseAmmo( uint32 item ) const { sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item); @@ -9187,20 +10787,25 @@ uint8 Player::CanUseAmmo( uint32 item ) const */ if( getLevel() < pProto->RequiredLevel ) return EQUIP_ERR_CANT_EQUIP_LEVEL_I; + // Requires No Ammo if(HasAura(46699)) return EQUIP_ERR_BAG_FULL6; + return EQUIP_ERR_OK; } return EQUIP_ERR_ITEM_NOT_FOUND; } + void Player::SetAmmo( uint32 item ) { if(!item) return; + // already set if( GetUInt32Value(PLAYER_AMMO_ID) == item ) return; + // check ammo if(item) { @@ -9211,22 +10816,29 @@ void Player::SetAmmo( uint32 item ) return; } } + SetUInt32Value(PLAYER_AMMO_ID, item); + _ApplyAmmoBonuses(); } + void Player::RemoveAmmo() { SetUInt32Value(PLAYER_AMMO_ID, 0); + m_ammoDPS = 0.0f; + if(CanModifyStats()) UpdateDamagePhysical(RANGED_ATTACK); } + // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case. Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId ) { uint32 count = 0; for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr) count += itr->count; + Item *pItem = Item::CreateItem( item, count, this ); if( pItem ) { @@ -9237,64 +10849,81 @@ Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool updat } return pItem; } + Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update ) { if( !pItem ) return NULL; + Item* lastItem = pItem; uint32 entry = pItem->GetEntry(); for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ) { uint16 pos = itr->pos; uint32 count = itr->count; + ++itr; + if(itr == dest.end()) { lastItem = _StoreItem(pos,pItem,count,false,update); break; } + lastItem = _StoreItem(pos,pItem,count,true,update); } GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry); return lastItem; } + // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case. Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update ) { if( !pItem ) return NULL; + uint8 bag = pos >> 8; uint8 slot = pos & 255; + sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u, guid = %u", bag, slot, pItem->GetEntry(), count, pItem->GetGUIDLow()); + Item *pItem2 = GetItemByPos( bag, slot ); + if (!pItem2) { if (clone) pItem = pItem->CloneItem(count, this); else pItem->SetCount(count); + if (!pItem) return NULL; + if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM || (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos))) pItem->SetBinding( true ); + if (bag == INVENTORY_SLOT_BAG_0) { m_items[slot] = pItem; SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() ); pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() ); pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() ); + pItem->SetSlot( slot ); pItem->SetContainer( NULL ); + // need update known currency if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END) UpdateKnownCurrencies(pItem->GetEntry(), true); + if (IsInWorld() && update) { pItem->AddToWorld(); pItem->SendUpdateToPlayer( this ); } + pItem->SetState(ITEM_CHANGED, this); } else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag )) @@ -9308,8 +10937,10 @@ Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, boo pItem->SetState(ITEM_CHANGED, this); pBag->SetState(ITEM_CHANGED, this); } + AddEnchantmentDurations(pItem); AddItemDurations(pItem); + return pItem; } else @@ -9318,9 +10949,11 @@ Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, boo pItem2->GetProto()->Bonding == BIND_QUEST_ITEM || (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos))) pItem2->SetBinding( true ); + pItem2->SetCount( pItem2->GetCount() + count ); if (IsInWorld() && update) pItem2->SendUpdateToPlayer( this ); + if (!clone) { // delete item (it not in any slot currently) @@ -9329,17 +10962,23 @@ Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, boo pItem->RemoveFromWorld(); pItem->DestroyForPlayer( this ); } + RemoveEnchantmentDurations(pItem); RemoveItemDurations(pItem); + pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor pItem->SetState(ITEM_REMOVED, this); } + // AddItemDurations(pItem2); - pItem2 already have duration listed for player AddEnchantmentDurations(pItem2); + pItem2->SetState(ITEM_CHANGED, this); + return pItem2; } } + Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update ) { if (Item *pItem = Item::CreateItem( item, 1, this )) @@ -9347,36 +10986,49 @@ Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update ) ItemAddedQuestCheck( item, 1 ); return EquipItem( pos, pItem, update ); } + return NULL; } + Item* Player::EquipItem( uint16 pos, Item *pItem, bool update ) { AddEnchantmentDurations(pItem); AddItemDurations(pItem); + uint8 bag = pos >> 8; uint8 slot = pos & 255; + Item *pItem2 = GetItemByPos( bag, slot ); + if( !pItem2 ) { VisualizeItem( slot, pItem); + if(isAlive()) { ItemPrototype const *pProto = pItem->GetProto(); + // item set bonuses applied only at equip and removed at unequip, and still active for broken items if(pProto && pProto->ItemSet) AddItemsSetItem(this, pItem); + _ApplyItemMods(pItem, slot, true); + if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0) { uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s; + if (getClass() == CLASS_ROGUE) cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s; + SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell); + if (!spellProto) sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell); else { m_weaponChangeTimer = spellProto->StartRecoveryTime; + WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4); data << uint64(GetGUID()); data << uint8(1); @@ -9386,17 +11038,23 @@ Item* Player::EquipItem( uint16 pos, Item *pItem, bool update ) } } } + if( IsInWorld() && update ) { pItem->AddToWorld(); pItem->SendUpdateToPlayer( this ); } + ApplyEquipCooldown(pItem); + // update expertise and armor penetration - passive auras may need it + if( slot == EQUIPMENT_SLOT_MAINHAND ) UpdateExpertise(BASE_ATTACK); + else if( slot == EQUIPMENT_SLOT_OFFHAND ) UpdateExpertise(OFF_ATTACK); + switch(slot) { case EQUIPMENT_SLOT_MAINHAND: @@ -9412,6 +11070,7 @@ Item* Player::EquipItem( uint16 pos, Item *pItem, bool update ) pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() ); if( IsInWorld() && update ) pItem2->SendUpdateToPlayer( this ); + // delete item (it not in any slot currently) //pItem->DeleteFromDB(); if( IsInWorld() && update ) @@ -9419,34 +11078,45 @@ Item* Player::EquipItem( uint16 pos, Item *pItem, bool update ) pItem->RemoveFromWorld(); pItem->DestroyForPlayer( this ); } + RemoveEnchantmentDurations(pItem); RemoveItemDurations(pItem); + pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor pItem->SetState(ITEM_REMOVED, this); pItem2->SetState(ITEM_CHANGED, this); + ApplyEquipCooldown(pItem2); + return pItem2; } + // only for full equip instead adding to stack GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry()); + return pItem; } + void Player::QuickEquipItem( uint16 pos, Item *pItem) { if( pItem ) { AddEnchantmentDurations(pItem); AddItemDurations(pItem); + uint8 slot = pos & 255; VisualizeItem( slot, pItem); + if( IsInWorld() ) { pItem->AddToWorld(); pItem->SendUpdateToPlayer( this ); } + GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry()); } } + void Player::SetVisibleItemSlot(uint8 slot, Item *pItem) { if(pItem) @@ -9461,49 +11131,63 @@ void Player::SetVisibleItemSlot(uint8 slot, Item *pItem) SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0); } } + void Player::VisualizeItem( uint8 slot, Item *pItem) { if(!pItem) return; + // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory) if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM ) pItem->SetBinding( true ); + sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry()); + m_items[slot] = pItem; SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() ); pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() ); pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() ); pItem->SetSlot( slot ); pItem->SetContainer( NULL ); + if( slot < EQUIPMENT_SLOT_END ) SetVisibleItemSlot(slot, pItem); + pItem->SetState(ITEM_CHANGED, this); } + void Player::RemoveItem( uint8 bag, uint8 slot, bool update ) { // note: removeitem does not actually change the item // it only takes the item out of storage temporarily // note2: if removeitem is to be used for delinking // the item must be removed from the player's updatequeue + Item *pItem = GetItemByPos( bag, slot ); if( pItem ) { sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry()); + RemoveEnchantmentDurations(pItem); RemoveItemDurations(pItem); + if( bag == INVENTORY_SLOT_BAG_0 ) { if ( slot < INVENTORY_SLOT_BAG_END ) { ItemPrototype const *pProto = pItem->GetProto(); // item set bonuses applied only at equip and removed at unequip, and still active for broken items + if(pProto && pProto->ItemSet) RemoveItemsSetItem(this, pProto); + _ApplyItemMods(pItem, slot, false); + // remove item dependent auras and casts (only weapon and armor slots) if(slot < EQUIPMENT_SLOT_END) { RemoveItemDependentAurasAndCasts(pItem); + // remove held enchantments, update expertise if ( slot == EQUIPMENT_SLOT_MAINHAND ) { @@ -9517,6 +11201,7 @@ void Player::RemoveItem( uint8 bag, uint8 slot, bool update ) pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0); pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1); } + UpdateExpertise(BASE_ATTACK); } else if( slot == EQUIPMENT_SLOT_OFFHAND ) @@ -9536,8 +11221,10 @@ void Player::RemoveItem( uint8 bag, uint8 slot, bool update ) // need update known currency else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END) UpdateKnownCurrencies(pItem->GetEntry(), false); + m_items[slot] = NULL; SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0); + if ( slot < EQUIPMENT_SLOT_END ) SetVisibleItemSlot(slot, NULL); } @@ -9554,6 +11241,7 @@ void Player::RemoveItem( uint8 bag, uint8 slot, bool update ) pItem->SendUpdateToPlayer( this ); } } + // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail.... void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update) { @@ -9569,57 +11257,72 @@ void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update) } } } + // Common operation need to add item from inventory without delete in trade, guild bank, mail.... void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB) { // update quest counters ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount()); + // store item Item* pLastItem = StoreItem(dest, pItem, update); + // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way) if(pLastItem == pItem) { // update owner for last item (this can be original item with wrong owner if(pLastItem->GetOwnerGUID() != GetGUID()) pLastItem->SetOwnerGUID(GetGUID()); + // if this original item then it need create record in inventory // in case trade we already have item in other player inventory pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this); } } + void Player::DestroyItem( uint8 bag, uint8 slot, bool update ) { Item *pItem = GetItemByPos( bag, slot ); if( pItem ) { sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry()); + // start from destroy contained items (only equipped bag can have its) if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot { for (uint8 i = 0; i < MAX_BAG_SIZE; ++i) DestroyItem(slot, i, update); } + if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED)) CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow()); + RemoveEnchantmentDurations(pItem); RemoveItemDurations(pItem); + ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() ); + if( bag == INVENTORY_SLOT_BAG_0 ) { SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0); + // equipment and equipped bags can have applied bonuses if ( slot < INVENTORY_SLOT_BAG_END ) { ItemPrototype const *pProto = pItem->GetProto(); + // item set bonuses applied only at equip and removed at unequip, and still active for broken items if(pProto && pProto->ItemSet) RemoveItemsSetItem(this, pProto); + _ApplyItemMods(pItem, slot, false); } + if ( slot < EQUIPMENT_SLOT_END ) { // remove item dependent auras and casts (only weapon and armor slots) RemoveItemDependentAurasAndCasts(pItem); + // update expertise and armor penetration - passive auras may need it switch(slot) { @@ -9630,35 +11333,43 @@ void Player::DestroyItem( uint8 bag, uint8 slot, bool update ) default: break; } + if( slot == EQUIPMENT_SLOT_MAINHAND ) UpdateExpertise(BASE_ATTACK); + else if( slot == EQUIPMENT_SLOT_OFFHAND ) UpdateExpertise(OFF_ATTACK); + // equipment visual show SetVisibleItemSlot(slot, NULL); } // need update known currency else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END) UpdateKnownCurrencies(pItem->GetEntry(), false); + m_items[slot] = NULL; } else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag )) pBag->RemoveItem(slot, update); + if( IsInWorld() && update ) { pItem->RemoveFromWorld(); pItem->DestroyForPlayer(this); } + //pItem->SetOwnerGUID(0); pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 ); pItem->SetSlot( NULL_SLOT ); pItem->SetState(ITEM_REMOVED, this); } } + void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check) { sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count); uint32 remcount = 0; + // in inventory for(uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++) { @@ -9671,6 +11382,7 @@ void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool uneq // all items in inventory can unequipped remcount += pItem->GetCount(); DestroyItem( INVENTORY_SLOT_BAG_0, i, update); + if (remcount >= count) return; } @@ -9686,6 +11398,7 @@ void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool uneq } } } + for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) { if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) @@ -9697,6 +11410,7 @@ void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool uneq // all keys can be unequipped remcount += pItem->GetCount(); DestroyItem( INVENTORY_SLOT_BAG_0, i, update); + if (remcount >= count) return; } @@ -9712,6 +11426,7 @@ void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool uneq } } } + // in inventory bags for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) { @@ -9728,6 +11443,7 @@ void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool uneq { remcount += pItem->GetCount(); DestroyItem( i, j, update ); + if (remcount >= count) return; } @@ -9745,6 +11461,7 @@ void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool uneq } } } + // in equipment and bag list for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++) { @@ -9758,6 +11475,7 @@ void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool uneq { remcount += pItem->GetCount(); DestroyItem( INVENTORY_SLOT_BAG_0, i, update); + if (remcount >= count) return; } @@ -9775,18 +11493,22 @@ void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool uneq } } } + void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone ) { sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone ); + // in inventory for(uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++) if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone)) DestroyItem( INVENTORY_SLOT_BAG_0, i, update); + for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone)) DestroyItem( INVENTORY_SLOT_BAG_0, i, update); + // in inventory bags for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) @@ -9794,22 +11516,26 @@ void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone ) if (Item* pItem = pBag->GetItemByPos(j)) if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone)) DestroyItem(i, j, update); + // in equipment and bag list for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++) if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone)) DestroyItem( INVENTORY_SLOT_BAG_0, i, update); } + void Player::DestroyConjuredItems( bool update ) { // used when entering arena // destroys all conjured items sLog.outDebug( "STORAGE: DestroyConjuredItems" ); + // in inventory for(uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++) if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) if (pItem->IsConjuredConsumable()) DestroyItem( INVENTORY_SLOT_BAG_0, i, update); + // in inventory bags for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) @@ -9817,20 +11543,25 @@ void Player::DestroyConjuredItems( bool update ) if (Item* pItem = pBag->GetItemByPos(j)) if (pItem->IsConjuredConsumable()) DestroyItem( i, j, update); + // in equipment and bag list for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++) if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i )) if (pItem->IsConjuredConsumable()) DestroyItem( INVENTORY_SLOT_BAG_0, i, update); } + void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update ) { if(!pItem) return; + sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count); + if( pItem->GetCount() <= count ) { count -= pItem->GetCount(); + DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update); } else @@ -9843,36 +11574,43 @@ void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update ) pItem->SetState(ITEM_CHANGED, this); } } + void Player::SplitItem( uint16 src, uint16 dst, uint32 count ) { uint8 srcbag = src >> 8; uint8 srcslot = src & 255; + uint8 dstbag = dst >> 8; uint8 dstslot = dst & 255; + Item *pSrcItem = GetItemByPos( srcbag, srcslot ); if( !pSrcItem ) { SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL ); return; } + // not let split all items (can be only at cheating) if(pSrcItem->GetCount() == count) { SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL ); return; } + // not let split more existed items (can be only at cheating) if(pSrcItem->GetCount() < count) { SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL ); return; } + if(pSrcItem->m_lootGenerated) // prevent split looting item (item { //best error message found for attempting to split while looting SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL ); return; } + sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count); Item *pNewItem = pSrcItem->CloneItem( count, this ); if( !pNewItem ) @@ -9880,10 +11618,12 @@ void Player::SplitItem( uint16 src, uint16 dst, uint32 count ) SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL ); return; } + if( IsInventoryPos( dst ) ) { // change item amount before check (for unique max count check) pSrcItem->SetCount( pSrcItem->GetCount() - count ); + ItemPosCountVec dest; uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false ); if( msg != EQUIP_ERR_OK ) @@ -9893,6 +11633,7 @@ void Player::SplitItem( uint16 src, uint16 dst, uint32 count ) SendEquipError( msg, pSrcItem, NULL ); return; } + if( IsInWorld() ) pSrcItem->SendUpdateToPlayer( this ); pSrcItem->SetState(ITEM_CHANGED, this); @@ -9902,6 +11643,7 @@ void Player::SplitItem( uint16 src, uint16 dst, uint32 count ) { // change item amount before check (for unique max count check) pSrcItem->SetCount( pSrcItem->GetCount() - count ); + ItemPosCountVec dest; uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false ); if( msg != EQUIP_ERR_OK ) @@ -9911,6 +11653,7 @@ void Player::SplitItem( uint16 src, uint16 dst, uint32 count ) SendEquipError( msg, pSrcItem, NULL ); return; } + if( IsInWorld() ) pSrcItem->SendUpdateToPlayer( this ); pSrcItem->SetState(ITEM_CHANGED, this); @@ -9920,6 +11663,7 @@ void Player::SplitItem( uint16 src, uint16 dst, uint32 count ) { // change item amount before check (for unique max count check), provide space for splitted items pSrcItem->SetCount( pSrcItem->GetCount() - count ); + uint16 dest; uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false ); if( msg != EQUIP_ERR_OK ) @@ -9929,6 +11673,7 @@ void Player::SplitItem( uint16 src, uint16 dst, uint32 count ) SendEquipError( msg, pSrcItem, NULL ); return; } + if( IsInWorld() ) pSrcItem->SendUpdateToPlayer( this ); pSrcItem->SetState(ITEM_CHANGED, this); @@ -9936,29 +11681,38 @@ void Player::SplitItem( uint16 src, uint16 dst, uint32 count ) AutoUnequipOffhandIfNeed(); } } + void Player::SwapItem( uint16 src, uint16 dst ) { uint8 srcbag = src >> 8; uint8 srcslot = src & 255; + uint8 dstbag = dst >> 8; uint8 dstslot = dst & 255; + Item *pSrcItem = GetItemByPos( srcbag, srcslot ); Item *pDstItem = GetItemByPos( dstbag, dstslot ); + if( !pSrcItem ) return; + sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry()); + if(!isAlive() ) { SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem ); return; } + // SRC checks + if(pSrcItem->m_lootGenerated) // prevent swap looting item { //best error message found for attempting to swap while looting SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL ); return; } + // check unequip potability for equipped items and bank bags if(IsEquipmentPos ( src ) || IsBagPos ( src )) { @@ -9970,13 +11724,16 @@ void Player::SwapItem( uint16 src, uint16 dst ) return; } } + // prevent put equipped/bank bag in self if( IsBagPos ( src ) && srcslot == dstbag) { SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem ); return; } + // DST checks + if (pDstItem) { if(pDstItem->m_lootGenerated) // prevent swap looting item @@ -9985,6 +11742,7 @@ void Player::SwapItem( uint16 src, uint16 dst ) SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL ); return; } + // check unequip potability for equipped items and bank bags if(IsEquipmentPos ( dst ) || IsBagPos ( dst )) { @@ -9997,8 +11755,10 @@ void Player::SwapItem( uint16 src, uint16 dst ) } } } + // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions) // or swap empty bag with another empty or not empty bag (with items exchange) + // Move case if( !pDstItem ) { @@ -10011,6 +11771,7 @@ void Player::SwapItem( uint16 src, uint16 dst ) SendEquipError( msg, pSrcItem, NULL ); return; } + RemoveItem(srcbag, srcslot, true); StoreItem( dest, pSrcItem, true); } @@ -10023,6 +11784,7 @@ void Player::SwapItem( uint16 src, uint16 dst ) SendEquipError( msg, pSrcItem, NULL ); return; } + RemoveItem(srcbag, srcslot, true); BankItem( dest, pSrcItem, true); } @@ -10035,12 +11797,15 @@ void Player::SwapItem( uint16 src, uint16 dst ) SendEquipError( msg, pSrcItem, NULL ); return; } + RemoveItem(srcbag, srcslot, true); EquipItem(dest, pSrcItem, true); AutoUnequipOffhandIfNeed(); } + return; } + // attempt merge to / fill target item if(!pSrcItem->IsBag() && !pDstItem->IsBag()) { @@ -10055,12 +11820,14 @@ void Player::SwapItem( uint16 src, uint16 dst ) msg = CanEquipItem( dstslot, eDest, pSrcItem, false ); else return; + // can be merge/fill if(msg == EQUIP_ERR_OK) { if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize()) { RemoveItem(srcbag, srcslot, true); + if( IsInventoryPos( dst ) ) StoreItem( sDest, pSrcItem, true); else if( IsBankPos ( dst ) ) @@ -10086,8 +11853,10 @@ void Player::SwapItem( uint16 src, uint16 dst ) return; } } + // impossible merge/fill, do real swap uint8 msg; + // check src->dest move possibility ItemPosCountVec sDest; uint16 eDest = 0; @@ -10101,11 +11870,13 @@ void Player::SwapItem( uint16 src, uint16 dst ) if( msg == EQUIP_ERR_OK ) msg = CanUnequipItem( eDest, true ); } + if( msg != EQUIP_ERR_OK ) { SendEquipError( msg, pSrcItem, pDstItem ); return; } + // check dest->src move possibility ItemPosCountVec sDest2; uint16 eDest2 = 0; @@ -10119,11 +11890,13 @@ void Player::SwapItem( uint16 src, uint16 dst ) if( msg == EQUIP_ERR_OK ) msg = CanUnequipItem( eDest2, true); } + if( msg != EQUIP_ERR_OK ) { SendEquipError( msg, pDstItem, pSrcItem ); return; } + // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store) if(pSrcItem->IsBag() && pDstItem->IsBag()) { @@ -10139,16 +11912,20 @@ void Player::SwapItem( uint16 src, uint16 dst ) emptyBag = (Bag*)pDstItem; fullBag = (Bag*)pSrcItem; } + // bag swap (with items exchange) case if(emptyBag && fullBag) { ItemPrototype const* emotyProto = emptyBag->GetProto(); + uint32 count = 0; + for(uint32 i=0; i < fullBag->GetBagSize(); ++i) { Item *bagItem = fullBag->GetItemByPos(i); if (!bagItem) continue; + ItemPrototype const* bagItemProto = bagItem->GetProto(); if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto)) { @@ -10156,15 +11933,18 @@ void Player::SwapItem( uint16 src, uint16 dst ) SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem ); return; } + ++count; } + if (count > emptyBag->GetBagSize()) { // too small targeted bag SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem ); return; } + // Items swap count = 0; // will pos in new bag for(uint32 i = 0; i< fullBag->GetBagSize(); ++i) @@ -10172,16 +11952,20 @@ void Player::SwapItem( uint16 src, uint16 dst ) Item *bagItem = fullBag->GetItemByPos(i); if (!bagItem) continue; + fullBag->RemoveItem(i, true); emptyBag->StoreItem(count, bagItem, true); bagItem->SetState(ITEM_CHANGED, this); + ++count; } } } + // now do moves, remove... RemoveItem(dstbag, dstslot, false); RemoveItem(srcbag, srcslot, false); + // add to dest if (IsInventoryPos(dst)) StoreItem(sDest, pSrcItem, true); @@ -10189,6 +11973,7 @@ void Player::SwapItem( uint16 src, uint16 dst ) BankItem(sDest, pSrcItem, true); else if (IsEquipmentPos(dst)) EquipItem(eDest, pSrcItem, true); + // add to src if (IsInventoryPos(src)) StoreItem(sDest2, pDstItem, true); @@ -10196,8 +11981,10 @@ void Player::SwapItem( uint16 src, uint16 dst ) BankItem(sDest2, pDstItem, true); else if (IsEquipmentPos(src)) EquipItem(eDest2, pDstItem, true); + AutoUnequipOffhandIfNeed(); } + void Player::AddItemToBuyBackSlot( Item *pItem ) { if (pItem) @@ -10208,6 +11995,7 @@ void Player::AddItemToBuyBackSlot( Item *pItem ) { uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 ); uint32 oldest_slot = BUYBACK_SLOT_START; + for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i ) { // found empty @@ -10216,33 +12004,41 @@ void Player::AddItemToBuyBackSlot( Item *pItem ) slot = i; break; } + uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START); + if (oldest_time > i_time) { oldest_time = i_time; oldest_slot = i; } } + // find oldest slot = oldest_slot; } + RemoveItemFromBuyBackSlot( slot, true ); sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot); + m_items[slot] = pItem; time_t base = time(NULL); uint32 etime = uint32(base - m_logintime + (30 * 3600)); uint32 eslot = slot - BUYBACK_SLOT_START; + SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() ); if (ItemPrototype const *pProto = pItem->GetProto()) SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() ); else SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 ); SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime ); + // move to next (for non filled list is move most optimized choice) if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1) ++m_currentBuybackSlot; } } + Item* Player::GetItemFromBuyBackSlot( uint32 slot ) { sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot); @@ -10250,6 +12046,7 @@ Item* Player::GetItemFromBuyBackSlot( uint32 slot ) return m_items[slot]; return NULL; } + void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del ) { sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot); @@ -10261,37 +12058,46 @@ void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del ) pItem->RemoveFromWorld(); if(del) pItem->SetState(ITEM_REMOVED, this); } + m_items[slot] = NULL; + uint32 eslot = slot - BUYBACK_SLOT_START; SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 ); SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 ); SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 ); + // if current backslot is filled set to now free slot if(m_items[m_currentBuybackSlot]) m_currentBuybackSlot = slot; } } + void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 ) { sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg); WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18)); data << uint8(msg); + if (msg != EQUIP_ERR_OK) { data << uint64(pItem ? pItem->GetGUID() : 0); data << uint64(pItem2 ? pItem2->GetGUID() : 0); data << uint8(0); // not 0 there... + if (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I) { uint32 level = 0; + if (pItem) if (ItemPrototype const* proto = pItem->GetProto()) level = proto->RequiredLevel; + data << uint32(level); // new 2.4.0 } } GetSession()->SendPacket(&data); } + void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param ) { sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" ); @@ -10303,6 +12109,7 @@ void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 p data << uint8(msg); GetSession()->SendPacket(&data); } + void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param ) { sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" ); @@ -10314,6 +12121,7 @@ void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 data << uint8(msg); GetSession()->SendPacket(&data); } + void Player::ClearTrade() { tradeGold = 0; @@ -10321,6 +12129,7 @@ void Player::ClearTrade() for(uint8 i = 0; i < TRADE_SLOT_COUNT; i++) tradeItems[i] = NULL_SLOT; } + void Player::TradeCancel(bool sendback) { if (pTrader) @@ -10333,6 +12142,7 @@ void Player::TradeCancel(bool sendback) ws = pTrader->GetSession(); if (!ws->PlayerLogout()) ws->SendCancelTrade(); + // cleanup ClearTrade(); pTrader->ClearTrade(); @@ -10341,19 +12151,24 @@ void Player::TradeCancel(bool sendback) pTrader = NULL; } } + void Player::UpdateItemDuration(uint32 time, bool realtimeonly) { if (m_itemDuration.empty()) return; + sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly); + for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ) { Item* item = *itr; ++itr; // current element can be erased in UpdateDuration + if ((realtimeonly && item->GetProto()->Duration < 0) || !realtimeonly) item->UpdateDuration(this,time); } } + void Player::UpdateEnchantTime(uint32 time) { for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next) @@ -10377,17 +12192,20 @@ void Player::UpdateEnchantTime(uint32 time) } } } + void Player::AddEnchantmentDurations(Item *item) { for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x) { if (!item->GetEnchantmentId(EnchantmentSlot(x))) continue; + uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x)); if (duration > 0) AddEnchantmentDuration(item, EnchantmentSlot(x), duration); } } + void Player::RemoveEnchantmentDurations(Item *item) { for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();) @@ -10402,6 +12220,7 @@ void Player::RemoveEnchantmentDurations(Item *item) ++itr; } } + void Player::RemoveArenaEnchantments(EnchantmentSlot slot) { // remove enchantments from equipped items first to clean up the m_enchantDuration list @@ -10429,6 +12248,7 @@ void Player::RemoveArenaEnchantments(EnchantmentSlot slot) else ++next; } + // remove enchants from inventory items // NOTE: no need to remove these from stats, since these aren't equipped // in inventory @@ -10436,6 +12256,7 @@ void Player::RemoveArenaEnchantments(EnchantmentSlot slot) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetEnchantmentId(slot)) pItem->ClearEnchantment(slot); + // in inventory bags for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i )) @@ -10444,13 +12265,16 @@ void Player::RemoveArenaEnchantments(EnchantmentSlot slot) if (pItem->GetEnchantmentId(slot)) pItem->ClearEnchantment(slot); } + // duration == 0 will remove item enchant void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration) { if (!item) return; + if (slot >= MAX_ENCHANTMENT_SLOT) return; + for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr) { if (itr->item == item && itr->slot == slot) @@ -10466,27 +12290,35 @@ void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 durat m_enchantDuration.push_back(EnchantDuration(item, slot, duration)); } } + void Player::ApplyEnchantment(Item *item,bool apply) { for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot) ApplyEnchantment(item, EnchantmentSlot(slot), apply); } + void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition) { if (!item) return; + if (!item->IsEquipped()) return; + if (slot >= MAX_ENCHANTMENT_SLOT) return; + uint32 enchant_id = item->GetEnchantmentId(slot); if (!enchant_id) return; + SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) return; + if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1)) return; + if (!item->IsBroken()) { for (int s = 0; s < 3; ++s) @@ -10494,6 +12326,7 @@ void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool uint32 enchant_display_type = pEnchant->type[s]; uint32 enchant_amount = pEnchant->amount[s]; uint32 enchant_spell_id = pEnchant->spellid[s]; + switch(enchant_display_type) { case ITEM_ENCHANTMENT_TYPE_NONE: @@ -10558,6 +12391,7 @@ void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool } } } + HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply); break; case ITEM_ENCHANTMENT_TYPE_STAT: @@ -10577,6 +12411,7 @@ void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool } } } + sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id); switch (enchant_spell_id) { @@ -10783,12 +12618,15 @@ void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool } /*switch(enchant_display_type)*/ } /*for*/ } + // visualize enchantment at player and equipped items if(slot == PERM_ENCHANTMENT_SLOT) SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0); + if(slot == TEMP_ENCHANTMENT_SLOT) SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0); + if(apply_dur) { if(apply) @@ -10805,6 +12643,7 @@ void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool } } } + void Player::SendEnchantmentDurations() { for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr) @@ -10812,6 +12651,7 @@ void Player::SendEnchantmentDurations() GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000); } } + void Player::SendItemDurations() { for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr) @@ -10819,10 +12659,12 @@ void Player::SendItemDurations() (*itr)->SendTimeUpdate(this); } } + void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast) { if(!item) // prevent crash return; + // last check 2.0.10 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) ); data << uint64(GetGUID()); // player GUID @@ -10837,19 +12679,23 @@ void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, data << uint32(item->GetItemRandomPropertyId()); // random item property id data << uint32(count); // count of items data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory + if (broadcast && GetGroup()) GetGroup()->BroadcastPacket(&data, true); else GetSession()->SendPacket(&data); } + /*********************************************************/ /*** QUEST SYSTEM ***/ /*********************************************************/ + void Player::PrepareQuestMenu( uint64 guid ) { Object *pObject; QuestRelations* pObjectQR; QuestRelations* pObjectQIR; + // pets also can have quests Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid); if( pCreature ) @@ -10874,8 +12720,10 @@ void Player::PrepareQuestMenu( uint64 guid ) else return; } + QuestMenu &qm = PlayerTalkClass->GetQuestMenu(); qm.ClearMenu(); + for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i) { uint32 quest_id = i->second; @@ -10887,31 +12735,39 @@ void Player::PrepareQuestMenu( uint64 guid ) //else if (status == QUEST_STATUS_AVAILABLE ) // qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT); } + for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i) { uint32 quest_id = i->second; Quest const* pQuest = objmgr.GetQuestTemplate(quest_id); if(!pQuest) continue; + QuestStatus status = GetQuestStatus( quest_id ); + if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false)) qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2); else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) ) qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT); } } + void Player::SendPreparedQuest(uint64 guid) { QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu(); if (questMenu.Empty()) return; + QuestMenuItem const& qmi0 = questMenu.GetItem(0); + uint32 status = qmi0.m_qIcon; + // single element case if (questMenu.MenuItemCount() == 1) { // Auto open -- maybe also should verify there is no greeting uint32 quest_id = qmi0.m_qId; Quest const* pQuest = objmgr.GetQuestTemplate(quest_id); + if (pQuest) { if (status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus(quest_id)) @@ -10933,6 +12789,7 @@ void Player::SendPreparedQuest(uint64 guid) qe._Delay = 0; qe._Emote = 0; std::string title = ""; + // need pet case for some quests Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid); if (pCreature) @@ -10948,9 +12805,11 @@ void Player::SendPreparedQuest(uint64 guid) else { qe = gossiptext->Options[0].Emotes[0]; + if(!gossiptext->Options[0].Text_0.empty()) { title = gossiptext->Options[0].Text_0; + int loc_idx = GetSession()->GetSessionDbLocaleIndex(); if (loc_idx >= 0) { @@ -10965,6 +12824,7 @@ void Player::SendPreparedQuest(uint64 guid) else { title = gossiptext->Options[0].Text_1; + int loc_idx = GetSession()->GetSessionDbLocaleIndex(); if (loc_idx >= 0) { @@ -10981,16 +12841,20 @@ void Player::SendPreparedQuest(uint64 guid) PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid); } } + bool Player::IsActiveQuest( uint32 quest_id ) const { QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id); + return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE; } + Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest ) { Object *pObject; QuestRelations* pObjectQR; QuestRelations* pObjectQIR; + Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid); if( pCreature ) { @@ -11014,14 +12878,17 @@ Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest ) else return NULL; } + uint32 nextQuestID = pQuest->GetNextQuestInChain(); for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr) { if (itr->second == nextQuestID) return objmgr.GetQuestTemplate(nextQuestID); } + return NULL; } + bool Player::CanSeeStartQuest( Quest const *pQuest ) { if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) && @@ -11031,8 +12898,10 @@ bool Player::CanSeeStartQuest( Quest const *pQuest ) { return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel(); } + return false; } + bool Player::CanTakeQuest( Quest const *pQuest, bool msg ) { return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg ) @@ -11042,16 +12911,19 @@ bool Player::CanTakeQuest( Quest const *pQuest, bool msg ) && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg ) && SatisfyQuestDay( pQuest, msg ); } + bool Player::CanAddQuest( Quest const *pQuest, bool msg ) { if( !SatisfyQuestLog( msg ) ) return false; + uint32 srcitem = pQuest->GetSrcItemId(); if( srcitem > 0 ) { uint32 count = pQuest->GetSrcItemCount(); ItemPosCountVec dest; uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count ); + // player already have max number (in most case 1) source item, no additional item needed and quest can be added. if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS ) return true; @@ -11063,6 +12935,7 @@ bool Player::CanAddQuest( Quest const *pQuest, bool msg ) } return true; } + bool Player::CanCompleteQuest( uint32 quest_id ) { if( quest_id ) @@ -11070,14 +12943,19 @@ bool Player::CanCompleteQuest( uint32 quest_id ) QuestStatusData& q_status = mQuestStatus[quest_id]; if( q_status.m_status == QUEST_STATUS_COMPLETE ) return false; // not allow re-complete quest + Quest const* qInfo = objmgr.GetQuestTemplate(quest_id); + if(!qInfo) return false; + // auto complete quest if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false)) return true; + if ( q_status.m_status == QUEST_STATUS_INCOMPLETE ) { + if ( qInfo->HasFlag( QUEST_TRINITY_FLAGS_DELIVER ) ) { for(uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; i++) @@ -11086,33 +12964,41 @@ bool Player::CanCompleteQuest( uint32 quest_id ) return false; } } + if ( qInfo->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO) ) { for(uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; i++) { if( qInfo->ReqCreatureOrGOId[i] == 0 ) continue; + if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] ) return false; } } + if ( qInfo->HasFlag( QUEST_TRINITY_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored ) return false; + if ( qInfo->HasFlag( QUEST_TRINITY_FLAGS_TIMED ) && q_status.m_timer == 0 ) return false; + if ( qInfo->GetRewOrReqMoney() < 0 ) { if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) ) return false; } + uint32 repFacId = qInfo->GetRepObjectiveFaction(); if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() ) return false; + return true; } } return false; } + bool Player::CanCompleteRepeatableQuest( Quest const *pQuest ) { // Solve problem that player don't have the quest and try complete it. @@ -11120,25 +13006,32 @@ bool Player::CanCompleteRepeatableQuest( Quest const *pQuest ) // Seem that all repeatable quest are DELIVER Flag so, no need to add more. if( !CanTakeQuest(pQuest, false) ) return false; + if (pQuest->HasFlag( QUEST_TRINITY_FLAGS_DELIVER) ) for(uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; i++) if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) ) return false; + if( !CanRewardQuest(pQuest, false) ) return false; + return true; } + bool Player::CanRewardQuest( Quest const *pQuest, bool msg ) { // not auto complete quest and not completed quest (only cheating case, then ignore without message) if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE) return false; + // daily quest can't be rewarded (25 daily quest already completed) if(!SatisfyQuestDay(pQuest,true)) return false; + // rewarded and not repeatable quest (only cheating case, then ignore without message) if(GetQuestRewardStatus(pQuest->GetQuestId())) return false; + // prevent receive reward with quest items in bank if ( pQuest->HasFlag( QUEST_TRINITY_FLAGS_DELIVER ) ) { @@ -11153,16 +13046,20 @@ bool Player::CanRewardQuest( Quest const *pQuest, bool msg ) } } } + // prevent receive reward with low money and GetRewOrReqMoney() < 0 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) ) return false; + return true; } + bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg ) { // prevent receive reward with quest items in bank or for not completed quest if(!CanRewardQuest(pQuest,msg)) return false; + if ( pQuest->GetRewChoiceItemsCount() > 0 ) { if( pQuest->RewChoiceItemId[reward] ) @@ -11176,6 +13073,7 @@ bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg ) } } } + if ( pQuest->GetRewItemsCount() > 0 ) { for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i) @@ -11192,73 +13090,94 @@ bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg ) } } } + return true; } + void Player::AddQuest( Quest const *pQuest, Object *questGiver ) { uint16 log_slot = FindQuestSlot( 0 ); assert(log_slot < MAX_QUEST_LOG_SIZE); + uint32 quest_id = pQuest->GetQuestId(); + // if not exist then created with set uState==NEW and rewarded=false QuestStatusData& questStatusData = mQuestStatus[quest_id]; + // check for repeatable quests status reset questStatusData.m_status = QUEST_STATUS_INCOMPLETE; questStatusData.m_explored = false; + if ( pQuest->HasFlag( QUEST_TRINITY_FLAGS_DELIVER ) ) { for(uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i) questStatusData.m_itemcount[i] = 0; } + if ( pQuest->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO) ) { for(uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i) questStatusData.m_creatureOrGOcount[i] = 0; } + GiveQuestSourceItem( pQuest ); AdjustQuestReqItemCount( pQuest, questStatusData ); + if( pQuest->GetRepObjectiveFaction() ) if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction())) GetReputationMgr().SetVisible(factionEntry); + uint32 qtime = 0; if( pQuest->HasFlag( QUEST_TRINITY_FLAGS_TIMED ) ) { uint32 limittime = pQuest->GetLimitTime(); + // shared timed quest if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER) limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS; + AddTimedQuest( quest_id ); questStatusData.m_timer = limittime * IN_MILISECONDS; qtime = static_cast<uint32>(time(NULL)) + limittime; } else questStatusData.m_timer = 0; + SetQuestSlot(log_slot, quest_id, qtime); + if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED; + //starting initial quest script if(questGiver && pQuest->GetQuestStartScript()!=0) GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this); + // Some spells applied at quest activation SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true); if(saBounds.first != saBounds.second) { uint32 zone, area; GetZoneAndAreaId(zone,area); + for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area)) if( !HasAura(itr->second->spellId) ) CastSpell(this,itr->second->spellId,true); } + UpdateForQuestWorldObjects(); } + void Player::CompleteQuest( uint32 quest_id ) { if( quest_id ) { SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE ); + uint16 log_slot = FindQuestSlot( quest_id ); if( log_slot < MAX_QUEST_LOG_SIZE) SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE); + if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id)) { if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) ) @@ -11268,28 +13187,35 @@ void Player::CompleteQuest( uint32 quest_id ) } } } + void Player::IncompleteQuest( uint32 quest_id ) { if( quest_id ) { SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE ); + uint16 log_slot = FindQuestSlot( quest_id ); if( log_slot < MAX_QUEST_LOG_SIZE) RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE); } } + void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce ) { //this THING should be here to protect code from quest, which cast on player far teleport as a reward //should work fine, cause far teleport will be executed in Player::Update() SetCanDelayTeleport(true); + uint32 quest_id = pQuest->GetQuestId(); + for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; i++ ) { if (pQuest->ReqItemId[i]) DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true); } + TakeQuestSourceItem(quest_id, true); // take quest src item from player on completing quest + for(uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i) { if (pQuest->ReqSourceId[i]) @@ -11298,7 +13224,9 @@ void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver DestroyItemCount(pQuest->ReqSourceId[i], count ? count : 9999, true); } } + RemoveTimedQuest(quest_id); + if (pQuest->GetRewChoiceItemsCount() > 0) { if (uint32 itemId = pQuest->RewChoiceItemId[reward]) @@ -11311,6 +13239,7 @@ void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver } } } + if (pQuest->GetRewItemsCount() > 0) { for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i) @@ -11326,17 +13255,23 @@ void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver } } } + RewardReputation( pQuest ); + uint16 log_slot = FindQuestSlot( quest_id ); if (log_slot < MAX_QUEST_LOG_SIZE) SetQuestSlot(log_slot,0); + QuestStatusData& q_status = mQuestStatus[quest_id]; + // Not give XP in case already completed once repeatable quest uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST)); + // handle SPELL_AURA_MOD_XP_QUEST_PCT auras Unit::AuraEffectList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_QUEST_PCT); for(Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i) XP = uint32(XP*(1.0f + (*i)->GetAmount() / 100.0f)); + if (getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)) GiveXP( XP , NULL ); else @@ -11345,27 +13280,33 @@ void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver ModifyMoney( money ); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money); } + // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative if (pQuest->GetRewOrReqMoney()) { ModifyMoney( pQuest->GetRewOrReqMoney() ); + if (pQuest->GetRewOrReqMoney() > 0) GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney()); } + // honor reward if (pQuest->GetRewHonorableKills()) RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills())); + // title reward if (pQuest->GetCharTitleId()) { if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId())) SetTitle(titleEntry); } + if (pQuest->GetBonusTalents()) { m_questRewardTalentCount+=pQuest->GetBonusTalents(); InitTalentForLevel(); } + // Send reward mail if (pQuest->GetRewMailTemplateId()) { @@ -11394,10 +13335,14 @@ void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver senderGuidOrEntry = GetGUIDLow(); break; } + Loot questMailLoot; + questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true); + // fill mail MailItemsInfo mi; // item list preparing + uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this); for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i) { @@ -11410,87 +13355,110 @@ void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver } } } + WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId()); } + if (pQuest->IsDaily()) { SetDailyQuestStatus(quest_id); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1); } + if (!pQuest->IsRepeatable()) SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE); else SetQuestStatus(quest_id, QUEST_STATUS_NONE); + q_status.m_rewarded = true; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; + if (announce) SendQuestReward( pQuest, XP, questGiver ); + // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data) if (pQuest->GetRewSpellCast() > 0) CastSpell( this, pQuest->GetRewSpellCast(), true); else if ( pQuest->GetRewSpell() > 0) CastSpell( this, pQuest->GetRewSpell(), true); + if (pQuest->GetZoneOrSort() > 0) GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort()); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId()); + uint32 zone = 0; uint32 area = 0; + // remove auras from spells with quest reward state limitations SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id); if(saEndBounds.first != saEndBounds.second) { GetZoneAndAreaId(zone,area); + for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr) if(!itr->second->IsFitToRequirements(this,zone,area)) RemoveAurasDueToSpell(itr->second->spellId); } + // Some spells applied at quest reward SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false); if(saBounds.first != saBounds.second) { if(!zone || !area) GetZoneAndAreaId(zone,area); + for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area)) if( !HasAura(itr->second->spellId) ) CastSpell(this,itr->second->spellId,true); } + //lets remove flag for delayed teleports SetCanDelayTeleport(false); } + void Player::FailQuest(uint32 questId) { if (Quest const* pQuest = objmgr.GetQuestTemplate(questId)) { SetQuestStatus(questId, QUEST_STATUS_FAILED); + uint16 log_slot = FindQuestSlot(questId); + if (log_slot < MAX_QUEST_LOG_SIZE) { SetQuestSlotTimer(log_slot, 1); SetQuestSlotState(log_slot, QUEST_STATE_FAIL); } + if (pQuest->HasFlag(QUEST_TRINITY_FLAGS_TIMED)) { QuestStatusData& q_status = mQuestStatus[questId]; + RemoveTimedQuest(questId); q_status.m_timer = 0; + SendQuestTimerFailed(questId); } else SendQuestFailed(questId); } } + bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg ) { int32 zoneOrSort = qInfo->GetZoneOrSort(); int32 skillOrClass = qInfo->GetSkillOrClass(); + // skip zone zoneOrSort and 0 case skillOrClass if( zoneOrSort >= 0 && skillOrClass == 0 ) return true; + int32 questSort = -zoneOrSort; uint8 reqSortClass = ClassByQuestSort(questSort); + // check class sort cases in zoneOrSort if( reqSortClass != 0 && getClass() != reqSortClass) { @@ -11498,6 +13466,7 @@ bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg ) SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ ); return false; } + // check class if( skillOrClass < 0 ) { @@ -11520,8 +13489,10 @@ bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg ) return false; } } + return true; } + bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg ) { if( getLevel() < qInfo->GetMinLevel() ) @@ -11532,11 +13503,13 @@ bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg ) } return true; } + bool Player::SatisfyQuestLog( bool msg ) { // exist free slot if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE ) return true; + if( msg ) { WorldPacket data( SMSG_QUESTLOG_FULL, 0 ); @@ -11545,16 +13518,20 @@ bool Player::SatisfyQuestLog( bool msg ) } return false; } + bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg ) { // No previous quest (might be first quest in a series) if( qInfo->prevQuests.empty()) return true; + for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter ) { uint32 prevId = abs(*iter); + QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId ); Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId); + if( qPrevInfo && i_prevstatus != mQuestStatus.end() ) { // If any of the positive previous quests completed, return true @@ -11563,18 +13540,24 @@ bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg ) // skip one-from-all exclusive group if(qPrevInfo->GetExclusiveGroup() >= 0) return true; + // each-from-all exclusive group ( < 0) // can be start if only all quests in prev quest exclusive group completed and rewarded ObjectMgr::ExclusiveQuestGroups::iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup()); ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup()); + assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0 + for(; iter2 != end; ++iter2) { uint32 exclude_Id = iter2->second; + // skip checked quest id, only state of other quests in group is interesting if(exclude_Id == prevId) continue; + QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id ); + // alternative quest from group also must be completed and rewarded(reported) if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded ) { @@ -11592,18 +13575,24 @@ bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg ) // skip one-from-all exclusive group if(qPrevInfo->GetExclusiveGroup() >= 0) return true; + // each-from-all exclusive group ( < 0) // can be start if only all quests in prev quest exclusive group active ObjectMgr::ExclusiveQuestGroups::iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup()); ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup()); + assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0 + for(; iter2 != end; ++iter2) { uint32 exclude_Id = iter2->second; + // skip checked quest id, only state of other quests in group is interesting if(exclude_Id == prevId) continue; + QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id ); + // alternative quest from group also must be active if( i_exstatus == mQuestStatus.end() || i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE && @@ -11618,12 +13607,15 @@ bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg ) } } } + // Has only positive prev. quests in non-rewarded state // and negative prev. quests in non-active state if( msg ) SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ ); + return false; } + bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg ) { uint32 reqraces = qInfo->GetRequiredRaces(); @@ -11637,6 +13629,7 @@ bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg ) } return true; } + bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg ) { uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep @@ -11646,6 +13639,7 @@ bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg ) SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ ); return false; } + uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue()) { @@ -11653,8 +13647,10 @@ bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg ) SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ ); return false; } + return true; } + bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg ) { QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() ); @@ -11666,6 +13662,7 @@ bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg ) } return true; } + bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg) { if (m_timedquests.empty() && qInfo->HasFlag(QUEST_TRINITY_FLAGS_TIMED)) @@ -11676,20 +13673,26 @@ bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg) } return true; } + bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg ) { // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed if(qInfo->GetExclusiveGroup() <= 0) return true; + ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup()); ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup()); + assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0 + for(; iter != end; ++iter) { uint32 exclude_Id = iter->second; + // skip checked quest id, only state of other quests in group is interesting if(exclude_Id == qInfo->GetQuestId()) continue; + // not allow have daily quest if daily quest from exclusive group already recently completed Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id); if( !SatisfyQuestDay(Nquest, false) ) @@ -11698,7 +13701,9 @@ bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg ) SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ ); return false; } + QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id ); + // alternative quest already started or completed if( i_exstatus != mQuestStatus.end() && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) ) @@ -11710,10 +13715,12 @@ bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg ) } return true; } + bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg ) { if(!qInfo->GetNextQuestInChain()) return true; + // next quest in chain already started or completed QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() ); if( itr != mQuestStatus.end() @@ -11723,20 +13730,25 @@ bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg ) SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ ); return false; } + // check for all quests further up the chain // only necessary if there are quest chains with more than one quest that can be skipped //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg ); return true; } + bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg ) { // No previous quest in chain if( qInfo->prevChainQuests.empty()) return true; + for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter ) { uint32 prevId = *iter; + QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId ); + if( i_prevstatus != mQuestStatus.end() ) { // If any of the previous quests in chain active, return false @@ -11748,35 +13760,43 @@ bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg ) return false; } } + // check for all quests further down the chain // only necessary if there are quest chains with more than one quest that can be skipped //if( !SatisfyQuestPrevChain( prevId, msg ) ) // return false; } + // No previous quest in chain active return true; } + bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg ) { if(!qInfo->IsDaily()) return true; + bool have_slot = false; for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) { uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx); if(qInfo->GetQuestId()==id) return false; + if(!id) have_slot = true; } + if(!have_slot) { if( msg ) SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING ); return false; } + return true; } + bool Player::GiveQuestSourceItem( Quest const *pQuest ) { uint32 srcitem = pQuest->GetSrcItemId(); @@ -11785,6 +13805,7 @@ bool Player::GiveQuestSourceItem( Quest const *pQuest ) uint32 count = pQuest->GetSrcItemCount(); if( count <= 0 ) count = 1; + ItemPosCountVec dest; uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count ); if( msg == EQUIP_ERR_OK ) @@ -11800,8 +13821,10 @@ bool Player::GiveQuestSourceItem( Quest const *pQuest ) SendEquipError( msg, NULL, NULL ); return false; } + return true; } + bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg ) { Quest const* qInfo = objmgr.GetQuestTemplate(quest_id); @@ -11813,6 +13836,7 @@ bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg ) uint32 count = qInfo->GetSrcItemCount(); if( count <= 0 ) count = 1; + // exist one case when destroy source quest item not possible: // non un-equippable item (equipped non-empty bag, for example) uint8 res = CanUnequipItems(srcitem,count); @@ -11822,11 +13846,13 @@ bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg ) SendEquipError( res, NULL, NULL ); return false; } + DestroyItemCount(srcitem, count, true, true); } } return true; } + bool Player::GetQuestRewardStatus( uint32 quest_id ) const { Quest const* qInfo = objmgr.GetQuestTemplate(quest_id); @@ -11837,10 +13863,12 @@ bool Player::GetQuestRewardStatus( uint32 quest_id ) const if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE && !qInfo->IsRepeatable() ) return itr->second.m_rewarded; + return false; } return false; } + QuestStatus Player::GetQuestStatus( uint32 quest_id ) const { if( quest_id ) @@ -11851,6 +13879,7 @@ QuestStatus Player::GetQuestStatus( uint32 quest_id ) const } return QUEST_STATUS_NONE; } + bool Player::CanShareQuest(uint32 quest_id) const { Quest const* qInfo = objmgr.GetQuestTemplate(quest_id); @@ -11862,28 +13891,36 @@ bool Player::CanShareQuest(uint32 quest_id) const } return false; } + void Player::SetQuestStatus(uint32 quest_id, QuestStatus status) { if (Quest const* qInfo = objmgr.GetQuestTemplate(quest_id)) { QuestStatusData& q_status = mQuestStatus[quest_id]; + q_status.m_status = status; + if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; } + UpdateForQuestWorldObjects(); } + // not used in TrinIty, but used in scripting code uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry) { Quest const* qInfo = objmgr.GetQuestTemplate(quest_id); if( !qInfo ) return 0; + for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j) if ( qInfo->ReqCreatureOrGOId[j] == entry ) return mQuestStatus[quest_id].m_creatureOrGOcount[j]; + return 0; } + void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData ) { if ( pQuest->HasFlag( QUEST_TRINITY_FLAGS_DELIVER ) ) @@ -11894,19 +13931,23 @@ void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& ques if( reqitemcount != 0 ) { uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true); + questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount); if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED; } } } } + uint16 Player::FindQuestSlot( uint32 quest_id ) const { for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) if ( GetQuestSlotQuestId(i) == quest_id ) return i; + return MAX_QUEST_LOG_SIZE; } + void Player::AreaExploredOrEventHappens( uint32 questId ) { if( questId ) @@ -11915,6 +13956,7 @@ void Player::AreaExploredOrEventHappens( uint32 questId ) if( log_slot < MAX_QUEST_LOG_SIZE) { QuestStatusData& q_status = mQuestStatus[questId]; + if(!q_status.m_explored) { q_status.m_explored = true; @@ -11926,6 +13968,7 @@ void Player::AreaExploredOrEventHappens( uint32 questId ) CompleteQuest( questId ); } } + //not used in Trinityd, function for external script library void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject ) { @@ -11934,6 +13977,7 @@ void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player *pGroupGuy = itr->getSource(); + // for any leave or dead (with not released body) group member at appropriate distance if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() ) pGroupGuy->AreaExploredOrEventHappens(questId); @@ -11942,6 +13986,7 @@ void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject else AreaExploredOrEventHappens(questId); } + void Player::ItemAddedQuestCheck( uint32 entry, uint32 count ) { for( uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) @@ -11949,12 +13994,16 @@ void Player::ItemAddedQuestCheck( uint32 entry, uint32 count ) uint32 questid = GetQuestSlotQuestId(i); if ( questid == 0 ) continue; + QuestStatusData& q_status = mQuestStatus[questid]; + if ( q_status.m_status != QUEST_STATUS_INCOMPLETE ) continue; + Quest const* qInfo = objmgr.GetQuestTemplate(questid); if( !qInfo || !qInfo->HasFlag( QUEST_TRINITY_FLAGS_DELIVER ) ) continue; + for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++) { uint32 reqitem = qInfo->ReqItemId[j]; @@ -11967,6 +14016,7 @@ void Player::ItemAddedQuestCheck( uint32 entry, uint32 count ) uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount); q_status.m_itemcount[j] += additemcount; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; + SendQuestUpdateAddItem( qInfo, j, additemcount ); } if ( CanCompleteQuest( questid ) ) @@ -11977,6 +14027,7 @@ void Player::ItemAddedQuestCheck( uint32 entry, uint32 count ) } UpdateForQuestWorldObjects(); } + void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count ) { for( uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) @@ -11989,12 +14040,14 @@ void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count ) continue; if( !qInfo->HasFlag( QUEST_TRINITY_FLAGS_DELIVER ) ) continue; + for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++) { uint32 reqitem = qInfo->ReqItemId[j]; if ( reqitem == entry ) { QuestStatusData& q_status = mQuestStatus[questid]; + uint32 reqitemcount = qInfo->ReqItemCount[j]; uint32 curitemcount; if( q_status.m_status != QUEST_STATUS_COMPLETE ) @@ -12006,6 +14059,7 @@ void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count ) uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount); q_status.m_itemcount[j] = curitemcount - remitemcount; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; + IncompleteQuest( questid ); } return; @@ -12014,14 +14068,17 @@ void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count ) } UpdateForQuestWorldObjects(); } + void Player::KilledMonster( CreatureInfo const* cInfo, uint64 guid ) { if(cInfo->Entry) KilledMonsterCredit(cInfo->Entry,guid); + for(int i = 0; i < MAX_KILL_CREDIT; ++i) if(cInfo->KillCredit[i]) KilledMonsterCredit(cInfo->KillCredit[i],guid); } + void Player::KilledMonsterCredit( uint32 entry, uint64 guid ) { uint32 addkillcount = 1; @@ -12031,6 +14088,7 @@ void Player::KilledMonsterCredit( uint32 entry, uint64 guid ) uint32 questid = GetQuestSlotQuestId(i); if(!questid) continue; + Quest const* qInfo = objmgr.GetQuestTemplate(questid); if( !qInfo ) continue; @@ -12045,10 +14103,13 @@ void Player::KilledMonsterCredit( uint32 entry, uint64 guid ) // skip GO activate objective or none if(qInfo->ReqCreatureOrGOId[j] <=0) continue; + // skip Cast at creature objective if(qInfo->ReqSpell[j] !=0 ) continue; + uint32 reqkill = qInfo->ReqCreatureOrGOId[j]; + if ( reqkill == entry ) { uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j]; @@ -12057,10 +14118,12 @@ void Player::KilledMonsterCredit( uint32 entry, uint64 guid ) { q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; + SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount); } if ( CanCompleteQuest( questid ) ) CompleteQuest( questid ); + // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization). continue; } @@ -12069,19 +14132,24 @@ void Player::KilledMonsterCredit( uint32 entry, uint64 guid ) } } } + void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id ) { bool isCreature = IS_CRE_OR_VEH_GUID(guid); + uint32 addCastCount = 1; for( uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i) { uint32 questid = GetQuestSlotQuestId(i); if(!questid) continue; + Quest const* qInfo = objmgr.GetQuestTemplate(questid); if ( !qInfo ) continue; + QuestStatusData& q_status = mQuestStatus[questid]; + if ( q_status.m_status == QUEST_STATUS_INCOMPLETE ) { if( qInfo->HasFlag( QUEST_TRINITY_FLAGS_KILL_OR_CAST ) ) @@ -12091,7 +14159,9 @@ void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id ) // skip kill creature objective (0) or wrong spell casts if(qInfo->ReqSpell[j] != spell_id ) continue; + uint32 reqTarget = 0; + if(isCreature) { // creature activate objectives @@ -12106,19 +14176,24 @@ void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id ) // checked at quest_template loading reqTarget = - qInfo->ReqCreatureOrGOId[j]; } + // other not this creature/GO related objectives if( reqTarget != entry ) continue; + uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j]; uint32 curCastCount = q_status.m_creatureOrGOcount[j]; if ( curCastCount < reqCastCount ) { q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; + SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount); } + if ( CanCompleteQuest( questid ) ) CompleteQuest( questid ); + // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization). break; } @@ -12126,6 +14201,7 @@ void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id ) } } } + void Player::TalkedToCreature( uint32 entry, uint64 guid ) { uint32 addTalkCount = 1; @@ -12134,10 +14210,13 @@ void Player::TalkedToCreature( uint32 entry, uint64 guid ) uint32 questid = GetQuestSlotQuestId(i); if(!questid) continue; + Quest const* qInfo = objmgr.GetQuestTemplate(questid); if ( !qInfo ) continue; + QuestStatusData& q_status = mQuestStatus[questid]; + if ( q_status.m_status == QUEST_STATUS_INCOMPLETE ) { if( qInfo->HasFlag( QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO ) ) @@ -12147,12 +14226,15 @@ void Player::TalkedToCreature( uint32 entry, uint64 guid ) // skip spell casts and Gameobject objectives if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0) continue; + uint32 reqTarget = 0; + if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives // checked at quest_template loading reqTarget = qInfo->ReqCreatureOrGOId[j]; else continue; + if ( reqTarget == entry ) { uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j]; @@ -12161,10 +14243,12 @@ void Player::TalkedToCreature( uint32 entry, uint64 guid ) { q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; + SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount); } if ( CanCompleteQuest( questid ) ) CompleteQuest( questid ); + // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization). continue; } @@ -12173,6 +14257,7 @@ void Player::TalkedToCreature( uint32 entry, uint64 guid ) } } } + void Player::MoneyChanged( uint32 count ) { for( uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) @@ -12180,10 +14265,12 @@ void Player::MoneyChanged( uint32 count ) uint32 questid = GetQuestSlotQuestId(i); if (!questid) continue; + Quest const* qInfo = objmgr.GetQuestTemplate(questid); if( qInfo && qInfo->GetRewOrReqMoney() < 0 ) { QuestStatusData& q_status = mQuestStatus[questid]; + if( q_status.m_status == QUEST_STATUS_INCOMPLETE ) { if(int32(count) >= -qInfo->GetRewOrReqMoney()) @@ -12200,6 +14287,7 @@ void Player::MoneyChanged( uint32 count ) } } } + void Player::ReputationChanged(FactionEntry const* factionEntry ) { for( uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) @@ -12227,6 +14315,7 @@ void Player::ReputationChanged(FactionEntry const* factionEntry ) } } } + bool Player::HasQuestForItem( uint32 itemid ) const { for( uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) @@ -12234,19 +14323,24 @@ bool Player::HasQuestForItem( uint32 itemid ) const uint32 questid = GetQuestSlotQuestId(i); if ( questid == 0 ) continue; + QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid); if(qs_itr == mQuestStatus.end()) continue; + QuestStatusData const& q_status = qs_itr->second; + if (q_status.m_status == QUEST_STATUS_INCOMPLETE) { Quest const* qinfo = objmgr.GetQuestTemplate(questid); if(!qinfo) continue; + // hide quest if player is in raid-group and quest is no raid quest if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID) if(!InBattleGround()) //there are two ways.. we can make every bg-quest a raidquest, or add this code here.. i don't know if this can be exploited by other quests, but i think all other quests depend on a specific area.. but keep this in mind, if something strange happens later continue; + // There should be no mixed ReqItem/ReqSource drop // This part for ReqItem drop for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++) @@ -12261,9 +14355,11 @@ bool Player::HasQuestForItem( uint32 itemid ) const if (qinfo->ReqSourceId[j] == itemid) { ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid); + // 'unique' item if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount) return true; + // allows custom amount drop when not 0 if (qinfo->ReqSourceCount[j]) { @@ -12277,6 +14373,7 @@ bool Player::HasQuestForItem( uint32 itemid ) const } return false; } + void Player::SendQuestComplete( uint32 quest_id ) { if( quest_id ) @@ -12287,6 +14384,7 @@ void Player::SendQuestComplete( uint32 quest_id ) sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id ); } } + void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver ) { uint32 questid = pQuest->GetQuestId(); @@ -12294,6 +14392,7 @@ void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGive gameeventmgr.HandleQuestComplete(questid); WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) ); data << uint32(questid); + if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) ) { data << uint32(XP); @@ -12304,12 +14403,15 @@ void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGive data << uint32(0); data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY))); } + data << uint32(10*Trinity::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills())); data << uint32(pQuest->GetBonusTalents()); // bonus talents GetSession()->SendPacket( &data ); + if (pQuest->GetQuestCompleteScript() != 0) GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this); } + void Player::SendQuestFailed( uint32 quest_id ) { if( quest_id ) @@ -12321,6 +14423,7 @@ void Player::SendQuestFailed( uint32 quest_id ) sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED"); } } + void Player::SendQuestTimerFailed( uint32 quest_id ) { if( quest_id ) @@ -12331,6 +14434,7 @@ void Player::SendQuestTimerFailed( uint32 quest_id ) sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER"); } } + void Player::SendCanTakeQuestResponse( uint32 msg ) { WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 ); @@ -12338,6 +14442,7 @@ void Player::SendCanTakeQuestResponse( uint32 msg ) GetSession()->SendPacket( &data ); sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID"); } + void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg ) { if( pPlayer ) @@ -12349,6 +14454,7 @@ void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg ) sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT"); } } + void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count ) { WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 ); @@ -12357,13 +14463,16 @@ void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint3 //data << count; GetSession()->SendPacket( &data ); } + void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count ) { assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)"); + int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ]; if (entry < 0) // client expected gameobject template id in form (id|0x80000000) entry = (-entry) | 0x80000000; + WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) ); sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" ); data << uint32(pQuest->GetQuestId()); @@ -12372,13 +14481,16 @@ void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, u data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]); data << uint64(guid); GetSession()->SendPacket(&data); + uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() ); if( log_slot < MAX_QUEST_LOG_SIZE) SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count); } + /*********************************************************/ /*** LOAD SYSTEM ***/ /*********************************************************/ + bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid ) { bool delete_result = true; @@ -12391,7 +14503,9 @@ bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid ) } else delete_result = false; + Field *fields = result->Fetch(); + if (!LoadValues( fields[1].GetString())) { sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid)); @@ -12399,55 +14513,76 @@ bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid ) delete result; return false; } + // overwrite possible wrong/corrupted guid SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)); + m_name = fields[2].GetCppString(); + Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat()); Map *map = MapManager::Instance().CreateMap(fields[6].GetUInt32(), this, 0); SetMap(map); + // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE] // this must help in case next save after mass player load after server startup m_nextSave = urand(m_nextSave/2,m_nextSave*3/2); + // the instance id is not needed at character enum + m_Played_time[PLAYED_TIME_TOTAL] = fields[7].GetUInt32(); m_Played_time[PLAYED_TIME_LEVEL] = fields[8].GetUInt32(); + m_atLoginFlags = fields[9].GetUInt32(); + // I don't see these used anywhere .. /*_LoadGroup(); + _LoadBoundInstances();*/ + if (delete_result) delete result; + for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++) m_items[i] = NULL; + if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) m_deathState = DEAD; + return true; } + void Player::_LoadDeclinedNames(QueryResult* result) { if(!result) return; + if(m_declinedname) delete m_declinedname; + m_declinedname = new DeclinedName; Field *fields = result->Fetch(); for(uint8 i = 0; i < MAX_DECLINED_NAME_CASES; ++i) m_declinedname->name[i] = fields[i].GetCppString(); + delete result; } + void Player::_LoadArenaTeamInfo(QueryResult *result) { // arenateamid, played_week, played_season, personal_rating memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18); if (!result) return; + do { Field *fields = result->Fetch(); + uint32 arenateamid = fields[0].GetUInt32(); uint32 played_week = fields[1].GetUInt32(); uint32 played_season = fields[2].GetUInt32(); uint32 personal_rating = fields[3].GetUInt32(); + ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid); if(!aTeam) { @@ -12455,43 +14590,55 @@ void Player::_LoadArenaTeamInfo(QueryResult *result) continue; } uint8 arenaSlot = aTeam->GetSlot(); + m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating + }while (result->NextRow()); delete result; } + void Player::_LoadEquipmentSets(QueryResult *result) { // SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid)); if (!result) return; + uint32 count = 0; do { Field *fields = result->Fetch(); + EquipmentSet eqSet; + eqSet.Guid = fields[0].GetUInt64(); uint32 index = fields[1].GetUInt32(); eqSet.Name = fields[2].GetCppString(); eqSet.IconName = fields[3].GetCppString(); eqSet.state = EQUIPMENT_SET_UNCHANGED; + for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i) eqSet.Items[i] = fields[4+i].GetUInt32(); + m_EquipmentSets[index] = eqSet; + ++count; + if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit break; } while (result->NextRow()); delete result; } + void Player::_LoadBGData(QueryResult* result) { if (!result) return; + // Expecting only one row Field *fields = result->Fetch(); /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */ @@ -12505,46 +14652,61 @@ void Player::_LoadBGData(QueryResult* result) m_bgData.taxiPath[0] = fields[7].GetUInt32(); m_bgData.taxiPath[1] = fields[8].GetUInt32(); m_bgData.mountSpell = fields[9].GetUInt32(); + delete result; } + bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid) { QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid)); if(!result) return false; + Field *fields = result->Fetch(); + x = fields[0].GetFloat(); y = fields[1].GetFloat(); z = fields[2].GetFloat(); o = fields[3].GetFloat(); mapid = fields[4].GetUInt32(); in_flight = !fields[5].GetCppString().empty(); + delete result; return true; } + bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid) { QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid)); if( !result ) return false; + Field *fields = result->Fetch(); + data = StrSplit(fields[0].GetCppString(), " "); + delete result; + return true; } + uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index) { if(index >= data.size()) return 0; + return (uint32)atoi(data[index].c_str()); } + float Player::GetFloatValueFromArray(Tokens const& data, uint16 index) { float result; uint32 temp = Player::GetUInt32ValueFromArray(data,index); memcpy(&result, &temp, sizeof(result)); + return result; } + uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid) { // todo: cleanup in this, move to a separate function. @@ -12581,27 +14743,35 @@ uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid) Tokens data; if(!LoadValuesArrayFromDB(data,guid)) return 0; + return GetUInt32ValueFromArray(data,index); } + float Player::GetFloatValueFromDB(uint16 index, uint64 guid) { float result; uint32 temp = Player::GetUInt32ValueFromDB(index, guid); memcpy(&result, &temp, sizeof(result)); + return result; } + bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) { //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points, instance_id, speccount, activespec FROM characters WHERE guid = '%u'", guid); QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM); + if(!result) { sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid); return false; } + Field *fields = result->Fetch(); + uint32 dbAccountId = fields[1].GetUInt32(); + // check if the character's account in the db and the logged in account match. // player should be able to load/delete character only with correct account! if( dbAccountId != GetSession()->GetAccountId() ) @@ -12610,8 +14780,11 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) delete result; return false; } + Object::_Create( guid, 0, HIGHGUID_PLAYER ); + m_name = fields[3].GetCppString(); + // check name limitations if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS || (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))) @@ -12620,20 +14793,24 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid); return false; } + if(!LoadValues( fields[2].GetString())) { sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid)); delete result; return false; } + // overwrite possible wrong/corrupted guid SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)); + // overwrite some data fields uint32 bytes0 = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0xFF000000; bytes0 |= fields[4].GetUInt8(); // race bytes0 |= fields[5].GetUInt8() << 8; // class bytes0 |= fields[6].GetUInt8() << 16; // gender SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0); + SetUInt32Value(UNIT_FIELD_LEVEL, fields[7].GetUInt8()); SetUInt32Value(PLAYER_XP, fields[8].GetUInt32()); SetUInt32Value(PLAYER_FIELD_COINAGE, fields[9].GetUInt32()); @@ -12641,33 +14818,42 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) SetUInt32Value(PLAYER_BYTES_2, fields[11].GetUInt32()); SetUInt32Value(PLAYER_BYTES_3, (GetUInt32Value(PLAYER_BYTES_3) & ~1) | fields[6].GetUInt8()); SetUInt32Value(PLAYER_FLAGS, fields[12].GetUInt32()); + InitDisplayIds(); + // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory) for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot) { SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 ); SetVisibleItemSlot(slot, NULL); + if (m_items[slot]) { delete m_items[slot]; m_items[slot] = NULL; } } + // update money limits if(GetMoney() > MAX_MONEY_AMOUNT) SetMoney(MAX_MONEY_AMOUNT); + sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str()); outDebugValues(); + //Need to call it to initialize m_team (m_team can be calculated from race) //Other way is to saves m_team into characters table. setFactionForRace(getRace()); + // load home bind and check in same time class/race pair, it used later for restore broken positions if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND))) { delete result; return false; } + InitPrimaryProfessions(); // to max set before any spell loaded + // init saved position, and fix it later if problematic uint32 transGUID = fields[31].GetUInt32(); Relocate(fields[13].GetFloat(),fields[14].GetFloat(),fields[15].GetFloat(),fields[17].GetFloat()); @@ -12675,28 +14861,38 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) uint32 instanceId = fields[41].GetFloat(); SetDifficulty(fields[39].GetUInt32()); // may be changed in _LoadGroup std::string taxi_nodes = fields[38].GetCppString(); + #define RelocateToHomebind(){ mapId = m_homebindMapId; instanceId = 0; Relocate(m_homebindX, m_homebindY, m_homebindZ); } + _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP)); + _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO)); + uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[40].GetUInt32(); if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS)) arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS); + SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency); + // check arena teams integrity for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot) { uint32 arena_team_id = GetArenaTeamId(arena_slot); if(!arena_team_id) continue; + if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id)) if(at->HaveMember(GetGUID())) continue; + // arena team not exist or not member, cleanup fields for(int j = 0; j < 6; ++j) SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0); } + _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES)); _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA)); + MapEntry const * mapEntry = sMapStore.LookupEntry(mapId); if(!mapEntry || !IsPositionValid()) { @@ -12709,14 +14905,18 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) BattleGround *currentBg = NULL; if(m_bgData.bgInstanceID) //saved in BattleGround currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE); + if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID())) { BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType()); AddBattleGroundQueueId(bgQueueTypeId); + m_bgData.bgTypeID = currentBg->GetTypeID(); + //join player to battleground group currentBg->EventPlayerLoggedIn(this, GetGUID()); currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData.bgTeam); + SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID()); } // Bg was not found - go to Entry Point @@ -12725,6 +14925,7 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) // Do not look for instance if bg not found const WorldLocation& _loc = GetBattleGroundEntryPoint(); mapId = _loc.GetMapId(); instanceId = 0; + if(mapId == MAPID_INVALID) // Battleground Entry Point not found (???) { sLog.outError("Player (guidlow %d) was in BG in database, but BG was not found, and entry point was invalid! Teleport to default race/class locations.",guid); @@ -12732,6 +14933,7 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) } else { Relocate(&_loc); } + // We are not in BG anymore m_bgData.bgInstanceID = 0; } @@ -12741,10 +14943,12 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) { // There are no transports on instances instanceId = 0; + m_movementInfo.t_x = fields[27].GetFloat(); m_movementInfo.t_y = fields[28].GetFloat(); m_movementInfo.t_z = fields[29].GetFloat(); m_movementInfo.t_o = fields[30].GetFloat(); + if( !MaNGOS::IsValidMapCoord( GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y, GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) || @@ -12754,6 +14958,7 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.", guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y, GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o); + RelocateToHomebind(); } else @@ -12772,6 +14977,7 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) { sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.", guid,transGUID); + RelocateToHomebind(); } } @@ -12780,6 +14986,7 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) else if (!taxi_nodes.empty()) { instanceId = 0; + // Not finish taxi flight path if(m_bgData.HasTaxiPath()) { @@ -12792,6 +14999,7 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) TaxiNodesEntry const* nodeEntry = NULL; if(uint32 node_id = m_taxi.GetTaxiSource()) nodeEntry = sTaxiNodesStore.LookupEntry(node_id); + if(!nodeEntry) // don't know taxi start node, to homebind { sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow()); @@ -12805,6 +15013,7 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) } m_taxi.ClearTaxiDestinations(); } + if(uint32 node_id = m_taxi.GetTaxiSource()) { // save source node as recall coord to prevent recall and fall from sky @@ -12812,9 +15021,11 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString mapId = nodeEntry->map_id; Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f); + // flight will started later } } + // Map could be changed before mapEntry = sMapStore.LookupEntry(mapId); // client without expansion support @@ -12823,14 +15034,17 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), mapId); RelocateToHomebind(); } + // fix crash (because of if(Map *map = _FindMap(instanceId)) in MapInstanced::CreateInstance) if(instanceId) if(InstanceSave * save = GetInstanceSave(mapId)) if(save->GetInstanceId() != instanceId) instanceId = 0; + // NOW player must have valid map // load the player's map here if it's not already loaded Map *map = MapManager::Instance().CreateMap(mapId, this, instanceId); + if (!map) { instanceId = 0; @@ -12846,6 +15060,7 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) sLog.outError("Player (guidlow %d) is teleported to home (Map: %u X: %f Y: %f Z: %f O: %f).",guid,mapId,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation()); RelocateToHomebind(); } + map = MapManager::Instance().CreateMap(mapId, this, 0); if(!map) { @@ -12862,6 +15077,7 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) } } } + // if the player is in an instance and it has been reset in the meantime teleport him to the entrance if(instanceId && !sInstanceSaveManager.GetInstanceSave(instanceId)) { @@ -12874,15 +15090,21 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) RelocateToHomebind(); } } + SetMap(map); + // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE] // this must help in case next save after mass player load after server startup m_nextSave = urand(m_nextSave/2,m_nextSave*3/2); + SaveRecallPosition(); + time_t now = time(NULL); time_t logoutTime = time_t(fields[23].GetUInt64()); + // since last logout (in seconds) uint64 time_diff = uint64(now - logoutTime); + // set value, including drunk invisibility detection // calculate sobering. after 15 minutes logged out, the player will be sober again float soberFactor; @@ -12892,46 +15114,61 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) soberFactor = 1-time_diff/(15.0f*MINUTE); uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE)); SetDrunkValue(newDrunkenValue); + m_rest_bonus = fields[22].GetFloat(); //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour) float bubble0 = 0.031; //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour) float bubble1 = 0.125; + if(time_diff > 0) { float bubble = fields[24].GetUInt32() > 0 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY) : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS); + SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble); } + m_cinematic = fields[19].GetUInt32(); m_Played_time[PLAYED_TIME_TOTAL]= fields[20].GetUInt32(); m_Played_time[PLAYED_TIME_LEVEL]= fields[21].GetUInt32(); + m_resetTalentsCost = fields[25].GetUInt32(); m_resetTalentsTime = time_t(fields[26].GetUInt64()); + // reserve some flags uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM ); + if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) ) SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags); + m_taxi.LoadTaxiMask( fields[18].GetString() ); // must be before InitTaxiNodesForLevel + uint32 extraflags = fields[32].GetUInt32(); + m_stableSlots = fields[33].GetUInt32(); if(m_stableSlots > MAX_PET_STABLES) { sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots)); m_stableSlots = MAX_PET_STABLES; } + m_atLoginFlags = fields[34].GetUInt32(); + // Honor system // Update Honor kills data m_lastHonorUpdateTime = logoutTime; UpdateHonorFields(); + m_deathExpireTime = (time_t)fields[37].GetUInt64(); if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP) m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1; + // clear channel spell data (if saved at channel spell casting) SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0); SetUInt32Value(UNIT_CHANNEL_SPELL,0); + // clear charm/summon related fields SetUInt64Value(UNIT_FIELD_SUMMONEDBY, 0); SetUInt64Value(UNIT_FIELD_CHARMEDBY, 0); @@ -12939,32 +15176,43 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) SetUInt64Value(UNIT_FIELD_SUMMON, 0); SetUInt64Value(PLAYER_FARSIGHT, 0); SetCreatorGUID(0); + RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE); + // reset some aura modifiers before aura apply SetUInt32Value(PLAYER_TRACK_CREATURES, 0 ); SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 ); + _LoadSkills(); + // make sure the unit is considered out of combat for proper loading ClearInCombat(); + // make sure the unit is considered not in duel for proper loading SetUInt64Value(PLAYER_DUEL_ARBITER, 0); SetUInt32Value(PLAYER_DUEL_TEAM, 0); + // remember loaded power/health values to restore after stats initialization and modifier applying uint32 savedHealth = GetHealth(); uint32 savedPower[MAX_POWERS]; for(uint32 i = 0; i < MAX_POWERS; ++i) savedPower[i] = GetPower(Powers(i)); + // reset stats before loading any modifiers InitStatsForLevel(); InitTaxiNodesForLevel(); InitGlyphsForLevel(); InitRunes(); + // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods() + //mails are loaded only when needed ;-) - when player in game click on mailbox. //_LoadMail(); + m_specsCount = fields[42].GetUInt32(); m_activeSpec = fields[43].GetUInt32(); delete result; + // sanity check if (m_specsCount > MAX_TALENT_SPECS || m_activeSpec > MAX_TALENT_SPEC || m_specsCount < MIN_TALENT_SPECS || m_activeSpec < MIN_TALENT_SPEC ) // if (m_specsCount < 2) is not logical @@ -12972,29 +15220,40 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) m_activeSpec = 0; sLog.outError("Player %s(GUID: %u) has SpecCount = %u and ActiveSpec = %u.", GetName(), GetGUIDLow(), m_specsCount, m_activeSpec); } + _LoadTalents(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTALENTS)); _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS)); + _LoadGlyphs(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGLYPHS)); _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff); _LoadGlyphAuras(); // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura) if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) ) m_deathState = DEAD; + // after spell load, learn rewarded spell if need also _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS)); _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS)); + // after spell and quest load InitTalentForLevel(); learnDefaultSpells(); + // must be before inventory (some items required reputation check) m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION)); + _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff); + // update items with duration and realtime UpdateItemDuration(time_diff, true); + _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS), true); + // unread mails and next delivery time, actual mails not loaded _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE)); + m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow()); + // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE)) @@ -13002,22 +15261,29 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) if(!HasTitle(curTitle)) SetUInt32Value(PLAYER_CHOSEN_TITLE, 0); } + // has to be called after last Relocate() in Player::LoadFromDB SetFallInformation(0, GetPositionZ()); + _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS)); + // Spell code allow apply any auras to dead character in load time in aura/spell/item loading // Do now before stats re-calculation cleanup for ghost state unexpected auras if(!isAlive()) RemoveAllAurasOnDeath(); + //apply all stat bonuses from items and auras SetCanModifyStats(true); UpdateAllStats(); + // restore remembered power/health values (but not more max values) SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth); for(uint32 i = 0; i < MAX_POWERS; ++i) SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]); + sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str()); outDebugValues(); + // GM state if(GetSession()->GetSecurity() > SEC_PLAYER) { @@ -13031,6 +15297,7 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) SetGameMaster(true); break; } + switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE)) { default: @@ -13041,6 +15308,7 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) SetGMVisible(false); break; } + /*switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS)) { default: @@ -13051,6 +15319,7 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) SetAcceptTicket(true); break; }*/ + switch(sWorld.getConfig(CONFIG_GM_CHAT)) { default: @@ -13061,6 +15330,7 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) SetGMChat(true); break; } + switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO)) { default: @@ -13072,16 +15342,22 @@ bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder ) break; } } + _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES)); + m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS)); m_achievementMgr.CheckAllAchievementCriteria(); + _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS)); + return true; } + bool Player::isAllowedToLoot(Creature* creature) { if(creature->isDead() && !creature->IsDamageEnoughForLootingAndReward()) return false; + if(Player* recipient = creature->GetLootRecipient()) { if (recipient == this) @@ -13099,6 +15375,7 @@ bool Player::isAllowedToLoot(Creature* creature) // prevent other players from looting if the recipient got disconnected return !creature->hasLootRecipient(); } + void Player::_LoadActions(QueryResult *result, bool startup) { if(result) @@ -13106,9 +15383,11 @@ void Player::_LoadActions(QueryResult *result, bool startup) do { Field *fields = result->Fetch(); + uint8 button = fields[0].GetUInt8(); uint32 action = fields[1].GetUInt32(); uint8 type = fields[2].GetUInt8(); + if(ActionButton* ab = addActionButton(button, action, type)) { ab->uState = ACTIONBUTTON_UNCHANGED; @@ -13118,18 +15397,23 @@ void Player::_LoadActions(QueryResult *result, bool startup) else { sLog.outError( " ...at loading, and will deleted in DB also"); + // Will deleted in DB at next save (it can create data until save but marked as deleted) m_actionButtons[button].uState = ACTIONBUTTON_DELETED; } } while( result->NextRow() ); + delete result; } } + void Player::_LoadAuras(QueryResult *result, uint32 timediff) { sLog.outDebug("Loading auras for player %u",GetGUIDLow()); + //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_mask,stackcount,amount0,amount1,amount2,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow()); + if(result) { do @@ -13146,19 +15430,23 @@ void Player::_LoadAuras(QueryResult *result, uint32 timediff) int32 maxduration = (int32)fields[7].GetUInt32(); int32 remaintime = (int32)fields[8].GetUInt32(); int32 remaincharges = (int32)fields[9].GetUInt32(); + SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid); if(!spellproto) { sLog.outError("Unknown aura (spellid %u), ignore.",spellid); continue; } + // negative effects should continue counting down after logout if (remaintime != -1 && !IsPositiveSpell(spellid)) { if(remaintime <= int32(timediff)) continue; + remaintime -= timediff; } + // prevent wrong values of remaincharges if(spellproto->procCharges) { @@ -13167,6 +15455,7 @@ void Player::_LoadAuras(QueryResult *result, uint32 timediff) } else remaincharges = 0; + Aura* aura = new Aura(spellproto, effmask, this, this, this); aura->SetLoadedState(caster_guid,maxduration,remaintime,remaincharges, stackcount, &damage[0]); if(!aura->CanBeSaved()) @@ -13178,11 +15467,14 @@ void Player::_LoadAuras(QueryResult *result, uint32 timediff) sLog.outDetail("Added aura spellid %u, effectmask %u", spellproto->Id, effmask); } while( result->NextRow() ); + delete result; } + if(getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT)) CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true); } + void Player::_LoadGlyphAuras() { for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i) @@ -13206,11 +15498,13 @@ void Player::_LoadGlyphAuras() } else sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i); + // On any error remove glyph SetGlyph(i, 0); } } } + void Player::LoadCorpse() { if( isAlive() ) @@ -13230,6 +15524,7 @@ void Player::LoadCorpse() } } } + void Player::_LoadInventory(QueryResult *result, uint32 timediff) { //QueryResult *result = CharacterDatabase.PQuery("SELECT data,bag,slot,item,item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '%u' ORDER BY bag,slot", GetGUIDLow()); @@ -13238,10 +15533,13 @@ void Player::_LoadInventory(QueryResult *result, uint32 timediff) //the bagMap is filled before items in the bags are loaded //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?) //expected to be equipped before offhand items (TODO: fixme) + uint32 zone = GetZoneId(); + if (result) { std::list<Item*> problematicItems; + // prevent items from being added to the queue when stored m_itemUpdateQueueBlocked = true; do @@ -13251,7 +15549,9 @@ void Player::_LoadInventory(QueryResult *result, uint32 timediff) uint8 slot = fields[2].GetUInt8(); uint32 item_guid = fields[3].GetUInt32(); uint32 item_id = fields[4].GetUInt32(); + ItemPrototype const * proto = objmgr.GetItemPrototype(item_id); + if(!proto) { CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid); @@ -13259,7 +15559,9 @@ void Player::_LoadInventory(QueryResult *result, uint32 timediff) sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id ); continue; } + Item *item = NewItemOrBag(proto); + if(!item->LoadFromDB(item_guid, GetGUID(), result)) { sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id ); @@ -13268,6 +15570,7 @@ void Player::_LoadInventory(QueryResult *result, uint32 timediff) item->SaveToDB(); // it also deletes item object ! continue; } + // not allow have in alive state item limited to another map/zone if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) ) { @@ -13276,6 +15579,7 @@ void Player::_LoadInventory(QueryResult *result, uint32 timediff) item->SaveToDB(); // it also deletes item object ! continue; } + // "Conjured items disappear if you are logged out for more than 15 minutes" if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED))) { @@ -13284,12 +15588,15 @@ void Player::_LoadInventory(QueryResult *result, uint32 timediff) item->SaveToDB(); // it also deletes item object ! continue; } + bool success = true; + if (!bag_guid) { // the item is not in a bag item->SetContainer( NULL ); item->SetSlot(slot); + if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) ) { ItemPosCountVec dest; @@ -13314,6 +15621,7 @@ void Player::_LoadInventory(QueryResult *result, uint32 timediff) else success = false; } + if(success) { // store bags that may contain items in them @@ -13341,6 +15649,7 @@ void Player::_LoadInventory(QueryResult *result, uint32 timediff) else success = false; } + // item's state may have changed after stored if (success) item->SetState(ITEM_UNCHANGED, this); @@ -13351,26 +15660,33 @@ void Player::_LoadInventory(QueryResult *result, uint32 timediff) problematicItems.push_back(item); } } while (result->NextRow()); + delete result; m_itemUpdateQueueBlocked = false; + // send by mail problematic items while(!problematicItems.empty()) { // fill mail MailItemsInfo mi; // item list preparing + for(uint8 i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i) { Item* item = problematicItems.front(); problematicItems.pop_front(); + mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item); } + std::string subject = GetSession()->GetTrinityString(LANG_NOT_EQUIPPED_ITEM); + WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE); } } //if(isAlive()) _ApplyAllItemMods(); } + // load mailed item which should receive current player void Player::_LoadMailedItems(Mail *mail) { @@ -13378,13 +15694,17 @@ void Player::_LoadMailedItems(Mail *mail) QueryResult* result = CharacterDatabase.PQuery("SELECT data, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail->messageID); if(!result) return; + do { Field *fields = result->Fetch(); uint32 item_guid_low = fields[1].GetUInt32(); uint32 item_template = fields[2].GetUInt32(); + mail->AddItem(item_guid_low, item_template); + ItemPrototype const *proto = objmgr.GetItemPrototype(item_template); + if(!proto) { sLog.outError( "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID); @@ -13392,7 +15712,9 @@ void Player::_LoadMailedItems(Mail *mail) CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low); continue; } + Item *item = NewItemOrBag(proto); + if(!item->LoadFromDB(item_guid_low, 0, result)) { sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low); @@ -13401,10 +15723,13 @@ void Player::_LoadMailedItems(Mail *mail) item->SaveToDB(); // it also deletes item object ! continue; } + AddMItem(item); } while (result->NextRow()); + delete result; } + void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery) { //set a count of unread mails @@ -13415,6 +15740,7 @@ void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDeliver unReadMails = fieldMail[0].GetUInt8(); delete resultUnread; } + // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called) //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid)); if (resultDelivery) @@ -13424,6 +15750,7 @@ void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDeliver delete resultDelivery; } } + void Player::_LoadMail() { m_mail.clear(); @@ -13449,20 +15776,25 @@ void Player::_LoadMail() m->checked = fields[11].GetUInt32(); m->stationery = fields[12].GetUInt8(); m->mailTemplateId = fields[13].GetInt16(); + if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId)) { sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId); m->mailTemplateId = 0; } + m->state = MAIL_STATE_UNCHANGED; + if (has_items) _LoadMailedItems(m); + m_mail.push_back(m); } while( result->NextRow() ); delete result; } m_mailsLoaded = true; } + void Player::LoadPet() { //fixme: the pet should still be loaded if the player is not in world @@ -13474,17 +15806,22 @@ void Player::LoadPet() delete pet; } } + void Player::_LoadQuestStatus(QueryResult *result) { mQuestStatus.clear(); + uint32 slot = 0; + //// 0 1 2 3 4 5 6 7 8 9 10 11 12 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest, status, rewarded, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3, itemcount4 FROM character_queststatus WHERE guid = '%u'", GetGUIDLow()); + if(result) { do { Field *fields = result->Fetch(); + uint32 quest_id = fields[0].GetUInt32(); // used to be new, no delete? Quest const* pQuest = objmgr.GetQuestTemplate(quest_id); @@ -13492,6 +15829,7 @@ void Player::_LoadQuestStatus(QueryResult *result) { // find or create QuestStatusData& questStatusData = mQuestStatus[quest_id]; + uint32 qstatus = fields[1].GetUInt32(); if(qstatus < MAX_QUEST_STATUS) questStatusData.m_status = QuestStatus(qstatus); @@ -13500,12 +15838,16 @@ void Player::_LoadQuestStatus(QueryResult *result) questStatusData.m_status = QUEST_STATUS_NONE; sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus); } + questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 ); questStatusData.m_explored = ( fields[3].GetUInt8() > 0 ); + time_t quest_time = time_t(fields[4].GetUInt64()); + if( pQuest->HasFlag( QUEST_TRINITY_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE ) { AddTimedQuest( quest_id ); + if (quest_time <= sWorld.GetGameTime()) questStatusData.m_timer = 1; else @@ -13513,6 +15855,7 @@ void Player::_LoadQuestStatus(QueryResult *result) } else quest_time = 0; + questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32(); questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32(); questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32(); @@ -13521,7 +15864,9 @@ void Player::_LoadQuestStatus(QueryResult *result) questStatusData.m_itemcount[1] = fields[10].GetUInt32(); questStatusData.m_itemcount[2] = fields[11].GetUInt32(); questStatusData.m_itemcount[3] = fields[12].GetUInt32(); + questStatusData.uState = QUEST_UNCHANGED; + // add to quest log if (slot < MAX_QUEST_LOG_SIZE && ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE || @@ -13530,46 +15875,60 @@ void Player::_LoadQuestStatus(QueryResult *result) (!questStatusData.m_rewarded || pQuest->IsDaily()))) { SetQuestSlot(slot, quest_id, quest_time); + if (questStatusData.m_status == QUEST_STATUS_COMPLETE) SetQuestSlotState(slot, QUEST_STATE_COMPLETE); + if (questStatusData.m_status == QUEST_STATUS_FAILED) SetQuestSlotState(slot, QUEST_STATE_FAIL); + for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx) if(questStatusData.m_creatureOrGOcount[idx]) SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]); + ++slot; } + if(questStatusData.m_rewarded) { // learn rewarded spell if unknown learnQuestRewardedSpells(pQuest); + // set rewarded title if any if(pQuest->GetCharTitleId()) { if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId())) SetTitle(titleEntry); } + if(pQuest->GetBonusTalents()) m_questRewardTalentCount += pQuest->GetBonusTalents(); } + sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow()); } } while( result->NextRow() ); + delete result; } + // clear quest log tail for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i ) SetQuestSlot(i, 0); } + void Player::_LoadDailyQuestStatus(QueryResult *result) { for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0); + //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow()); + if(result) { uint32 quest_daily_idx = 0; + do { if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query @@ -13577,36 +15936,49 @@ void Player::_LoadDailyQuestStatus(QueryResult *result) sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow()); break; } + Field *fields = result->Fetch(); + uint32 quest_id = fields[0].GetUInt32(); + // save _any_ from daily quest times (it must be after last reset anyway) m_lastDailyQuestTime = (time_t)fields[1].GetUInt64(); + Quest const* pQuest = objmgr.GetQuestTemplate(quest_id); if( !pQuest ) continue; + SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id); ++quest_daily_idx; + sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow()); } while( result->NextRow() ); + delete result; } + m_DailyQuestChanged = false; } + void Player::_LoadSpells(QueryResult *result) { //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow()); + if(result) { do { Field *fields = result->Fetch(); + addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool()); } while( result->NextRow() ); + delete result; } } + void Player::_LoadGroup(QueryResult *result) { //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow()); @@ -13627,11 +15999,14 @@ void Player::_LoadGroup(QueryResult *result) } } } + void Player::_LoadBoundInstances(QueryResult *result) { for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++) m_boundInstances[i].clear(); + Group *group = GetGroup(); + //QueryResult *result = CharacterDatabase.PQuery("SELECT id, permanent, map, difficulty, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = '%u'", GUID_LOPART(m_guid)); if(result) { @@ -13646,6 +16021,7 @@ void Player::_LoadBoundInstances(QueryResult *result) // the resettime for normal instances is only saved when the InstanceSave is unloaded // so the value read from the DB may be wrong here but only if the InstanceSave is loaded // and in that case it is not used + MapEntry const* mapEntry = sMapStore.LookupEntry(mapId); if(!mapEntry || !mapEntry->IsDungeon()) { @@ -13653,12 +16029,14 @@ void Player::_LoadBoundInstances(QueryResult *result) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId); continue; } + if(!perm && group) { sLog.outError("_LoadBoundInstances: player %s(%d) is in group %d but has a non-permanent character bind to map %d,%d,%d", GetName(), GetGUIDLow(), GUID_LOPART(group->GetLeaderGUID()), mapId, instanceId, difficulty); CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId); continue; } + // since non permanent binds are always solo bind, they can always be reset InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true); if(save) BindToInstance(save, perm, true); @@ -13666,17 +16044,20 @@ void Player::_LoadBoundInstances(QueryResult *result) delete result; } } + InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty) { // some instances only have one difficulty const MapEntry* entry = sMapStore.LookupEntry(mapid); if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL; + BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid); if(itr != m_boundInstances[difficulty].end()) return &itr->second; else return NULL; } + InstanceSave * Player::GetInstanceSave(uint32 mapid) { InstancePlayerBind *pBind = GetBoundInstance(mapid, GetDifficulty()); @@ -13689,11 +16070,13 @@ InstanceSave * Player::GetInstanceSave(uint32 mapid) } return pSave; } + void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload) { BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid); UnbindInstance(itr, difficulty, unload); } + void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload) { if(itr != m_boundInstances[difficulty].end()) @@ -13703,6 +16086,7 @@ void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, m_boundInstances[difficulty].erase(itr++); } } + InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load) { if(save) @@ -13716,12 +16100,15 @@ InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, b } else if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent); + if(bind.save != save) { if(bind.save) bind.save->RemovePlayer(this); save->AddPlayer(this); } + if(permanent) save->SetCanReset(false); + bind.save = save; bind.perm = permanent; if(!load) sLog.outDebug("Player::BindToInstance: %s(%d) is now bound to map %d, instance %d, difficulty %d", GetName(), GetGUIDLow(), save->GetMapId(), save->GetInstanceId(), save->GetDifficulty()); @@ -13730,13 +16117,18 @@ InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, b else return NULL; } + void Player::SendRaidInfo() { uint32 counter = 0; + WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4); + size_t p_counter = data.wpos(); data << uint32(counter); // placeholder + time_t now = time(NULL); + for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i) { for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr) @@ -13756,6 +16148,7 @@ void Player::SendRaidInfo() data.put<uint32>(p_counter, counter); GetSession()->SendPacket(&data); } + /* - called on every successful teleportation to a map */ @@ -13763,6 +16156,7 @@ void Player::SendSavedInstances() { bool hasBeenSaved = false; WorldPacket data; + for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++) { for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr) @@ -13774,12 +16168,15 @@ void Player::SendSavedInstances() } } } + //Send opcode 811. true or false means, whether you have current raid/heroic instances data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP); data << uint32(hasBeenSaved); GetSession()->SendPacket(&data); + if(!hasBeenSaved) return; + for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++) { for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr) @@ -13793,15 +16190,19 @@ void Player::SendSavedInstances() } } } + /// convert the player's binds to the group void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid) { bool has_binds = false; bool has_solo = false; + if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); } assert(player_guid); + // copy all binds to the group, when changing leader it's assumed the character // will not have any solo binds + if(player) { for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++) @@ -13821,17 +16222,20 @@ void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player } } } + // if the player's not online we don't know what binds it has if(!player || !group || has_binds) CharacterDatabase.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid)); // the following should not get executed when changing leaders if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid)); } + bool Player::Satisfy(AccessRequirement const *ar, uint32 target_map, bool report) { if(!isGameMaster() && ar) { uint32 LevelMin = 0; uint32 LevelMax = 0; + if(!sWorld.getConfig(CONFIG_INSTANCE_IGNORE_LEVEL)) { if(ar->levelMin && getLevel() < ar->levelMin) @@ -13841,6 +16245,7 @@ bool Player::Satisfy(AccessRequirement const *ar, uint32 target_map, bool report if(ar->levelMax && getLevel() > ar->levelMax) LevelMax = ar->levelMax; } + uint32 missingItem = 0; if(ar->item) { @@ -13850,6 +16255,7 @@ bool Player::Satisfy(AccessRequirement const *ar, uint32 target_map, bool report } else if(ar->item2 && !HasItemCount(ar->item2, 1)) missingItem = ar->item2; + uint32 missingKey = 0; uint32 missingHeroicQuest = 0; if(GetDifficulty() == DIFFICULTY_HEROIC) @@ -13862,12 +16268,15 @@ bool Player::Satisfy(AccessRequirement const *ar, uint32 target_map, bool report } else if(ar->heroicKey2 && !HasItemCount(ar->heroicKey2, 1)) missingKey = ar->heroicKey2; + if(ar->heroicQuest && !GetQuestRewardStatus(ar->heroicQuest)) missingHeroicQuest = ar->heroicQuest; } + uint32 missingQuest = 0; if(ar->quest && !GetQuestRewardStatus(ar->quest)) missingQuest = ar->quest; + if(LevelMin || LevelMax || missingItem || missingKey || missingQuest || missingHeroicQuest) { if(report) @@ -13888,6 +16297,7 @@ bool Player::Satisfy(AccessRequirement const *ar, uint32 target_map, bool report } return true; } + bool Player::_LoadHomeBind(QueryResult *result) { PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass()); @@ -13896,6 +16306,7 @@ bool Player::_LoadHomeBind(QueryResult *result) sLog.outError("Player have incorrect race/class pair. Can't be loaded."); return false; } + bool ok = false; //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid)); if (result) @@ -13907,7 +16318,9 @@ bool Player::_LoadHomeBind(QueryResult *result) m_homebindY = fields[3].GetFloat(); m_homebindZ = fields[4].GetFloat(); delete result; + MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId); + // accept saved data only for valid position (and non instanceable), and accessable if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) && !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion()) @@ -13917,6 +16330,7 @@ bool Player::_LoadHomeBind(QueryResult *result) else CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow()); } + if(!ok) { m_homebindMapId = info->mapId; @@ -13924,33 +16338,45 @@ bool Player::_LoadHomeBind(QueryResult *result) m_homebindX = info->positionX; m_homebindY = info->positionY; m_homebindZ = info->positionZ; + CharacterDatabase.PExecute("INSERT INTO character_homebind (guid,map,zone,position_x,position_y,position_z) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GetGUIDLow(), m_homebindMapId, (uint32)m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ); } + DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f", m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ); + return true; } + /*********************************************************/ /*** SAVE SYSTEM ***/ /*********************************************************/ + void Player::SaveToDB() { // delay auto save at any saves (manual, in code, or autosave) m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE); + //lets allow only players in world to be saved if(IsBeingTeleportedFar()) { ScheduleDelayedOperation(DELAYED_SAVE_PLAYER); return; } + // first save/honor gain after midnight will also update the player's honor fields UpdateHonorFields(); + sLog.outDebug("The value of player %s at save: ", m_name.c_str()); outDebugValues(); + CharacterDatabase.BeginTransaction(); + CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow()); + std::string sql_name = m_name; CharacterDatabase.escape_string(sql_name); + std::ostringstream ss; ss << "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags," "map, instance_id, dungeon_difficulty, position_x, position_y, position_z, orientation, data, " @@ -13970,6 +16396,7 @@ void Player::SaveToDB() << GetUInt32Value(PLAYER_BYTES) << ", " << GetUInt32Value(PLAYER_BYTES_2) << ", " << GetUInt32Value(PLAYER_FLAGS) << ", "; + if(!IsBeingTeleported()) { ss << GetMapId() << ", " @@ -13990,17 +16417,24 @@ void Player::SaveToDB() << finiteAlways(GetTeleportDest().GetPositionZ()) << ", " << finiteAlways(GetTeleportDest().GetOrientation()) << ", '"; } + uint16 i; for( i = 0; i < m_valuesCount; i++ ) { ss << GetUInt32Value(i) << " "; } + ss << "', "; + ss << m_taxi << ", "; // string with TaxiMaskSize numbers + ss << (IsInWorld() ? 1 : 0) << ", "; + ss << m_cinematic << ", "; + ss << m_Played_time[PLAYED_TIME_TOTAL] << ", "; ss << m_Played_time[PLAYED_TIME_LEVEL] << ", "; + ss << finiteAlways(m_rest_bonus) << ", "; ss << (uint64)time(NULL) << ", "; ss << (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0) << ", "; @@ -14008,6 +16442,7 @@ void Player::SaveToDB() //save, but in tavern/city ss << m_resetTalentsCost << ", "; ss << (uint64)m_resetTalentsTime << ", "; + ss << finiteAlways(m_movementInfo.t_x) << ", "; ss << finiteAlways(m_movementInfo.t_y) << ", "; ss << finiteAlways(m_movementInfo.t_z) << ", "; @@ -14017,11 +16452,17 @@ void Player::SaveToDB() else ss << "0"; ss << ", "; + ss << m_ExtraFlags << ", "; + ss << uint32(m_stableSlots) << ", "; // to prevent save uint8 as char + ss << uint32(m_atLoginFlags) << ", "; + ss << GetZoneId() << ", "; + ss << (uint64)m_deathExpireTime << ", '"; + ss << m_taxi.SaveTaxiDestinationsToString() << "', "; ss << "'0', "; // arena_pending_points ss << GetSession()->GetLatency(); @@ -14030,9 +16471,12 @@ void Player::SaveToDB() ss << ", "; ss << uint32(m_activeSpec); ss << ")"; + CharacterDatabase.Execute( ss.str().c_str() ); + if(m_mailsUpdated) //save mails only when needed _SaveMail(); + _SaveBGData(); _SaveInventory(); _SaveQuestStatus(); @@ -14047,21 +16491,26 @@ void Player::SaveToDB() _SaveEquipmentSets(); GetSession()->SaveTutorialsData(); // changed only while character in game _SaveGlyphs(); + CharacterDatabase.CommitTransaction(); + // save pet (hunter pet level and experience and all type pets health/mana). if(Pet* pet = GetPet()) pet->SavePetToDB(PET_SAVE_AS_CURRENT); } + // fast save function for item/money cheating preventing - save only inventory and money state void Player::SaveInventoryAndGoldToDB() { _SaveInventory(); SaveGoldToDB(); } + void Player::SaveGoldToDB() { CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow()); } + void Player::_SaveActions() { for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); ) @@ -14090,14 +16539,17 @@ void Player::_SaveActions() } } } + void Player::_SaveAuras() { CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow()); + AuraMap const& auras = GetAuras(); for(AuraMap::const_iterator itr = auras.begin(); itr !=auras.end() ; ++itr) { if(!itr->second->CanBeSaved()) continue; + int32 amounts[MAX_SPELL_EFFECTS]; for (uint8 i=0;i<MAX_SPELL_EFFECTS;++i) { @@ -14106,6 +16558,7 @@ void Player::_SaveAuras() else amounts[i]=0; } + CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_mask,stackcount,amount0, amount1, amount2,maxduration,remaintime,remaincharges) " "VALUES ('%u', '" UI64FMTD "', '%u', '%u', '%d', '%d', '%d', '%d', '%d', '%d', '%d')", GetGUIDLow(), itr->second->GetCasterGUID(),(uint32)itr->second->GetId(), (uint32)itr->second->GetEffectMask(), @@ -14113,6 +16566,7 @@ void Player::_SaveAuras() ,int(itr->second->GetAuraMaxDuration()),int(itr->second->GetAuraDuration()),int(itr->second->GetAuraCharges())); } } + void Player::_SaveInventory() { // force items in buyback slots to new state @@ -14125,13 +16579,16 @@ void Player::_SaveInventory() CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow()); m_items[i]->FSetState(ITEM_NEW); } + // update enchantment durations for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr) { itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration); } + // if no changes if (m_itemUpdateQueue.empty()) return; + // do not save if the update queue is corrupt bool error = false; for(size_t i = 0; i < m_itemUpdateQueue.size(); i++) @@ -14139,6 +16596,7 @@ void Player::_SaveInventory() Item *item = m_itemUpdateQueue[i]; if(!item || item->GetState() == ITEM_REMOVED) continue; Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot()); + if (test == NULL) { sLog.outCrash("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d (state %d) are incorrect, the player doesn't have an item at that position!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), (int32)item->GetState()); @@ -14151,18 +16609,22 @@ void Player::_SaveInventory() error = true; } } + if (error) { sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!"); ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED); return; } + for(size_t i = 0; i < m_itemUpdateQueue.size(); i++) { Item *item = m_itemUpdateQueue[i]; if(!item) continue; + Bag *container = item->GetContainer(); uint32 bag_guid = container ? container->GetGUIDLow() : 0; + switch(item->GetState()) { case ITEM_NEW: @@ -14177,14 +16639,17 @@ void Player::_SaveInventory() case ITEM_UNCHANGED: break; } + item->SaveToDB(); // item have unchanged inventory record and can be save standalone } m_itemUpdateQueue.clear(); } + void Player::_SaveMail() { if (!m_mailsLoaded) return; + for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr) { Mail *m = (*itr); @@ -14211,6 +16676,7 @@ void Player::_SaveMail() CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID); } } + //deallocate deleted mails... for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ) { @@ -14224,8 +16690,10 @@ void Player::_SaveMail() else ++itr; } + m_mailsUpdated = false; } + void Player::_SaveQuestStatus() { // we don't need transactions here. @@ -14248,12 +16716,16 @@ void Player::_SaveQuestStatus() i->second.uState = QUEST_UNCHANGED; } } + void Player::_SaveDailyQuestStatus() { if(!m_DailyQuestChanged) return; + m_DailyQuestChanged = false; + // save last daily quest time for all quests: we need only mostly reset time for reset check anyway + // we don't need transactions here. CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow()); for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) @@ -14261,15 +16733,18 @@ void Player::_SaveDailyQuestStatus() CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')", GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime)); } + void Player::_SaveSpells() { for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();) { if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED) CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first); + // add only changed/new not dependent spells if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)) CharacterDatabase.PExecute("INSERT INTO character_spell (guid,spell,active,disabled) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), itr->first, itr->second->active ? 1 : 0,itr->second->disabled ? 1 : 0); + if (itr->second->state == PLAYERSPELL_REMOVED) { delete itr->second; @@ -14280,12 +16755,15 @@ void Player::_SaveSpells() itr->second->state = PLAYERSPELL_UNCHANGED; ++itr; } + } } + void Player::outDebugValues() const { if(!sLog.IsOutDebug()) // optimize disabled debug output return; + sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA)); sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH)); sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT)); @@ -14299,20 +16777,24 @@ void Player::outDebugValues() const sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE)); sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK)); } + /*********************************************************/ /*** FLOOD FILTER SYSTEM ***/ /*********************************************************/ + void Player::UpdateSpeakTime() { // ignore chat spam protection for GMs in any mode if(GetSession()->GetSecurity() > SEC_PLAYER) return; + time_t current = time (NULL); if(m_speakTime > current) { uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT); if(!max_count) return; + ++m_speakCount; if(m_speakCount >= max_count) { @@ -14320,25 +16802,31 @@ void Player::UpdateSpeakTime() time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME); if(GetSession()->m_muteTime < new_mute) GetSession()->m_muteTime = new_mute; + m_speakCount = 0; } } else m_speakCount = 0; + m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY); } + bool Player::CanSpeak() const { return GetSession()->m_muteTime <= time (NULL); } + /*********************************************************/ /*** LOW LEVEL FUNCTIONS:Notifiers ***/ /*********************************************************/ + void Player::SendAttackSwingNotInRange() { WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0); GetSession()->SendPacket( &data ); } + void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid) { std::ostringstream ss; @@ -14349,17 +16837,21 @@ void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint sLog.outDebug(ss.str().c_str()); CharacterDatabase.Execute(ss.str().c_str()); } + void Player::SaveDataFieldToDB() { std::ostringstream ss; ss<<"UPDATE characters SET data='"; + for(uint16 i = 0; i < m_valuesCount; i++ ) { ss << GetUInt32Value(i) << " "; } ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'"; + CharacterDatabase.Execute(ss.str().c_str()); } + bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid) { std::ostringstream ss2; @@ -14370,73 +16862,93 @@ bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid) ss2<<tokens[i]<<" "; } ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'"; + return CharacterDatabase.Execute(ss2.str().c_str()); } + void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value) { char buf[11]; snprintf(buf,11,"%u",value); + if(index >= tokens.size()) return; + tokens[index] = buf; } + void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid) { Tokens tokens; if(!LoadValuesArrayFromDB(tokens,guid)) return; + if(index >= tokens.size()) return; + char buf[11]; snprintf(buf,11,"%u",value); tokens[index] = buf; + SaveValuesArrayInDB(tokens,guid); } + void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid) { uint32 temp; memcpy(&temp, &value, sizeof(value)); Player::SetUInt32ValueInDB(index, temp, guid); } + void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair) { // 0 QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid)); if(!result) return; + Field* fields = result->Fetch(); + uint32 player_bytes2 = fields[0].GetUInt32(); player_bytes2 &= ~0xFF; player_bytes2 |= facialHair; + CharacterDatabase.PExecute("UPDATE characters SET gender = '%u', playerBytes = '%u', playerBytes2 = '%u' WHERE guid = '%u'", gender, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24), player_bytes2, GUID_LOPART(guid)); + delete result; } + void Player::SendAttackSwingDeadTarget() { WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0); GetSession()->SendPacket( &data ); } + void Player::SendAttackSwingCantAttack() { WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0); GetSession()->SendPacket( &data ); } + void Player::SendAttackSwingCancelAttack() { WorldPacket data(SMSG_CANCEL_COMBAT, 0); GetSession()->SendPacket( &data ); } + void Player::SendAttackSwingBadFacingAttack() { WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0); GetSession()->SendPacket( &data ); } + void Player::SendAutoRepeatCancel(Unit *target) { WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size()); data.append(target->GetPackGUID()); // may be it's target guid GetSession()->SendPacket( &data ); } + void Player::SendExplorationExperience(uint32 Area, uint32 Experience) { WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 ); @@ -14444,6 +16956,7 @@ void Player::SendExplorationExperience(uint32 Area, uint32 Experience) data << Experience; GetSession()->SendPacket(&data); } + void Player::SendDungeonDifficulty(bool IsInGroup) { uint8 val = 0x00000001; @@ -14453,18 +16966,22 @@ void Player::SendDungeonDifficulty(bool IsInGroup) data << uint32(IsInGroup); GetSession()->SendPacket(&data); } + void Player::SendResetFailedNotify(uint32 mapid) { WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4); data << uint32(mapid); GetSession()->SendPacket(&data); } + /// Reset all solo instances and optionally send a message on success for each void Player::ResetInstances(uint8 method) { // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN + // we assume that when the difficulty changes, all instances that can be reset will be uint8 dif = GetDifficulty(); + for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();) { InstanceSave *p = itr->second.save; @@ -14474,6 +16991,7 @@ void Player::ResetInstances(uint8 method) ++itr; continue; } + if(method == INSTANCE_RESET_ALL) { // the "reset all instances" method can only reset normal maps @@ -14483,6 +17001,7 @@ void Player::ResetInstances(uint8 method) continue; } } + // if the map is loaded, reset it Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId()); if(map && map->IsDungeon()) @@ -14491,21 +17010,26 @@ void Player::ResetInstances(uint8 method) ++itr; continue; } + // since this is a solo instance there should not be any players inside if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY) SendResetInstanceSuccess(p->GetMapId()); + p->DeleteFromDB(); m_boundInstances[dif].erase(itr++); + // the following should remove the instance save from the manager and delete it as well p->RemovePlayer(this); } } + void Player::SendResetInstanceSuccess(uint32 MapId) { WorldPacket data(SMSG_INSTANCE_RESET, 4); data << MapId; GetSession()->SendPacket(&data); } + void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId) { // TODO: find what other fail reasons there are besides players in the instance @@ -14514,9 +17038,11 @@ void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId) data << MapId; GetSession()->SendPacket(&data); } + /*********************************************************/ /*** Update timers ***/ /*********************************************************/ + ///checks the 15 afk reports per 5 minutes limit void Player::UpdateAfkReport(time_t currTime) { @@ -14526,6 +17052,7 @@ void Player::UpdateAfkReport(time_t currTime) m_bgData.bgAfkReportedTimer = currTime+5*MINUTE; } } + void Player::UpdateContestedPvP(uint32 diff) { if(!m_contestedPvPTimer||isInCombat()) @@ -14537,54 +17064,68 @@ void Player::UpdateContestedPvP(uint32 diff) else m_contestedPvPTimer -= diff; } + void Player::UpdatePvPFlag(time_t currTime) { if(!IsPvP()) return; if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300)) return; + UpdatePvP(false); } + void Player::UpdateDuelFlag(time_t currTime) { if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3) return; + SetUInt32Value(PLAYER_DUEL_TEAM, 1); duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2); + duel->startTimer = 0; duel->startTime = currTime; duel->opponent->duel->startTimer = 0; duel->opponent->duel->startTime = currTime; } + Pet* Player::GetPet() const { if(uint64 pet_guid = GetPetGUID()) { if(!IS_PET_GUID(pet_guid)) return NULL; + if(Pet* pet = ObjectAccessor::GetPet(pet_guid)) return pet; + //there may be a guardian in slot //sLog.outError("Player::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid)); //const_cast<Player*>(this)->SetPetGUID(0); } + return NULL; } + void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent) { if(!pet) pet = GetPet(); + if(pet) { sLog.outDebug("RemovePet %u, %u, %u", pet->GetEntry(), mode, returnreagent); + if(pet->m_removed) return; } + if(returnreagent && (pet || m_temporaryUnsummonedPetNumber) && !InBattleGround()) { //returning of reagents only for players, so best done here uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell; SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); + if(spellInfo) { for(uint32 i = 0; i < 7; ++i) @@ -14604,9 +17145,12 @@ void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent) } m_temporaryUnsummonedPetNumber = 0; } + if(!pet || pet->GetOwnerGUID()!=GetGUID()) return; + pet->CombatStop(); + if(returnreagent) { switch(pet->GetEntry()) @@ -14620,25 +17164,32 @@ void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent) break; } } + // only if current pet in slot pet->SavePetToDB(mode); + SetMinion(pet, false); + pet->AddObjectToRemoveList(); pet->m_removed = true; + if(pet->isControlled()) { WorldPacket data(SMSG_PET_SPELLS, 8); data << uint64(0); GetSession()->SendPacket(&data); + if(GetGroup()) SetGroupUpdateFlag(GROUP_UPDATE_PET); } } + void Player::StopCastingCharm() { Unit* charm = GetCharm(); if(!charm) return; + if(charm->GetTypeId() == TYPEID_UNIT) { if(((Creature*)charm)->HasUnitTypeMask(UNIT_MASK_PUPPET)) @@ -14648,6 +17199,7 @@ void Player::StopCastingCharm() } if(GetCharmGUID()) charm->RemoveCharmAuras(); + if(GetCharmGUID()) { sLog.outCrash("Player %s (GUID: " UI64FMTD " is not able to uncharm unit (GUID: " UI64FMTD " Entry: %u, Type: %u)", GetName(), GetGUID(), GetCharmGUID(), charm->GetEntry(), charm->GetTypeId()); @@ -14660,6 +17212,7 @@ void Player::StopCastingCharm() SetCharm(charm, false); } } + void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const { *data << (uint8)msgtype; @@ -14671,47 +17224,58 @@ void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string *data << text; *data << (uint8)chatTag(); } + void Player::Say(const std::string& text, const uint32 language) { WorldPacket data(SMSG_MESSAGECHAT, 200); BuildPlayerChat(&data, CHAT_MSG_SAY, text, language); SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true); + if(sWorld.getConfig(CONFIG_CHATLOG_PUBLIC)) sLog.outChat("[SAY] Player %s says (language %u): %s", GetName(), language, text.c_str()); } + void Player::Yell(const std::string& text, const uint32 language) { WorldPacket data(SMSG_MESSAGECHAT, 200); BuildPlayerChat(&data, CHAT_MSG_YELL, text, language); SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true); + if(sWorld.getConfig(CONFIG_CHATLOG_PUBLIC)) sLog.outChat("[YELL] Player %s yells (language %u): %s", GetName(), language, text.c_str()); } + void Player::TextEmote(const std::string& text) { WorldPacket data(SMSG_MESSAGECHAT, 200); BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL); SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT)); + if(sWorld.getConfig(CONFIG_CHATLOG_PUBLIC)) sLog.outChat("[TEXTEMOTE] Player %s emotes: %s", GetName(), text.c_str()); } + void Player::Whisper(const std::string& text, uint32 language,uint64 receiver) { if (language != LANG_ADDON) // if not addon data language = LANG_UNIVERSAL; // whispers should always be readable + Player *rPlayer = objmgr.GetPlayer(receiver); + if(sWorld.getConfig(CONFIG_CHATLOG_WHISPER)) sLog.outChat("[WHISPER] Player %s tells %s: %s", GetName(), rPlayer->GetName(), text.c_str()); + // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode if(!rPlayer->isDND() || isGameMaster()) { WorldPacket data(SMSG_MESSAGECHAT, 200); BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language); rPlayer->GetSession()->SendPacket(&data); + data.Initialize(SMSG_MESSAGECHAT, 200); rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language); GetSession()->SendPacket(&data); @@ -14721,36 +17285,48 @@ void Player::Whisper(const std::string& text, uint32 language,uint64 receiver) // announce to player that player he is whispering to is dnd and cannot receive his message ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str()); } + if(!isAcceptWhispers() && !isGameMaster() && !rPlayer->isGameMaster()) { SetAcceptWhispers(true); ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON); } + // announce to player that player he is whispering to is afk if(rPlayer->isAFK()) ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str()); + // if player whisper someone, auto turn of dnd to be able to receive an answer if(isDND() && !rPlayer->isGameMaster()) ToggleDND(); } + void Player::PetSpellInitialize() { Pet* pet = GetPet(); + if(!pet) return; + sLog.outDebug("Pet Spells Groups"); + CharmInfo *charmInfo = pet->GetCharmInfo(); + WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1); data << uint64(pet->GetGUID()); data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents) data << uint32(0); data << uint8(pet->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0); + // action bar loop charmInfo->BuildActionBar(&data); + size_t spellsCountPos = data.wpos(); + // spells count uint8 addlist = 0; data << uint8(addlist); // placeholder + if (pet->IsPermanentPetFor(this)) { // spells loop @@ -14758,72 +17334,94 @@ void Player::PetSpellInitialize() { if(itr->second.state == PETSPELL_REMOVED) continue; + data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active)); ++addlist; } } + data.put<uint8>(spellsCountPos, addlist); + uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size(); data << uint8(cooldownsCount); + time_t curTime = time(NULL); + for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr) { time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0; + data << uint32(itr->first); // spellid data << uint16(0); // spell category? data << uint32(cooldown); // cooldown data << uint32(0); // category cooldown } + for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr) { time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0; + data << uint32(itr->first); // spellid data << uint16(0); // spell category? data << uint32(0); // cooldown data << uint32(cooldown); // category cooldown } + data.hexlike(); + GetSession()->SendPacket(&data); } + void Player::PossessSpellInitialize() { Unit* charm = GetCharm(); if(!charm) return; + CharmInfo *charmInfo = charm->GetCharmInfo(); + if(!charmInfo) { sLog.outError("Player::PossessSpellInitialize(): charm ("UI64FMTD") has no charminfo!", charm->GetGUID()); return; } + WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1); data << uint64(charm->GetGUID()); data << uint16(0); data << uint32(0); data << uint32(0); + charmInfo->BuildActionBar(&data); + data << uint8(0); // spells count data << uint8(0); // cooldowns count + GetSession()->SendPacket(&data); } + void Player::VehicleSpellInitialize() { Creature* veh = GetVehicleCreatureBase(); if(!veh) return; + WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*10+1+1); data << uint64(veh->GetGUID()); data << uint16(0); data << uint32(0); data << uint32(0x00000101); + for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i) { uint32 spellId = ((Creature*)veh)->m_spells[i]; if(!spellId) continue; + SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if(!spellInfo) continue; + if(IsPassiveSpell(spellId)) { veh->CastSpell(veh, spellId, true); @@ -14832,23 +17430,28 @@ void Player::VehicleSpellInitialize() else data << uint16(spellId) << uint8(0) << uint8(i+8); } + for(uint32 i = CREATURE_MAX_SPELLS; i < MAX_SPELL_CONTROL_BAR; ++i) data << uint16(0) << uint8(0) << uint8(i+8); + data << uint8(0); data << uint8(0); GetSession()->SendPacket(&data); } + void Player::CharmSpellInitialize() { Unit* charm = GetFirstControlled(); if(!charm) return; + CharmInfo *charmInfo = charm->GetCharmInfo(); if(!charmInfo) { sLog.outError("Player::CharmSpellInitialize(): the player's charm ("UI64FMTD") has no charminfo!", charm->GetGUID()); return; } + uint8 addlist = 0; if(charm->GetTypeId() != TYPEID_PLAYER) { @@ -14862,16 +17465,21 @@ void Player::CharmSpellInitialize() } } } + WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1); data << uint64(charm->GetGUID()); data << uint16(0); data << uint32(0); + if(charm->GetTypeId() != TYPEID_PLAYER) data << uint8(((Creature*)charm)->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0); else data << uint8(0) << uint8(0) << uint16(0); + charmInfo->BuildActionBar(&data); + data << uint8(addlist); + if(addlist) { for(uint32 i = 0; i < MAX_SPELL_CHARM; ++i) @@ -14881,33 +17489,42 @@ void Player::CharmSpellInitialize() data << uint32(cspell->packedData); } } + data << uint8(0); // cooldowns count + GetSession()->SendPacket(&data); } + void Player::SendRemoveControlBar() { WorldPacket data(SMSG_PET_SPELLS, 8); data << uint64(0); GetSession()->SendPacket(&data); } + bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell * spell) { if (!mod || !spellInfo) return false; + // Mod out of charges if (spell && mod->charges == -1 && spell->m_appliedMods.find(mod->ownerAura) == spell->m_appliedMods.end()) return false; + return spellmgr.IsAffectedByMod(spellInfo, mod); } + void Player::AddSpellMod(SpellModifier* mod, bool apply) { uint16 Opcode = (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER; + int i = 0; flag96 _mask = 0; for (int eff = 0; eff < 96; ++eff) { if (eff != 0 && eff%32 == 0) _mask[i++] = 0; + _mask[i] = uint32(1) << (eff-(32*i)); if (mod->mask & _mask) { @@ -14925,6 +17542,7 @@ void Player::AddSpellMod(SpellModifier* mod, bool apply) SendDirectMessage(&data); } } + if (apply) m_spellMods[mod->op].push_back(mod); else @@ -14933,44 +17551,54 @@ void Player::AddSpellMod(SpellModifier* mod, bool apply) delete mod; } } + // Restore spellmods in case of failed cast void Player::RestoreSpellMods(Spell * spell) { if (!spell || spell->m_appliedMods.empty()) return; + for(uint8 i=0;i<MAX_SPELLMOD;++i) { for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();++itr) { SpellModifier *mod = *itr; + // spellmods without aura set cannot be charged if (!mod->ownerAura || !mod->ownerAura->GetAuraCharges()) continue; + // check if mod affected this spell Spell::UsedSpellMods::iterator iterMod = spell->m_appliedMods.find(mod->ownerAura); if (iterMod == spell->m_appliedMods.end()) continue; + // remove from list spell->m_appliedMods.erase(iterMod); + // add mod charges back to mod if (mod->charges == -1) mod->charges = 1; else mod->charges++; + // Do not set more spellmods than avalible if (mod->ownerAura->GetAuraCharges() < mod->charges) mod->charges = mod->ownerAura->GetAuraCharges(); + // Skip this check for now - aura charges may change due to various reason // TODO: trac these changes correctly //assert (mod->ownerAura->GetAuraCharges() <= mod->charges); } } } + void Player::RemoveSpellMods(Spell * spell) { if (!spell) return; std::set <Aura *> checkedSpells; + AuraEffectList const & auraList = GetAurasByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE); for(AuraEffectList::const_iterator itr = auraList.begin(); itr != auraList.end();) { @@ -14978,10 +17606,13 @@ void Player::RemoveSpellMods(Spell * spell) ++itr; if (!aur->GetParentAura()->GetAuraCharges()) continue; + SpellEntry const * spellInfo = aur->GetSpellProto(); + if (spellInfo->SpellFamilyName != spell->m_spellInfo->SpellFamilyName || checkedSpells.find(aur->GetParentAura()) != checkedSpells.end()) continue; + if (spell->m_spellInfo->SpellFamilyFlags & spellInfo->EffectSpellClassMask[aur->GetEffIndex()] // this is for fingers of frost, look at spell::finish part, a charge will be taken by the triggering spell && aur->GetParentAura()->GetAuraDuration() != aur->GetParentAura()->GetAuraMaxDuration()) @@ -14992,28 +17623,35 @@ void Player::RemoveSpellMods(Spell * spell) itr = auraList.begin(); } } + if (spell->m_appliedMods.empty()) return; + for(uint8 i=0;i<MAX_SPELLMOD;++i) { for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();) { SpellModifier *mod = *itr; ++itr; + // spellmods without aura set cannot be charged if (!mod->ownerAura || !mod->ownerAura->GetAuraCharges()) continue; + // check if mod affected this spell Spell::UsedSpellMods::iterator iterMod = spell->m_appliedMods.find(mod->ownerAura); if (iterMod == spell->m_appliedMods.end()) continue; + // remove from list spell->m_appliedMods.erase(iterMod); + if (mod->ownerAura->DropAuraCharge()) itr = m_spellMods[i].begin(); } } } + void Player::DropModCharge(SpellModifier * mod, Spell * spell) { if (spell && mod->ownerAura && mod->charges > 0 ) @@ -15026,14 +17664,18 @@ void Player::DropModCharge(SpellModifier * mod, Spell * spell) spell->m_appliedMods.insert(mod->ownerAura); } } + void Player::SetSpellModTakingSpell(Spell * spell, bool apply) { if (!spell || (m_spellModTakingSpell && m_spellModTakingSpell != spell)) return; + if (apply && spell->getState() == SPELL_STATE_FINISHED) return; + m_spellModTakingSpell = apply ? spell : NULL; } + // send Proficiency void Player::SendProficiency(uint8 pr1, uint32 pr2) { @@ -15041,6 +17683,7 @@ void Player::SendProficiency(uint8 pr1, uint32 pr2) data << pr1 << pr2; GetSession()->SendPacket (&data); } + void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type) { QueryResult *result = NULL; @@ -15055,17 +17698,22 @@ void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type) Field *fields = result->Fetch(); uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER); uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM); + // send update if charter owner in game Player* owner = objmgr.GetPlayer(ownerguid); if(owner) owner->GetSession()->SendPetitionQueryOpcode(petitionguid); + } while ( result->NextRow() ); + delete result; + if(type==10) CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid)); else CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type); } + CharacterDatabase.BeginTransaction(); if(type == 10) { @@ -15079,11 +17727,13 @@ void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type) } CharacterDatabase.CommitTransaction(); } + void Player::LeaveAllArenaTeams(uint64 guid) { QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u'", GUID_LOPART(guid)); if(!result) return; + do { Field *fields = result->Fetch(); @@ -15095,50 +17745,63 @@ void Player::LeaveAllArenaTeams(uint64 guid) at->DelMember(guid); } } while (result->NextRow()); + delete result; } + void Player::SetRestBonus (float rest_bonus_new) { // Prevent resting on max level if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)) rest_bonus_new = 0; + if(rest_bonus_new < 0) rest_bonus_new = 0; + float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2; + if(rest_bonus_new > rest_bonus_max) m_rest_bonus = rest_bonus_max; else m_rest_bonus = rest_bonus_new; + // update data for client if(m_rest_bonus>10) SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested else if(m_rest_bonus<=1) SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal + //RestTickUpdate SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus)); } + void Player::HandleStealthedUnitsDetection() { std::list<Unit*> stealthedUnits; Trinity::AnyStealthedCheck u_check; Trinity::UnitListSearcher<Trinity::AnyStealthedCheck > searcher(this, stealthedUnits, u_check); VisitNearbyObject(GetMap()->GetVisibilityDistance(), searcher); + for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i) { if((*i)==this) continue; + bool hasAtClient = HaveAtClient((*i)); bool hasDetected = canSeeOrDetect(*i, true); + if (hasDetected) { if(!hasAtClient) { (*i)->SendUpdateToPlayer(this); m_clientGUIDs.insert((*i)->GetGUID()); + #ifdef MANGOS_DEBUG if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0) sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i)); #endif + // target aura duration for caster show only if target exist at caster client // send data at target visibility change (adding to client) SendInitialVisiblePackets(*i); @@ -15154,10 +17817,12 @@ void Player::HandleStealthedUnitsDetection() } } } + bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/) { if(nodes.size() < 2) return false; + // not let cheating with start flight in time of logout process || while in combat || has type state: stunned || has type state: root if(GetSession()->isLogingOut() || isInCombat() || hasUnitState(UNIT_STAT_STUNNED) || hasUnitState(UNIT_STAT_ROOT)) { @@ -15166,8 +17831,10 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc GetSession()->SendPacket(&data); return false; } + if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE)) return false; + // taximaster case if(npc) { @@ -15179,6 +17846,7 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc GetSession()->SendPacket(&data); return false; } + if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW ) { WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); @@ -15186,6 +17854,7 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc GetSession()->SendPacket(&data); return false; } + // not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi if(IsNonMeleeSpellCasted(false)) { @@ -15199,17 +17868,23 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc else { RemoveAurasByType(SPELL_AURA_MOUNTED); + if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW ) RemoveAurasDueToSpell(m_ShapeShiftFormSpellId); + if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL)) if (spell->m_spellInfo->Id != spellid) InterruptSpell(CURRENT_GENERIC_SPELL,false); + InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false); + if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL)) if (spell->m_spellInfo->Id != spellid) InterruptSpell(CURRENT_CHANNELED_SPELL,true); } + uint32 sourcenode = nodes[0]; + // starting node too far away (cheat?) TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode); if (!node) @@ -15219,6 +17894,7 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc GetSession()->SendPacket(&data); return false; } + // check node starting pos data set case if provided if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f) { @@ -15242,39 +17918,55 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc GetSession()->SendPacket(&data); return false; } + // Prepare to flight start now + // stop combat at start taxi flight if any CombatStop(); + StopCastingCharm(); StopCastingBindSight(); ExitVehicle(); + // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it) TradeCancel(true); + // clean not finished taxi path if any m_taxi.ClearTaxiDestinations(); + // 0 element current node m_taxi.AddTaxiDestination(sourcenode); + // fill destinations path tail uint32 sourcepath = 0; uint32 totalcost = 0; + uint32 prevnode = sourcenode; uint32 lastnode = 0; + for(uint32 i = 1; i < nodes.size(); ++i) { uint32 path, cost; + lastnode = nodes[i]; objmgr.GetTaxiPath(prevnode, lastnode, path, cost); + if(!path) { m_taxi.ClearTaxiDestinations(); return false; } + totalcost += cost; + if(prevnode == sourcenode) sourcepath = path; + m_taxi.AddTaxiDestination(lastnode); + prevnode = lastnode; } + // get mount model (in case non taximaster (npc==NULL) allow more wide lookup) // // Hack-Fix for Alliance not being able to use Acherus taxi. There is @@ -15282,6 +17974,7 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc // change but I couldn't find a suitable alternative. OK to use class because only DK // can use this taxi. uint32 mount_display_id = objmgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL || (sourcenode == 315 && getClass() == CLASS_DEATH_KNIGHT)); + // in spell case allow 0 model if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0) { @@ -15291,9 +17984,12 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc m_taxi.ClearTaxiDestinations(); return false; } + uint32 money = GetMoney(); + if (npc) totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc)); + if(money < totalcost) { WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); @@ -15302,12 +17998,15 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc m_taxi.ClearTaxiDestinations(); return false; } + //Checks and preparations done, DO FLIGHT ModifyMoney(-(int32)totalcost); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1); + // prevent stealth flight //RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK); + if (sWorld.getConfig(CONFIG_INSTANT_TAXI)) { TaxiNodesEntry const* lastnode = sTaxiNodesStore.LookupEntry(nodes[nodes.size()-1]); @@ -15325,17 +18024,22 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc } return true; } + bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ ) { TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id); if(!entry) return false; + std::vector<uint32> nodes; + nodes.resize(2); nodes[0] = entry->from; nodes[1] = entry->to; + return ActivateTaxiPathTo(nodes,NULL,spellid); } + void Player::CleanupAfterTaxiFlight() { m_taxi.ClearTaxiDestinations(); // not destinations, clear source node @@ -15343,46 +18047,60 @@ void Player::CleanupAfterTaxiFlight() RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT); getHostilRefManager().setOnlineOfflineState(true); } + void Player::ContinueTaxiFlight() { uint32 sourceNode = m_taxi.GetTaxiSource(); if (!sourceNode) return; + sLog.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() ); + uint32 mountDisplayId = objmgr.GetTaxiMountDisplayId(sourceNode, GetTeam(),true); uint32 path = m_taxi.GetCurrentTaxiPath(); + // search appropriate start path node uint32 startNode = 0; + TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path]; + float distPrev = MAP_SIZE*MAP_SIZE; float distNext = (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+ (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+ (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ()); + for(uint32 i = 1; i < nodeList.size(); ++i) { TaxiPathNode const& node = nodeList[i]; TaxiPathNode const& prevNode = nodeList[i-1]; + // skip nodes at another map if(node.mapid != GetMapId()) continue; + distPrev = distNext; + distNext = (node.x-GetPositionX())*(node.x-GetPositionX())+ (node.y-GetPositionY())*(node.y-GetPositionY())+ (node.z-GetPositionZ())*(node.z-GetPositionZ()); + float distNodes = (node.x-prevNode.x)*(node.x-prevNode.x)+ (node.y-prevNode.y)*(node.y-prevNode.y)+ (node.z-prevNode.z)*(node.z-prevNode.z); + if(distNext + distPrev < distNodes) { startNode = i; break; } } + GetSession()->SendDoFlight(mountDisplayId, path, startNode); } + void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs ) { // last check 2.0.10 @@ -15401,11 +18119,14 @@ void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs ) ASSERT(spellInfo); continue; } + // Not send cooldown for this spells if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) continue; + if(spellInfo->PreventionType != SPELL_PREVENTION_TYPE_SILENCE) continue; + if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs ) { data << uint32(unSpellId); @@ -15415,6 +18136,7 @@ void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs ) } GetSession()->SendPacket(&data); } + void Player::InitDataForForm(bool reapplyMods) { SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form); @@ -15426,6 +18148,7 @@ void Player::InitDataForForm(bool reapplyMods) } else SetRegularAttackTime(); + switch(m_form) { case FORM_GHOUL: @@ -15450,12 +18173,15 @@ void Player::InitDataForForm(bool reapplyMods) break; } } + // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change. if (!reapplyMods) UpdateEquipSpellsAtFormChange(); + UpdateAttackPowerAndDamage(); UpdateAttackPowerAndDamage(true); } + void Player::InitDisplayIds() { PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass()); @@ -15464,6 +18190,7 @@ void Player::InitDisplayIds() sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow()); return; } + uint8 gender = getGender(); switch(gender) { @@ -15480,22 +18207,27 @@ void Player::InitDisplayIds() return; } } + // Return true is the bought item has a max count to force refresh of window by caller bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot) { // cheating attempt if (count < 1) count = 1; + // cheating attempt if(slot > MAX_BAG_SIZE && slot !=NULL_SLOT) return false; + if (!isAlive()) return false; + ItemPrototype const *pProto = objmgr.GetItemPrototype( item ); if (!pProto) { SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0); return false; } + Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR); if (!pCreature) { @@ -15503,19 +18235,23 @@ bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0); return false; } + VendorItemData const* vItems = pCreature->GetVendorItems(); if(!vItems || vItems->Empty()) { SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0); return false; } + size_t vendor_slot = vItems->FindItemSlot(item); if (vendor_slot >= vItems->GetItemCount()) { SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0); return false; } + VendorItem const* crItem = vItems->m_items[vendor_slot]; + // check current item amount if it limited if (crItem->maxcount != 0) { @@ -15525,6 +18261,7 @@ bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint return false; } } + if (pProto->RequiredReputationFaction && (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)) { SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0); @@ -15538,6 +18275,7 @@ bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint return false; } } + if (crItem->ExtendedCost) { ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost); @@ -15546,18 +18284,21 @@ bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost); return false; } + // honor points price if (GetHonorPoints() < (iece->reqhonorpoints * count)) { SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL); return false; } + // arena points price if (GetArenaPoints() < (iece->reqarenapoints * count)) { SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL); return false; } + // item base price for (uint8 i = 0; i < 5; ++i) { @@ -15567,6 +18308,7 @@ bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint return false; } } + // check for personal arena rating requirement if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating ) { @@ -15575,14 +18317,18 @@ bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint return false; } } + uint32 price = pProto->BuyPrice * count; + // reputation discount price = uint32(floor(price * GetReputationPriceDiscount(pCreature))); + if (GetMoney() < price) { SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0); return false; } + if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot)) { ItemPosCountVec dest; @@ -15592,6 +18338,7 @@ bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint SendEquipError( msg, NULL, NULL ); return false; } + ModifyMoney( -(int32)price ); if (crItem->ExtendedCost) // case for new honor system { @@ -15606,15 +18353,18 @@ bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true); } } + if (Item *it = StoreNewItem( dest, item, true )) { uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count); + WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4)); data << pCreature->GetGUID(); data << (uint32)(vendor_slot+1); // numbered from 1 at client data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF); data << (uint32)count; GetSession()->SendPacket(&data); + SendNewItem(it, pProto->BuyCount*count, true, false, false); } } @@ -15625,6 +18375,7 @@ bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL ); return false; } + uint16 dest; uint8 msg = CanEquipNewItem( slot, dest, item, false ); if (msg != EQUIP_ERR_OK) @@ -15632,6 +18383,7 @@ bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint SendEquipError( msg, NULL, NULL ); return false; } + ModifyMoney( -(int32)price ); if (crItem->ExtendedCost) // case for new honor system { @@ -15646,16 +18398,20 @@ bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true); } } + if (Item *it = EquipNewItem( dest, item, true )) { uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count); + WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4)); data << pCreature->GetGUID(); data << (uint32)(vendor_slot+1); // numbered from 1 at client data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF); data << (uint32)count; GetSession()->SendPacket(&data); + SendNewItem(it, pProto->BuyCount*count, true, false, false); + AutoUnequipOffhandIfNeed(); } } @@ -15664,8 +18420,10 @@ bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL ); return false; } + return crItem->maxcount != 0; } + uint32 Player::GetMaxPersonalArenaRatingRequirement() { // returns the maximal personal arena rating that can be used to purchase items requiring this condition @@ -15685,6 +18443,7 @@ uint32 Player::GetMaxPersonalArenaRatingRequirement() } return max_personal_rating; } + void Player::UpdateHomebindTime(uint32 time) { // GMs never get homebind timer online @@ -15723,6 +18482,7 @@ void Player::UpdateHomebindTime(uint32 time) sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow()); } } + void Player::UpdatePvPState(bool onlyFFA) { // TODO: should we always synchronize UNIT_FIELD_BYTES_2, 1 of controller and controlled? @@ -15742,8 +18502,10 @@ void Player::UpdatePvPState(bool onlyFFA) for(ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) (*itr)->RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP); } + if(onlyFFA) return; + if(pvpInfo.inHostileArea) // in hostile area { if(!IsPvP() || pvpInfo.endTimer != 0) @@ -15755,6 +18517,7 @@ void Player::UpdatePvPState(bool onlyFFA) pvpInfo.endTimer = time(0); // start toggle-off } } + void Player::UpdatePvP(bool state, bool override) { if(!state || override) @@ -15770,15 +18533,18 @@ void Player::UpdatePvP(bool state, bool override) SetPvP(state); } } + void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown) { // init cooldown values uint32 cat = 0; int32 rec = -1; int32 catrec = -1; + // some special item spells without correct cooldown in SpellInfo // cooldown information stored in item prototype // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client. + if(itemId) { if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId)) @@ -15795,6 +18561,7 @@ void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 it } } } + // if no cooldown found above then base at DBC data if(rec < 0 && catrec < 0) { @@ -15802,9 +18569,12 @@ void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 it rec = spellInfo->RecoveryTime; catrec = spellInfo->CategoryRecoveryTime; } + time_t curTime = time(NULL); + time_t catrecTime; time_t recTime; + // overwrite time for selected category if(infinityCooldown) { @@ -15819,23 +18589,30 @@ void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 it // prevent 0 cooldowns set by another way if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT)) rec = GetAttackTime(RANGED_ATTACK); + // Now we have cooldown data (if found any), time to apply mods if(rec > 0) ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell); + if(catrec > 0) ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell); + // replace negative cooldowns by 0 if (rec < 0) rec = 0; if (catrec < 0) catrec = 0; + // no cooldown after applying spell mods if( rec == 0 && catrec == 0) return; + catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0; recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime; } + // self spell cooldown if(recTime > 0) AddSpellCooldown(spellInfo->Id, itemId, recTime); + // category spells if (cat && catrec > 0) { @@ -15846,11 +18623,13 @@ void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 it { if(*i_scset == spellInfo->Id) // skip main spell, already handled above continue; + AddSpellCooldown(*i_scset, itemId, catrecTime); } } } } + void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time) { SpellCooldown sc; @@ -15858,21 +18637,25 @@ void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time) sc.itemid = itemid; m_spellCooldowns[spellid] = sc; } + void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell) { // start cooldowns at server side, if any AddSpellAndCategoryCooldowns(spellInfo,itemId,spell); + // Send activate cooldown timer (possible 0) at client side WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8)); data << spellInfo->Id; data << GetGUID(); SendDirectMessage(&data); } + void Player::UpdatePotionCooldown(Spell* spell) { // no potion used i combat or still in combat if(!m_lastPotionId || isInCombat()) return; + // Call not from spell cast, send cooldown event for item spells if no in combat if(!spell) { @@ -15886,17 +18669,23 @@ void Player::UpdatePotionCooldown(Spell* spell) // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown) else SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell); + m_lastPotionId = 0; } + //slot to be excluded while counting bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) { if(!enchantmentcondition) return true; + SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition); + if(!Condition) return true; + uint8 curcount[4] = {0, 0, 0, 0}; + //counting current equipped gem colors for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { @@ -15910,19 +18699,25 @@ bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if(!enchant_id) continue; + SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if(!enchantEntry) continue; + uint32 gemid = enchantEntry->GemID; if(!gemid) continue; + ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid); if(!gemProto) continue; + GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties); if(!gemProperty) continue; + uint8 GemColor = gemProperty->color; + for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1) { if(tmpcolormask & GemColor) @@ -15931,14 +18726,19 @@ bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) } } } + bool activate = true; + for(uint8 i = 0; i < 5; i++) { if(!Condition->Color[i]) continue; + uint32 _cur_gem = curcount[Condition->Color[i] - 1]; + // if have <CompareColor> use them as count, else use <value> from Condition uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i]; + switch(Condition->Comparator[i]) { case 2: // requires less <color> than (<value> || <comparecolor>) gems @@ -15952,9 +18752,12 @@ bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) break; } } + sLog.outDebug("Checking Condition %u, there are %u Meta Gems, %u Red Gems, %u Yellow Gems and %u Blue Gems, Activate:%s", enchantmentcondition, curcount[0], curcount[1], curcount[2], curcount[3], activate ? "yes" : "no"); + return activate; } + void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply) { //cycle all equipped items @@ -15963,17 +18766,22 @@ void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply) //enchants for the slot being socketed are handled by Player::ApplyItemMods if(slot == exceptslot) continue; + Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ); + if(!pItem || !pItem->GetProto()->Socket[0].Color) continue; + for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if(!enchant_id) continue; + SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if(!enchantEntry) continue; + uint32 condition = enchantEntry->EnchantmentCondition; if(condition) { @@ -15990,6 +18798,7 @@ void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply) } } } + //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply) { @@ -15999,18 +18808,23 @@ void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply) //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data) if(slot == exceptslot) continue; + Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ); + if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item continue; + //cycle all (gem)enchants for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if(!enchant_id) //if no enchant go to next enchant(slot) continue; + SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if(!enchantEntry) continue; + //only metagems to be (de)activated, so only enchants with condition uint32 condition = enchantEntry->EnchantmentCondition; if(condition) @@ -16018,6 +18832,7 @@ void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply) } } } + void Player::SetBattleGroundEntryPoint() { // Taxi path store @@ -16026,6 +18841,7 @@ void Player::SetBattleGroundEntryPoint() m_bgData.mountSpell = 0; m_bgData.taxiPath[0] = m_taxi.GetTaxiSource(); m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination(); + // On taxi we don't need check for dungeon m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); return; @@ -16033,6 +18849,7 @@ void Player::SetBattleGroundEntryPoint() else { m_bgData.ClearTaxiPath(); + // Mount spell id storing if (IsMounted()) { @@ -16042,6 +18859,7 @@ void Player::SetBattleGroundEntryPoint() } else m_bgData.mountSpell = 0; + // If map is dungeon find linked graveyard if(GetMap()->IsDungeon()) { @@ -16060,14 +18878,17 @@ void Player::SetBattleGroundEntryPoint() return; } } + // In error cases use homebind position m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f); } + void Player::LeaveBattleground(bool teleportToEntryPoint) { if(BattleGround *bg = GetBattleGround()) { bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true); + // call after remove to be sure that player resurrected for correct cast if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) ) { @@ -16079,31 +18900,38 @@ void Player::LeaveBattleground(bool teleportToEntryPoint) ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER); return; } + CastSpell(this, SPELL_ID_DESERTER, true); // Deserter } } } } + bool Player::CanJoinToBattleground() const { // check Deserter debuff if(HasAura(SPELL_ID_DESERTER)) return false; + return true; } + bool Player::CanReportAfkDueToLimit() { // a player can complain about 15 people per 5 minutes if(m_bgData.bgAfkReportedCount++ >= 15) return false; + return true; } + ///This player has been blamed to be inactive in a battleground void Player::ReportedAfkBy(Player* reporter) { BattleGround *bg = GetBattleGround(); if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam()) return; + // check if player has 'Idle' or 'Inactive' debuff if(m_bgData.bgAfkReporter.find(reporter->GetGUIDLow())==m_bgData.bgAfkReporter.end() && !HasAura(43680) && !HasAura(43681) && reporter->CanReportAfkDueToLimit()) { @@ -16117,6 +18945,7 @@ void Player::ReportedAfkBy(Player* reporter) } } } + WorldLocation Player::GetStartPosition() const { PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass()); @@ -16125,14 +18954,17 @@ WorldLocation Player::GetStartPosition() const mapId = 0; return WorldLocation(mapId, info->positionX, info->positionY, info->positionZ, 0); } + bool Player::canSeeOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const { // Always can see self if (m_mover == u || this == u) return true; + // phased visibility (both must phased in same way) if(!InSamePhase(u)) return false; + // player visible for other player if not logout and at same transport // including case when player is out of world bool at_same_transport = @@ -16140,24 +18972,30 @@ bool Player::canSeeOrDetect(Unit const* u, bool detect, bool inVisibleList, bool && !GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() && !GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() && GetTransport() == ((Player*)u)->GetTransport(); + // not in world if(!at_same_transport && (!IsInWorld() || !u->IsInWorld())) return false; + // forbidden to seen (at GM respawn command) //if(u->GetVisibility() == VISIBILITY_RESPAWN) // return false; + Map& _map = *u->GetMap(); // Grid dead/alive checks // non visible at grid for any stealth state if(!u->IsVisibleInGridForPlayer(this)) return false; + // always seen by owner if(uint64 guid = u->GetCharmerOrOwnerGUID()) if(GetGUID() == guid) return true; + if(uint64 guid = GetUInt64Value(PLAYER_FARSIGHT)) if(u->GetGUID() == guid) return true; + // different visible distance checks if(isInFlight()) // what see player in flight { @@ -16190,6 +19028,7 @@ bool Player::canSeeOrDetect(Unit const* u, bool detect, bool inVisibleList, bool , is3dDistance)) return false; } + if(u->GetVisibility() == VISIBILITY_OFF) { // GMs see any players, not higher GMs and all units @@ -16202,6 +19041,7 @@ bool Player::canSeeOrDetect(Unit const* u, bool detect, bool inVisibleList, bool } return false; } + // GM's can see everyone with invisibilitymask with less or equal security level if(m_mover->m_invisibilityMask || u->m_invisibilityMask) { @@ -16212,11 +19052,13 @@ bool Player::canSeeOrDetect(Unit const* u, bool detect, bool inVisibleList, bool else return true; } + // player see other player with stealth/invisibility only if he in same group or raid or same team (raid/team case dependent from conf setting) if(!m_mover->canDetectInvisibilityOf(u)) if(!(u->GetTypeId()==TYPEID_PLAYER && !IsHostileTo(u) && IsGroupVisibleFor(((Player*)u)))) return false; } + // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible if(u->GetVisibility() == VISIBILITY_GROUP_STEALTH && !isGameMaster()) { @@ -16230,16 +19072,19 @@ bool Player::canSeeOrDetect(Unit const* u, bool detect, bool inVisibleList, bool if(!detect || !m_mover->canDetectStealthOf(u, GetDistance(u))) return false; } + // If use this server will be too laggy // Now check is target visible with LoS //return u->IsWithinLOS(GetPositionX(),GetPositionY(),GetPositionZ()); return true; } + bool Player::IsVisibleInGridForPlayer( Player const * pl ) const { // gamemaster in GM mode see all, including ghosts if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity()) return true; + // It seems in battleground everyone sees everyone, except the enemy-faction ghosts if (InBattleGround()) { @@ -16247,14 +19092,17 @@ bool Player::IsVisibleInGridForPlayer( Player const * pl ) const return false; return true; } + // Live player see live player or dead player with not realized corpse if(pl->isAlive() || pl->m_deathTimer > 0) { return isAlive() || m_deathTimer > 0; } + // Ghost see other friendly ghosts, that's for sure if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl)) return true; + // Dead player see live players near own corpse if(isAlive()) { @@ -16266,39 +19114,49 @@ bool Player::IsVisibleInGridForPlayer( Player const * pl ) const return true; } } + // and not see any other return false; } + bool Player::IsVisibleGloballyFor( Player* u ) const { if(!u) return false; + // Always can see self if (u==this) return true; + // Visible units, always are visible for all players if (GetVisibility() == VISIBILITY_ON) return true; + // GMs are visible for higher gms (or players are visible for gms) if (u->GetSession()->GetSecurity() > SEC_PLAYER) return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity(); + // non faction visibility non-breakable for non-GMs if (GetVisibility() == VISIBILITY_OFF) return false; + // non-gm stealth/invisibility not hide from global player lists return true; } + template<class T> inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target) { s64.insert(target->GetGUID()); } + template<> inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target) { if(!target->IsTransport()) s64.insert(target->GetGUID()); } + void Player::UpdateVisibilityOf(WorldObject* target) { if(HaveAtClient(target)) @@ -16307,6 +19165,7 @@ void Player::UpdateVisibilityOf(WorldObject* target) { target->DestroyForPlayer(this); m_clientGUIDs.erase(target->GetGUID()); + #ifdef TRINITY_DEBUG if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0) sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target)); @@ -16319,12 +19178,15 @@ void Player::UpdateVisibilityOf(WorldObject* target) { //if(target->isType(TYPEMASK_UNIT) && ((Unit*)target)->m_Vehicle) // UpdateVisibilityOf(((Unit*)target)->m_Vehicle); + target->SendUpdateToPlayer(this); UpdateVisibilityOf_helper(m_clientGUIDs, target); + #ifdef TRINITY_DEBUG if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0) sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target)); #endif + // target aura duration for caster show only if target exist at caster client // send data at target visibility change (adding to client) if(target->isType(TYPEMASK_UNIT)) @@ -16332,6 +19194,7 @@ void Player::UpdateVisibilityOf(WorldObject* target) } } } + void Player::SendInitialVisiblePackets(Unit* target) { SendAurasForTarget(target); @@ -16343,6 +19206,7 @@ void Player::SendInitialVisiblePackets(Unit* target) target->SendMeleeAttackStart(target->getVictim()); } } + template<class T> void Player::UpdateVisibilityOf(T* target, UpdateData& data, std::set<WorldObject*>& visibleNow) { @@ -16352,6 +19216,7 @@ void Player::UpdateVisibilityOf(T* target, UpdateData& data, std::set<WorldObjec { target->BuildOutOfRangeUpdateBlock(&data); m_clientGUIDs.erase(target->GetGUID()); + #ifdef TRINITY_DEBUG if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0) sLog.outDebug("Object %u (Type: %u, Entry: %u) is out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),target->GetEntry(),GetGUIDLow(),GetDistance(target)); @@ -16364,9 +19229,11 @@ void Player::UpdateVisibilityOf(T* target, UpdateData& data, std::set<WorldObjec { //if(target->isType(TYPEMASK_UNIT) && ((Unit*)target)->m_Vehicle) // UpdateVisibilityOf(((Unit*)target)->m_Vehicle, data, visibleNow); + visibleNow.insert(target); target->BuildCreateUpdateBlockForPlayer(&data, this); UpdateVisibilityOf_helper(m_clientGUIDs,target); + #ifdef TRINITY_DEBUG if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0) sLog.outDebug("Object %u (Type: %u, Entry: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),target->GetEntry(),GetGUIDLow(),GetDistance(target)); @@ -16374,27 +19241,32 @@ void Player::UpdateVisibilityOf(T* target, UpdateData& data, std::set<WorldObjec } } } + template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, std::set<WorldObject*>& visibleNow); template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, std::set<WorldObject*>& visibleNow); template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, std::set<WorldObject*>& visibleNow); template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, std::set<WorldObject*>& visibleNow); template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, std::set<WorldObject*>& visibleNow); + void Player::InitPrimaryProfessions() { SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL)); } + Unit * Player::GetSelectedUnit() const { if(m_curSelection) return ObjectAccessor::GetUnit(*this, m_curSelection); return NULL; } + Player * Player::GetSelectedPlayer() const { if(m_curSelection) return ObjectAccessor::GetPlayer(*this, m_curSelection); return NULL; } + void Player::SendComboPoints() { Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget); @@ -16413,13 +19285,17 @@ void Player::SendComboPoints() GetSession()->SendPacket(&data); } } + void Player::AddComboPoints(Unit* target, int8 count, Spell * spell) { if(!count) return; + int8 * comboPoints = spell ? &spell->m_comboPointGain : &m_comboPoints; + // without combo points lost (duration checked in aura) RemoveAurasByType(SPELL_AURA_RETAIN_COMBO_POINTS); + if(target->GetGUID() == m_comboTarget) { *comboPoints += count; @@ -16429,36 +19305,50 @@ void Player::AddComboPoints(Unit* target, int8 count, Spell * spell) if(m_comboTarget) if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget)) target2->RemoveComboPointHolder(GetGUIDLow()); + m_comboTarget = target->GetGUID(); *comboPoints = count; + target->AddComboPointHolder(GetGUIDLow()); } + if (*comboPoints > 5) *comboPoints = 5; else if (*comboPoints < 0) *comboPoints = 0; + if (!spell) SendComboPoints(); } + void Player::GainSpellComboPoints(int8 count) { if(!count) return; + m_comboPoints += count; if (m_comboPoints > 5) m_comboPoints = 5; else if (m_comboPoints < 0) m_comboPoints = 0; + SendComboPoints(); } + void Player::ClearComboPoints() { if(!m_comboTarget) return; + // without combopoints lost (duration checked in aura) RemoveAurasByType(SPELL_AURA_RETAIN_COMBO_POINTS); + m_comboPoints = 0; + SendComboPoints(); + if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget)) target->RemoveComboPointHolder(GetGUIDLow()); + m_comboTarget = 0; } + void Player::SetGroup(Group *group, int8 subgroup) { if(group == NULL) @@ -16471,45 +19361,58 @@ void Player::SetGroup(Group *group, int8 subgroup) m_group.setSubGroup((uint8)subgroup); } } + void Player::SendInitialPacketsBeforeAddToMap() { WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4); data << uint32(0); // unknown, may be rest state time or experience GetSession()->SendPacket(&data); + GetSocial()->SendSocialList(); + // Homebind data.Initialize(SMSG_BINDPOINTUPDATE, 5*4); data << m_homebindX << m_homebindY << m_homebindZ; data << (uint32) m_homebindMapId; data << (uint32) m_homebindZoneId; GetSession()->SendPacket(&data); + // SMSG_SET_PROFICIENCY // SMSG_UPDATE_AURA_DURATION + SendTalentsInfoData(false); SendInitialSpells(); + data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4); data << uint32(0); // count, for(count) uint32; GetSession()->SendPacket(&data); + SendInitialActionButtons(); m_reputationMgr.SendInitialReputations(); m_achievementMgr.SendAllAchievementData(); + SendEquipmentSetList(); + data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4); data << uint32(secsToTimeBitFields(sWorld.GetGameTime())); data << (float)0.01666667f; // game speed data << uint32(0); // added in 3.1.2 GetSession()->SendPacket( &data ); } + void Player::SendInitialPacketsAfterAddToMap() { // update zone uint32 newzone, newarea; GetZoneAndAreaId(newzone,newarea); UpdateZone(newzone,newarea); // also call SendInitWorldStates(); + WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement data << uint32(0x00000000); // on blizz it increments periodically GetSession()->SendPacket(&data); + CastSpell(this, SPELL_ID_LOGINEFFECT, true); // LOGINEFFECT + // set some aura effects that send packet to player client after add player to map // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply // same auras state lost at far teleport, send it one more time in this case also @@ -16525,8 +19428,10 @@ void Player::SendInitialPacketsAfterAddToMap() if(!auraList.empty()) auraList.front()->ApplyModifier(true,true); } + if(HasAuraType(SPELL_AURA_MOD_STUN)) SetMovement(MOVE_ROOT); + // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied. if(HasAuraType(SPELL_AURA_MOD_ROOT)) { @@ -16535,21 +19440,25 @@ void Player::SendInitialPacketsAfterAddToMap() data2 << (uint32)2; SendMessageToSet(&data2,true); } + SendAurasForTarget(this); SendEnchantmentDurations(); // must be after add to map SendItemDurations(); // must be after add to map } + void Player::SendUpdateToOutOfRangeGroupMembers() { if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE) return; if(Group* group = GetGroup()) group->UpdatePlayerOutOfRange(this); + m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE; m_auraRaidUpdateMask = 0; if(Pet *pet = GetPet()) pet->ResetAuraUpdateMaskForRaid(); } + void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg) { WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2); @@ -16565,6 +19474,7 @@ void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg) } GetSession()->SendPacket(&data); } + void Player::SendInstanceResetWarning( uint32 mapid, uint32 difficulty, uint32 time ) { // type of warning, based on the time remaining until reset @@ -16577,6 +19487,7 @@ void Player::SendInstanceResetWarning( uint32 mapid, uint32 difficulty, uint32 t type = RAID_INSTANCE_WARNING_MIN; else type = RAID_INSTANCE_WARNING_MIN_SOON; + WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4); data << uint32(type); data << uint32(mapid); @@ -16589,33 +19500,42 @@ void Player::SendInstanceResetWarning( uint32 mapid, uint32 difficulty, uint32 t } GetSession()->SendPacket(&data); } + void Player::ApplyEquipCooldown( Item * pItem ) { for(uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) { _Spell const& spellData = pItem->GetProto()->Spells[i]; + // no spell if( !spellData.SpellId ) continue; + // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown) if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE ) continue; + AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30); + WorldPacket data(SMSG_ITEM_COOLDOWN, 12); data << pItem->GetGUID(); data << uint32(spellData.SpellId); GetSession()->SendPacket(&data); } } + void Player::resetSpells(bool myClassOnly) { // not need after this call if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS)) RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true); + // make full copy of map (spells removed and marked as deleted at another spell remove // and we can't use original map for safe iterative with visit each spell at loop end PlayerSpellMap smap = GetSpellMap(); + uint32 family; + if(myClassOnly) { ChrClassesEntry const* clsEntry = sChrClassesStore.LookupEntry(getClass()); @@ -16623,6 +19543,7 @@ void Player::resetSpells(bool myClassOnly) return; family = clsEntry->spellfamily; } + for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter) { if(myClassOnly) @@ -16630,28 +19551,35 @@ void Player::resetSpells(bool myClassOnly) SpellEntry const *spellInfo = sSpellStore.LookupEntry(iter->first); if(!spellInfo) continue; + // skip server-side/triggered spells if(spellInfo->spellLevel == 0) continue; + // skip wrong class/race skills if(!IsSpellFitByClassAndRace(spellInfo->Id)) continue; + // skip other spell families if(spellInfo->SpellFamilyName != family) continue; + // skip spells with first rank learned as talent (and all talents then also) uint32 first_rank = spellmgr.GetFirstSpellInChain(spellInfo->Id); if(GetTalentSpellCost(first_rank) > 0) continue; + // skip broken spells if(!SpellMgr::IsSpellValid(spellInfo,this,false)) continue; } removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already } + learnDefaultSpells(); learnQuestRewardedSpells(); } + void Player::learnDefaultSpells() { // learn default race/class spells @@ -16666,15 +19594,19 @@ void Player::learnDefaultSpells() learnSpell(tspell,true); } } + void Player::learnQuestRewardedSpells(Quest const* quest) { uint32 spell_id = quest->GetRewSpellCast(); + // skip quests without rewarded spell if( !spell_id ) return; + SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id); if(!spellInfo) return; + // check learned spells state bool found = false; for(uint8 i=0; i < 3; ++i) @@ -16685,9 +19617,11 @@ void Player::learnQuestRewardedSpells(Quest const* quest) break; } } + // skip quests with not teaching spell or already known spell if(!found) return; + // prevent learn non first rank unknown profession and second specialization for same profession) uint32 learned_0 = spellInfo->EffectTriggerSpell[0]; if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) ) @@ -16696,10 +19630,13 @@ void Player::learnQuestRewardedSpells(Quest const* quest) uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0); if( !HasSpell(first_spell) ) return; + SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0); if(!learnedInfo) return; + uint32 profSpell = spellmgr.GetSpellRequired(learned_0); + // specialization if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0 && profSpell) { @@ -16708,20 +19645,25 @@ void Player::learnQuestRewardedSpells(Quest const* quest) { if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0) continue; + SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first); if(!itrInfo) return; + // compare only specializations if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0) continue; + // compare same chain spells if (spellmgr.GetSpellRequired(itr->first) == profSpell) return; } } } + CastSpell( this, spell_id, true); } + void Player::learnQuestRewardedSpells() { // learn spells received from quest completing @@ -16730,12 +19672,15 @@ void Player::learnQuestRewardedSpells() // skip no rewarded quests if(!itr->second.m_rewarded) continue; + Quest const* quest = objmgr.GetQuestTemplate(itr->first); if( !quest ) continue; + learnQuestRewardedSpells(quest); } } + void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value ) { uint32 raceMask = getRaceMask(); @@ -16751,6 +19696,7 @@ void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value ) // Check class if set if (pAbility->classmask && !(pAbility->classmask & classMask)) continue; + if (sSpellStore.LookupEntry(pAbility->spellId)) { // need unlearn spell @@ -16764,24 +19710,29 @@ void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value ) } } } + void Player::SendAurasForTarget(Unit *target) { if(!target || target->GetVisibleAuras()->empty()) // speedup things return; + WorldPacket data(SMSG_AURA_UPDATE_ALL); data.append(target->GetPackGUID()); + Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras(); for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr) { Aura * aura=itr->second; data << uint8(aura->GetAuraSlot()); data << uint32(aura->GetId()); + // flags data << aura->m_auraFlags; // level data << aura->m_auraLevel; // charges data << uint8(aura->GetStackAmount()>1 ? aura->GetStackAmount() : aura->GetAuraCharges()); + if(!(aura->m_auraFlags & AFLAG_CASTER)) { if (Unit * caster = aura->GetCaster()) @@ -16789,14 +19740,17 @@ void Player::SendAurasForTarget(Unit *target) else data << uint8(0); } + if(aura->m_auraFlags & AFLAG_DURATION) // include aura duration { data << uint32(aura->GetAuraMaxDuration()); data << uint32(aura->GetAuraDuration()); } } + GetSession()->SendPacket(&data); } + void Player::SetDailyQuestStatus( uint32 quest_id ) { for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) @@ -16810,43 +19764,54 @@ void Player::SetDailyQuestStatus( uint32 quest_id ) } } } + void Player::ResetDailyQuestStatus() { for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0); + // DB data deleted in caller m_DailyQuestChanged = false; m_lastDailyQuestTime = 0; } + BattleGround* Player::GetBattleGround() const { if(GetBattleGroundId()==0) return NULL; + return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID); } + bool Player::InArena() const { BattleGround *bg = GetBattleGround(); if(!bg || !bg->isArena()) return false; + return true; } + bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const { // get a template bg instead of running one BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId); if(!bg) return false; + if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel()) return false; + return true; } + BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const { //returned to hardcoded version of this function, because there is no way to code it dynamic uint32 level = getLevel(); if( bgTypeId == BATTLEGROUND_AV ) level--; + uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80 if( queue_id >= MAX_BATTLEGROUND_QUEUES ) { @@ -16855,35 +19820,45 @@ BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId } return BGQueueIdBasedOnLevel(queue_id); } + float Player::GetReputationPriceDiscount( Creature const* pCreature ) const { FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry(); if(!vendor_faction || !vendor_faction->faction) return 1.0f; + ReputationRank rank = GetReputationRank(vendor_faction->faction); if(rank <= REP_NEUTRAL) return 1.0f; + return 1.0f - 0.05f* (rank - REP_NEUTRAL); } + bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const { uint32 racemask = getRaceMask(); uint32 classmask = getClassMask(); + SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id); if (bounds.first==bounds.second) return true; + for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx) { // skip wrong race skills if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0) continue; + // skip wrong class skills if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0) continue; + return true; } + return false; } + bool Player::HasQuestForGO(int32 GOId) const { for( uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i ) @@ -16891,21 +19866,27 @@ bool Player::HasQuestForGO(int32 GOId) const uint32 questid = GetQuestSlotQuestId(i); if ( questid == 0 ) continue; + QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid); if(qs_itr == mQuestStatus.end()) continue; + QuestStatusData const& qs = qs_itr->second; + if (qs.m_status == QUEST_STATUS_INCOMPLETE) { Quest const* qinfo = objmgr.GetQuestTemplate(questid); if(!qinfo) continue; + if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID) continue; + for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++) { if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case continue; + if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j]) return true; } @@ -16913,10 +19894,12 @@ bool Player::HasQuestForGO(int32 GOId) const } return false; } + void Player::UpdateForQuestWorldObjects() { if(m_clientGUIDs.empty()) return; + UpdateData udata; WorldPacket packet; for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr) @@ -16932,9 +19915,11 @@ void Player::UpdateForQuestWorldObjects() Creature *obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr); if(!obj) continue; + // check if this unit requires quest specific flags if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK)) continue; + SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(obj->GetEntry()); for(SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr) { @@ -16949,6 +19934,7 @@ void Player::UpdateForQuestWorldObjects() udata.BuildPacket(&packet); GetSession()->SendPacket(&packet); } + void Player::SummonIfPossible(bool agree) { if(!agree) @@ -16956,23 +19942,30 @@ void Player::SummonIfPossible(bool agree) m_summon_expire = 0; return; } + // expire and auto declined if(m_summon_expire < time(NULL)) return; + // stop taxi flight at summon if(isInFlight()) { GetMotionMaster()->MovementExpired(); CleanupAfterTaxiFlight(); } + // drop flag at summon // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag if(BattleGround *bg = GetBattleGround()) bg->EventPlayerDroppedFlag(this); + m_summon_expire = 0; + GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1); + TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation()); } + void Player::RemoveItemDurations( Item *item ) { for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr) @@ -16984,6 +19977,7 @@ void Player::RemoveItemDurations( Item *item ) } } } + void Player::AddItemDurations( Item *item ) { if(item->GetUInt32Value(ITEM_FIELD_DURATION)) @@ -16992,14 +19986,17 @@ void Player::AddItemDurations( Item *item ) item->SendTimeUpdate(this); } } + void Player::AutoUnequipOffhandIfNeed() { Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND ); if(!offItem) return; + // need unequip offhand for 2h-weapon without TitanGrip (in any from hands) if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed())) return; + ItemPosCountVec off_dest; uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ); if( off_msg == EQUIP_ERR_OK ) @@ -17016,18 +20013,22 @@ void Player::AutoUnequipOffhandIfNeed() offItem->DeleteFromInventoryDB(); // deletes item from character's inventory offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone CharacterDatabase.CommitTransaction(); + std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM); WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE); } } + OutdoorPvP * Player::GetOutdoorPvP() const { return sOutdoorPvPMgr.GetOutdoorPvPToZoneId(GetZoneId()); } + bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem) { if(spellInfo->EquippedItemClass < 0) return true; + // scan other equipped items for same requirements (mostly 2 daggers/etc) // for optimize check 2 used cases only switch(spellInfo->EquippedItemClass) @@ -17047,28 +20048,34 @@ bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item cons if(Item *item = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, i )) if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo)) return true; + // shields can be equipped to offhand slot if(Item *item = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND)) if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo)) return true; + // ranged slot can have some armor subclasses if(Item *item = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED)) if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo)) return true; + break; } default: sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass); break; } + return false; } + bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const { // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION)) return true; + // Check no reagent use mask flag96 noReagentMask; noReagentMask[0] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1); @@ -17076,14 +20083,17 @@ bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const noReagentMask[2] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+2); if (spellInfo->SpellFamilyFlags & noReagentMask) return true; + return false; } + void Player::RemoveItemDependentAurasAndCasts( Item * pItem ) { AuraMap& auras = GetAuras(); for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); ) { Aura* aura = itr->second; + // skip passive (passive item dependent spells work in another way) and not self applied auras SpellEntry const* spellInfo = aura->GetSpellProto(); if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID()) @@ -17091,21 +20101,25 @@ void Player::RemoveItemDependentAurasAndCasts( Item * pItem ) ++itr; continue; } + // skip if not item dependent or have alternative item if(HasItemFitToSpellReqirements(spellInfo,pItem)) { ++itr; continue; } + // no alt item, remove aura, restart check RemoveAura(itr); } + // currently casted spells can be dependent from item for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i) if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i))) if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) ) InterruptSpell(CurrentSpellTypes(i)); } + uint32 Player::GetResurrectionSpellId() { // search priceless resurrection possibilities @@ -17130,6 +20144,7 @@ uint32 Player::GetResurrectionSpellId() sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId()); continue; } + prio = 3; } // Twisting Nether // prio: 2 (max) @@ -17139,19 +20154,24 @@ uint32 Player::GetResurrectionSpellId() spell_id = 23700; } } + // Reincarnation (passive spell) // prio: 1 // Glyph of Renewed Life if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasAura(58059) || HasItemCount(17030,1))) spell_id = 21169; + return spell_id; } + // Used in triggers for check "Only to targets that grant experience or honor" req bool Player::isHonorOrXPTarget(Unit* pVictim) { uint32 v_level = pVictim->getLevel(); uint32 k_grey = Trinity::XP::GetGrayLevel(getLevel()); + // Victim level less gray level if(v_level<=k_grey) return false; + if(pVictim->GetTypeId() == TYPEID_UNIT) { if (((Creature*)pVictim)->isTotem() || @@ -17161,58 +20181,73 @@ bool Player::isHonorOrXPTarget(Unit* pVictim) } return true; } + bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim) { bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer(); + // prepare data for near group iteration (PvP and !PvP cases) uint32 xp = 0; bool honored_kill = false; + if(Group *pGroup = GetGroup()) { uint32 count = 0; uint32 sum_level = 0; Player* member_with_max_level = NULL; Player* not_gray_member_with_max_level = NULL; + pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level); + if(member_with_max_level) { // PvP kills doesn't yield experience // also no XP gained if there is no member below gray level xp = (PvP || !not_gray_member_with_max_level || GetVehicle()) ? 0 : Trinity::XP::Gain(not_gray_member_with_max_level, pVictim); + /// skip in check PvP case (for speed, not used) bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup(); bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon(); float group_rate = Trinity::XP::xp_in_group_rate(count,is_raid); + for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* pGroupGuy = itr->getSource(); if(!pGroupGuy) continue; + if(!pGroupGuy->IsAtGroupRewardDistance(pVictim)) continue; // member (alive or dead) or his corpse at req. distance + // honor can be in PvP and !PvP (racial leader) cases (for alive) if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count, -1, true) && pGroupGuy==this) honored_kill = true; + // xp and reputation only in !PvP case if(!PvP) { float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level; + // if is in dungeon then all receive full reputation at kill // rewarded any alive/dead/near_corpse group member pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate); + // XP updated only for alive group member if(pGroupGuy->isAlive() && not_gray_member_with_max_level && pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel()) { uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1); + // handle SPELL_AURA_MOD_XP_PCT auras Unit::AuraEffectList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT); for(Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i) itr_xp = uint32(itr_xp*(1.0f + (*i)->GetAmount() / 100.0f)); + pGroupGuy->GiveXP(itr_xp, pVictim); if(Pet* pet = pGroupGuy->GetPet()) pet->GivePetXP(itr_xp/2); } + // quest objectives updated only for alive group member or dead but with not released body if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse()) { @@ -17227,20 +20262,26 @@ bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim) else // if (!pGroup) { xp = (PvP || GetVehicle()) ? 0 : Trinity::XP::Gain(this, pVictim); + // honor can be in PvP and !PvP (racial leader) cases if(RewardHonor(pVictim,1, -1, true)) honored_kill = true; + // xp and reputation only in !PvP case if(!PvP) { RewardReputation(pVictim,1); + // handle SPELL_AURA_MOD_XP_PCT auras Unit::AuraEffectList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT); for(Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i) xp = uint32(xp*(1.0f + (*i)->GetAmount() / 100.0f)); + GiveXP(xp, pVictim); + if(Pet* pet = GetPet()) pet->GivePetXP(xp); + // normal creature (not pet/etc) can be only in !PvP case if(pVictim->GetTypeId()==TYPEID_UNIT) KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID()); @@ -17248,9 +20289,11 @@ bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim) } return xp || honored_kill; } + void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource) { uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0); + // prepare data for near group iteration if(Group *pGroup = GetGroup()) { @@ -17259,8 +20302,10 @@ void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewar Player* pGroupGuy = itr->getSource(); if(!pGroupGuy) continue; + if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource)) continue; // member (alive or dead) or his corpse at req. distance + // quest objectives updated only for alive group member or dead but with not released body if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse()) pGroupGuy->KilledMonsterCredit(creature_id, creature_guid); @@ -17269,30 +20314,38 @@ void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewar else // if (!pGroup) KilledMonsterCredit(creature_id, creature_guid); } + bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const { const WorldObject* player = GetCorpse(); if(!player || isAlive()) player = this; + if(player->GetMapId() != pRewardSource->GetMapId() || player->GetInstanceId() != pRewardSource->GetInstanceId()) return false; + return pRewardSource->GetDistance(player) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE); } + uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const { Item* item = GetWeaponForAttack(attType,true); + // unarmed only with base attack if(attType != BASE_ATTACK && !item) return 0; + // weapon skill or (unarmed for base attack) uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED); return GetBaseSkillValue(skill); } + void Player::ResurectUsingRequestData() { /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse if(IS_PLAYER_GUID(m_resurrectGUID)) TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation()); + //we cannot resurrect player when we triggered far teleport //player will be resurrected upon teleportation if(IsBeingTeleportedFar()) @@ -17300,19 +20353,26 @@ void Player::ResurectUsingRequestData() ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER); return; } + ResurrectPlayer(0.0f,false); + if(GetMaxHealth() > m_resurrectHealth) SetHealth( m_resurrectHealth ); else SetHealth( GetMaxHealth() ); + if(GetMaxPower(POWER_MANA) > m_resurrectMana) SetPower(POWER_MANA, m_resurrectMana ); else SetPower(POWER_MANA, GetMaxPower(POWER_MANA) ); + SetPower(POWER_RAGE, 0 ); + SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) ); + SpawnCorpseBones(); } + void Player::SetClientControl(Unit* target, uint8 allowMove) { WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1); @@ -17322,6 +20382,7 @@ void Player::SetClientControl(Unit* target, uint8 allowMove) if(target == this) SetMover(this); } + void Player::UpdateZoneDependentAuras( uint32 newZone ) { // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update @@ -17331,6 +20392,7 @@ void Player::UpdateZoneDependentAuras( uint32 newZone ) if( !HasAura(itr->second->spellId) ) CastSpell(this,itr->second->spellId,true); } + void Player::UpdateAreaDependentAuras( uint32 newArea ) { // remove auras from spells with area limitations @@ -17342,12 +20404,14 @@ void Player::UpdateAreaDependentAuras( uint32 newArea ) else ++iter; } + // some auras applied at subzone enter SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea); for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea)) if( !HasAura(itr->second->spellId) ) CastSpell(this,itr->second->spellId,true); + if(newArea == 4273 && GetVehicle() && GetPositionX() > 400) // Ulduar { switch(GetVehicleBase()->GetEntry()) @@ -17360,6 +20424,7 @@ void Player::UpdateAreaDependentAuras( uint32 newArea ) } } } + uint32 Player::GetCorpseReclaimDelay(bool pvp) const { if(pvp) @@ -17369,18 +20434,22 @@ uint32 Player::GetCorpseReclaimDelay(bool pvp) const } else if(!sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ) return 0; + time_t now = time(NULL); // 0..2 full period // should be ceil(x)-1 but not floor(x) uint32 count = (now < m_deathExpireTime - 1) ? (m_deathExpireTime - 1 - now)/DEATH_EXPIRE_STEP : 0; return copseReclaimDelay[count]; } + void Player::UpdateCorpseReclaimDelay() { bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH; + if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) || (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )) return; + time_t now = time(NULL); if(now < m_deathExpireTime) { @@ -17394,21 +20463,25 @@ void Player::UpdateCorpseReclaimDelay() else m_deathExpireTime = now+DEATH_EXPIRE_STEP; } + void Player::SendCorpseReclaimDelay(bool load) { Corpse* corpse = GetCorpse(); if(load && !corpse) return; + bool pvp; if(corpse) pvp = (corpse->GetType() == CORPSE_RESURRECTABLE_PVP); else pvp = (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH); + uint32 delay; if(load) { if(corpse->GetGhostTime() > m_deathExpireTime) return; + uint32 count; if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) || !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ) @@ -17419,59 +20492,77 @@ void Player::SendCorpseReclaimDelay(bool load) } else count=0; + time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count]; + time_t now = time(NULL); if(now >= expected_time) return; + delay = expected_time-now; } else delay = GetCorpseReclaimDelay(pvp); + if(!delay) return; + //! corpse reclaim delay 30 * 1000ms or longer at often deaths WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4); data << uint32(delay*IN_MILISECONDS); GetSession()->SendPacket( &data ); } + Player* Player::GetNextRandomRaidMember(float radius) { Group *pGroup = GetGroup(); if(!pGroup) return NULL; + std::vector<Player*> nearMembers; nearMembers.reserve(pGroup->GetMembersCount()); + for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* Target = itr->getSource(); + // IsHostileTo check duel and controlled by enemy if( Target && Target != this && IsWithinDistInMap(Target, radius) && !Target->HasInvisibilityAura() && !IsHostileTo(Target) ) nearMembers.push_back(Target); } + if (nearMembers.empty()) return NULL; + uint32 randTarget = urand(0,nearMembers.size()-1); return nearMembers[randTarget]; } + PartyResult Player::CanUninviteFromGroup() const { const Group* grp = GetGroup(); if(!grp) return PARTY_RESULT_YOU_NOT_IN_GROUP; + if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID())) return PARTY_RESULT_YOU_NOT_LEADER; + if(InBattleGround()) return PARTY_RESULT_INVITE_RESTRICTED; + return PARTY_RESULT_OK; } + void Player::SetBattleGroundRaid(Group* group, int8 subgroup) { //we must move references from m_group to m_originalGroup SetOriginalGroup(GetGroup(), GetSubGroup()); + m_group.unlink(); m_group.link(group, this); m_group.setSubGroup((uint8)subgroup); } + void Player::RemoveFromBattleGroundRaid() { //remove existing reference @@ -17483,6 +20574,7 @@ void Player::RemoveFromBattleGroundRaid() } SetOriginalGroup(NULL); } + void Player::SetOriginalGroup(Group *group, int8 subgroup) { if( group == NULL ) @@ -17495,6 +20587,7 @@ void Player::SetOriginalGroup(Group *group, int8 subgroup) m_originalGroup.setSubGroup((uint8)subgroup); } } + void Player::UpdateUnderwaterState( Map* m, float x, float y, float z ) { LiquidData liquid_status; @@ -17507,6 +20600,7 @@ void Player::UpdateUnderwaterState( Map* m, float x, float y, float z ) m_MirrorTimerFlags|=UNDERWATER_INWATER; return; } + // All liquids type - check under water position if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME)) { @@ -17515,11 +20609,13 @@ void Player::UpdateUnderwaterState( Map* m, float x, float y, float z ) else m_MirrorTimerFlags &= ~UNDERWATER_INWATER; } + // Allow travel in dark water on taxi or transport if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport()) m_MirrorTimerFlags |= UNDERWARER_INDARKWATER; else m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER; + // in lava check, anywhere in lava level if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA) { @@ -17537,20 +20633,25 @@ void Player::UpdateUnderwaterState( Map* m, float x, float y, float z ) m_MirrorTimerFlags &= ~UNDERWATER_INSLIME; } } + void Player::SetCanParry( bool value ) { if(m_canParry==value) return; + m_canParry = value; UpdateParryPercentage(); } + void Player::SetCanBlock( bool value ) { if(m_canBlock==value) return; + m_canBlock = value; UpdateBlockPercentage(); } + bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const { for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr) @@ -17558,9 +20659,11 @@ bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const return true; return false; } + //*********************************** //-------------TRINITY--------------- //*********************************** + void Player::StopCastingBindSight() { if(WorldObject* target = GetViewpoint()) @@ -17573,43 +20676,53 @@ void Player::StopCastingBindSight() } } } + void Player::SetViewpoint(WorldObject* target, bool apply) { if(apply) { sLog.outDebug("Player::CreateViewpoint: Player %s create seer %u (TypeId: %u).", GetName(), target->GetEntry(), target->GetTypeId()); + if(!AddUInt64Value(PLAYER_FARSIGHT, target->GetGUID())) { sLog.outCrash("Player::CreateViewpoint: Player %s cannot add new viewpoint!", GetName()); return; } + // farsight dynobj or puppet may be very far away UpdateVisibilityOf(target); + if(target->isType(TYPEMASK_UNIT) && !GetVehicle()) ((Unit*)target)->AddPlayerToVision(this); } else { sLog.outDebug("Player::CreateViewpoint: Player %s remove seer", GetName()); + if(!RemoveUInt64Value(PLAYER_FARSIGHT, target->GetGUID())) { sLog.outCrash("Player::CreateViewpoint: Player %s cannot remove current viewpoint!", GetName()); return; } + if(target->isType(TYPEMASK_UNIT) && !GetVehicle()) ((Unit*)target)->RemovePlayerFromVision(this); + //must immediately set seer back otherwise may crash m_seer = this; + //WorldPacket data(SMSG_CLEAR_FAR_SIGHT_IMMEDIATE, 0); //GetSession()->SendPacket(&data); } } + WorldObject* Player::GetViewpoint() const { if(uint64 guid = GetUInt64Value(PLAYER_FARSIGHT)) return (WorldObject*)ObjectAccessor::GetObjectByTypeMask(*this, guid, TYPEMASK_SEER); return NULL; } + bool Player::CanUseBattleGroundObject() { // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction) @@ -17626,6 +20739,7 @@ bool Player::CanUseBattleGroundObject() isAlive() // live player ); } + bool Player::CanCaptureTowerPoint() { return ( !HasStealthAura() && // not stealthed @@ -17633,36 +20747,50 @@ bool Player::CanCaptureTowerPoint() isAlive() // live player ); } + uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair) { uint32 level = getLevel(); + if(level > GT_MAX_LEVEL) level = GT_MAX_LEVEL; // max level in this dbc + uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2); uint8 haircolor = GetByteValue(PLAYER_BYTES, 3); uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0); + if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair)) return 0; + GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1); + if(!bsc) // shouldn't happen return 0xFFFFFFFF; + float cost = 0; + if(hairstyle != newhairstyle) cost += bsc->cost; // full price + if((haircolor != newhaircolor) && (hairstyle == newhairstyle)) cost += bsc->cost * 0.5f; // +1/2 of price + if(facialhair != newfacialhair) cost += bsc->cost * 0.75f; // +3/4 of price + return uint32(cost); } + void Player::InitGlyphsForLevel() { for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i) if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i)) if(gs->Order) SetGlyphSlot(gs->Order - 1, gs->Id); + uint32 level = getLevel(); uint32 value = 0; + // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level if(level >= 15) value |= (0x01 | 0x02); @@ -17674,11 +20802,14 @@ void Player::InitGlyphsForLevel() value |= 0x10; if(level >= 80) value |= 0x20; + SetUInt32Value(PLAYER_GLYPHS_ENABLED, value); } + bool Player::isTotalImmune() { AuraEffectList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY); + uint32 immuneMask = 0; for(AuraEffectList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr) { @@ -17688,39 +20819,48 @@ bool Player::isTotalImmune() } return false; } + bool Player::HasTitle(uint32 bitIndex) { if (bitIndex > MAX_TITLE_INDEX) return false; + uint32 fieldIndexOffset = bitIndex / 32; uint32 flag = 1 << (bitIndex % 32); return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag); } + void Player::SetTitle(CharTitlesEntry const* title, bool lost) { uint32 fieldIndexOffset = title->bit_index / 32; uint32 flag = 1 << (title->bit_index % 32); + if(lost) { if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag)) return; + RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag); } else { if(HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag)) return; + SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag); } + WorldPacket data(SMSG_TITLE_EARNED, 4 + 4); data << uint32(title->bit_index); data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost GetSession()->SendPacket(&data); } + /*-----------------------TRINITY--------------------------*/ bool Player::isTotalImmunity() { AuraEffectList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY); + for(AuraEffectList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr) { if (((*itr)->GetMiscValue() & SPELL_SCHOOL_MASK_ALL) !=0) // total immunity @@ -17740,10 +20880,12 @@ bool Player::isTotalImmunity() } return false; } + void Player::UpdateCharmedAI() { //This should only called in Player::Update Creature *charmer = (Creature*)GetCharmer(); + //kill self if charm aura has infinite duration if(charmer->IsInEvadeMode()) { @@ -17755,26 +20897,32 @@ void Player::UpdateCharmedAI() return; } } + if(!charmer->isInCombat()) GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE); + Unit *target = getVictim(); if(!target || !charmer->canAttack(target)) { target = charmer->SelectNearestTarget(); if(!target) return; + GetMotionMaster()->MoveChase(target); Attack(target, true); } } + void Player::ConvertRune(uint8 index, RuneType newType) { SetCurrentRune(index, newType); + WorldPacket data(SMSG_CONVERT_RUNE, 2); data << uint8(index); data << uint8(newType); GetSession()->SendPacket(&data); } + void Player::ResyncRunes(uint8 count) { WorldPacket data(SMSG_RESYNC_RUNES, count * 2); @@ -17785,12 +20933,14 @@ void Player::ResyncRunes(uint8 count) } GetSession()->SendPacket(&data); } + void Player::AddRunePower(uint8 index) { WorldPacket data(SMSG_ADD_RUNE_POWER, 4); data << uint32(1 << index); // mask (0x00-0x3F probably) GetSession()->SendPacket(&data); } + static RuneType runeSlotTypes[MAX_RUNES] = { /*0*/ RUNE_BLOOD, /*1*/ RUNE_BLOOD, @@ -17799,13 +20949,17 @@ static RuneType runeSlotTypes[MAX_RUNES] = { /*4*/ RUNE_FROST, /*5*/ RUNE_FROST }; + void Player::InitRunes() { if(getClass() != CLASS_DEATH_KNIGHT) return; + m_runes = new Runes; + m_runes->runeState = 0; m_runes->lastUsedRune = RUNE_BLOOD; + for(uint32 i = 0; i < MAX_RUNES; ++i) { SetBaseRune(i, runeSlotTypes[i]); // init base types @@ -17813,24 +20967,30 @@ void Player::InitRunes() SetRuneCooldown(i, 0); // reset cooldowns m_runes->SetRuneState(i); } + for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i) SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f); } + bool Player::IsBaseRuneSlotsOnCooldown(RuneType runeType) const { for(uint32 i = 0; i < MAX_RUNES; ++i) if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0) return false; + return true; } + void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast) { Loot loot; loot.FillLoot (loot_id,store,this,true); + uint32 max_slot = loot.GetMaxSlotInLootFor(this); for(uint32 i = 0; i < max_slot; ++i) { LootItem* lootItem = loot.LootItemInSlot(i,this); + ItemPosCountVec dest; uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count); if(msg != EQUIP_ERR_OK && slot != NULL_SLOT) @@ -17842,50 +21002,65 @@ void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore cons SendEquipError( msg, NULL, NULL ); continue; } + Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId); SendNewItem(pItem, lootItem->count, false, false, broadcast); } } + uint32 Player::CalculateTalentsPoints() const { uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9; + if(getClass() != CLASS_DEATH_KNIGHT || GetMapId() != 609) return uint32(base_talent * sWorld.getRate(RATE_TALENT)); + uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55; talentPointsForLevel += m_questRewardTalentCount; + if(talentPointsForLevel > base_talent) talentPointsForLevel = base_talent; + return uint32(talentPointsForLevel * sWorld.getRate(RATE_TALENT)); } + bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const { // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone); return v_map != 571 || HasSpell(54197) && zone != 4197; // Cold Weather Flying } + void Player::learnSpellHighRank(uint32 spellid) { learnSpell(spellid,false); + if(uint32 next = spellmgr.GetNextSpellInChain(spellid)) learnSpellHighRank(next); } + void Player::_LoadSkills() { // Note: skill data itself loaded from `data` field. This is only cleanup part of load + // reset skill modifiers and set correct unlearn flags for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++) { SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0); + // set correct unlearn bit uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF; if(!id) continue; + SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id); if(!pSkill) continue; + // enable unlearn button for primary professions only if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION) SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1)); else SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0)); + // set fixed skill ranges switch(GetSkillRangeType(pSkill,false)) { @@ -17898,9 +21073,11 @@ void Player::_LoadSkills() default: break; } + uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))); learnSkillRewardedSpells(id, vskill); } + // special settings if(getClass()==CLASS_DEATH_KNIGHT) { @@ -17910,6 +21087,7 @@ void Player::_LoadSkills() uint32 base_skill = (base_level-1)*5; // 270 at starting level 55 if(base_skill < 1) base_skill = 1; // skill mast be known and then > 0 in any case + if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill) SetSkill(SKILL_FIRST_AID,base_skill, base_skill); if(GetPureSkillValue (SKILL_AXES) < base_skill) @@ -17928,6 +21106,7 @@ void Player::_LoadSkills() SetSkill(SKILL_UNARMED, base_skill,base_skill); } } + uint32 Player::GetPhaseMaskForSpawn() const { uint32 phase = PHASEMASK_NORMAL; @@ -17939,17 +21118,22 @@ uint32 Player::GetPhaseMaskForSpawn() const if(!phases.empty()) phase = phases.front()->GetMiscValue(); } + // some aura phases include 1 normal map in addition to phase itself if(uint32 n_phase = phase & ~PHASEMASK_NORMAL) return n_phase; + return PHASEMASK_NORMAL; } + uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const { ItemPrototype const* pProto = pItem->GetProto(); + // proto based limitations if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count)) return res; + // check unique-equipped on gems for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot) { @@ -17959,17 +21143,22 @@ uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) c SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if(!enchantEntry) continue; + ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID); if(!pGem) continue; + // include for check equip another gems with same limit category for not equipped item (and then not counted) uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1; + if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count)) return res; } + return EQUIP_ERR_OK; } + uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const { // check unique-equipped on item @@ -17979,25 +21168,31 @@ uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_s if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot)) return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; } + // check unique-equipped limit if (itemProto->ItemLimitCategory) { ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory); if(!limitEntry) return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; + if(limit_count > limitEntry->maxCount) return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems) + // there is an equip limit on this item if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot)) return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; } + return EQUIP_ERR_OK; } + void Player::HandleFall(MovementInfo const& movementInfo) { // calculate total z distance of the fall float z_diff = m_lastFallZ - movementInfo.z; //sLog.outDebug("zDiff = %f", z_diff); + //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored // 14.57 can be calculated by resolving damageperc formula below to 0 if (z_diff >= 14.57f && !isDead() && !isGameMaster() && @@ -18006,55 +21201,74 @@ void Player::HandleFall(MovementInfo const& movementInfo) { //Safe fall, fall height reduction int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL); + float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f; + if(damageperc >0 ) { uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL)); + float height = movementInfo.z; UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height); + if (damage > 0) { //Prevent fall damage from being more than the player maximum health if (damage > GetMaxHealth()) damage = GetMaxHealth(); + // Gust of Wind if (HasAura(43621)) damage = GetMaxHealth()/2; + uint32 original_health = GetHealth(); uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage); + // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case if (isAlive() && final_damage < original_health) GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100)); } + //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.z, height, GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall); } } } + void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ ) { GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1, miscvalue2, unit, time); } + void Player::CompletedAchievement(AchievementEntry const* entry) { GetAchievementMgr().CompletedAchievement(entry); } + void Player::LearnTalent(uint32 talentId, uint32 talentRank) { uint32 CurTalentPoints = GetFreeTalentPoints(); + if(CurTalentPoints == 0) return; + if (talentRank >= MAX_TALENT_RANK) return; + TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId ); + if(!talentInfo) return; + TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab ); + if(!talentTabInfo) return; + // prevent learn talent for different class (cheating) if( (getClassMask() & talentTabInfo->ClassMask) == 0 ) return; + // find current max talent rank (0~5) uint8 curtalent_maxrank = 0; // 0 = not learned any rank for(int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank) @@ -18065,12 +21279,15 @@ void Player::LearnTalent(uint32 talentId, uint32 talentRank) break; } } + // we already have same or higher talent rank learned if(curtalent_maxrank >= (talentRank + 1)) return; + // check if we have enough talent points if(CurTalentPoints < (talentRank - curtalent_maxrank + 1)) return; + // Check if it requires another talent if (talentInfo->DependsOn > 0) { @@ -18087,8 +21304,10 @@ void Player::LearnTalent(uint32 talentId, uint32 talentRank) return; } } + // Find out how many points we have in this field uint32 spentPoints = 0; + uint32 tTab = talentInfo->TalentTab; if (talentInfo->Row > 0) { @@ -18115,9 +21334,11 @@ void Player::LearnTalent(uint32 talentId, uint32 talentRank) } } } + // not have required min points spent in talent tree if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK)) return; + // spell not set in talent.dbc uint32 spellid = talentInfo->RankID[talentRank]; if( spellid == 0 ) @@ -18125,45 +21346,66 @@ void Player::LearnTalent(uint32 talentId, uint32 talentRank) sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank); return; } + // already known if(HasSpell(spellid)) return; + // learn! (other talent ranks will unlearned at learning) learnSpell(spellid, false); AddTalent(spellid, m_activeSpec, true); + sLog.outDetail("TalentID: %u Rank: %u Spell: %u Spec: %u\n", talentId, talentRank, spellid, m_activeSpec); + // update free talent points SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1)); } + void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank) { Pet *pet = GetPet(); + if(!pet) return; + if(petGuid != pet->GetGUID()) return; + uint32 CurTalentPoints = pet->GetFreeTalentPoints(); + if(CurTalentPoints == 0) return; + if (talentRank >= MAX_PET_TALENT_RANK) return; + TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId); + if(!talentInfo) return; + TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); + if(!talentTabInfo) return; + CreatureInfo const *ci = pet->GetCreatureInfo(); + if(!ci) return; + CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family); + if(!pet_family) return; + if(pet_family->petTalentType < 0) // not hunter pet return; + // prevent learn talent for different family (cheating) if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask)) return; + // find current max talent rank (0~5) uint8 curtalent_maxrank = 0; // 0 = not learned any rank for(int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank) @@ -18174,12 +21416,15 @@ void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank) break; } } + // we already have same or higher talent rank learned if(curtalent_maxrank >= (talentRank + 1)) return; + // check if we have enough talent points if(CurTalentPoints < (talentRank - curtalent_maxrank + 1)) return; + // Check if it requires another talent if (talentInfo->DependsOn > 0) { @@ -18196,8 +21441,10 @@ void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank) return; } } + // Find out how many points we have in this field uint32 spentPoints = 0; + uint32 tTab = talentInfo->TalentTab; if (talentInfo->Row > 0) { @@ -18224,9 +21471,11 @@ void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank) } } } + // not have required min points spent in talent tree if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK)) return; + // spell not set in talent.dbc uint32 spellid = talentInfo->RankID[talentRank]; if( spellid == 0 ) @@ -18234,15 +21483,19 @@ void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank) sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank); return; } + // already known if(pet->HasSpell(spellid)) return; + // learn! (other talent ranks will unlearned at learning) pet->learnSpell(spellid); sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid); + // update free talent points pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1)); } + void Player::UpdateKnownCurrencies(uint32 itemId, bool apply) { if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId)) @@ -18253,54 +21506,69 @@ void Player::UpdateKnownCurrencies(uint32 itemId, bool apply) RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1))); } } + void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode ) { if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND) SetFallInformation(minfo.fallTime, minfo.z); } + void Player::UnsummonPetTemporaryIfAny() { Pet* pet = GetPet(); if(!pet) return; + if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() ) { m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber(); m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL); } + RemovePet(pet, PET_SAVE_AS_CURRENT); } + void Player::ResummonPetTemporaryUnSummonedIfAny() { if(!m_temporaryUnsummonedPetNumber) return; + // not resummon in not appropriate state if(IsPetNeedBeTemporaryUnsummoned()) return; + if(GetPetGUID()) return; + Pet* NewPet = new Pet(this); if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true)) delete NewPet; + m_temporaryUnsummonedPetNumber = 0; } + bool Player::canSeeSpellClickOn(Creature const *c) const { if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK)) return false; + SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(c->GetEntry()); if(clickPair.first == clickPair.second) return true; + for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr) if(itr->second.IsFitToRequirements(this, c)) return true; + return false; } + void Player::BuildPlayerTalentsInfoData(WorldPacket *data) { *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints *data << uint8(m_specsCount); // talent group count (0, 1 or 2) *data << uint8(m_activeSpec); // talent group index (0 or 1) + if(m_specsCount) { // loop through all specs (only 1 for now) @@ -18309,19 +21577,24 @@ void Player::BuildPlayerTalentsInfoData(WorldPacket *data) uint8 talentIdCount = 0; size_t pos = data->wpos(); *data << uint8(talentIdCount); // [PH], talentIdCount + // find class talent tabs (all players have 3 talent tabs) uint32 const* talentTabIds = GetTalentTabPages(getClass()); + for(uint8 i = 0; i < 3; ++i) { uint32 talentTabId = talentTabIds[i]; + for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId) { TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId); if(!talentInfo) continue; + // skip another tab talents if(talentInfo->TalentTab != talentTabId) continue; + // find max talent rank (0~4) int8 curtalent_maxrank = -1; for(int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank) @@ -18332,55 +21605,73 @@ void Player::BuildPlayerTalentsInfoData(WorldPacket *data) break; } } + // not learned talent if(curtalent_maxrank < 0) continue; + *data << uint32(talentInfo->TalentID); // Talent.dbc *data << uint8(curtalent_maxrank); // talentMaxRank (0-4) + ++talentIdCount; } } + data->put<uint8>(pos, talentIdCount); // put real count + *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count + for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i) *data << uint16(m_Glyphs[specIdx][i]); // GlyphProperties.dbc } } } + void Player::BuildPetTalentsInfoData(WorldPacket *data) { uint32 unspentTalentPoints = 0; size_t pointsPos = data->wpos(); *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints + uint8 talentIdCount = 0; size_t countPos = data->wpos(); *data << uint8(talentIdCount); // [PH], talentIdCount + Pet *pet = GetPet(); if(!pet) return; + unspentTalentPoints = pet->GetFreeTalentPoints(); + data->put<uint32>(pointsPos, unspentTalentPoints); // put real points + CreatureInfo const *ci = pet->GetCreatureInfo(); if(!ci) return; + CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family); if(!pet_family || pet_family->petTalentType < 0) return; + for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId) { TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId ); if(!talentTabInfo) continue; + if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask)) continue; + for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId) { TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId); if(!talentInfo) continue; + // skip another tab talents if(talentInfo->TalentTab != talentTabId) continue; + // find max talent rank (0~4) int8 curtalent_maxrank = -1; for(int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank) @@ -18391,17 +21682,23 @@ void Player::BuildPetTalentsInfoData(WorldPacket *data) break; } } + // not learned talent if(curtalent_maxrank < 0) continue; + *data << uint32(talentInfo->TalentID); // Talent.dbc *data << uint8(curtalent_maxrank); // talentMaxRank (0-4) + ++talentIdCount; } + data->put<uint8>(countPos, talentIdCount); // put real count + break; } } + void Player::SendTalentsInfoData(bool pet) { WorldPacket data(SMSG_TALENTS_INFO, 50); @@ -18412,37 +21709,51 @@ void Player::SendTalentsInfoData(bool pet) BuildPlayerTalentsInfoData(&data); GetSession()->SendPacket(&data); } + void Player::BuildEnchantmentsInfoData(WorldPacket *data) { uint32 slotUsedMask = 0; size_t slotUsedMaskPos = data->wpos(); *data << uint32(slotUsedMask); // slotUsedMask < 0x80000 + for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i) { Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i); + if(!item) continue; + slotUsedMask |= (1 << i); + *data << uint32(item->GetEntry()); // item entry + uint16 enchantmentMask = 0; size_t enchantmentMaskPos = data->wpos(); *data << uint16(enchantmentMask); // enchantmentMask < 0x1000 + for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j) { uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j)); + if(!enchId) continue; + enchantmentMask |= (1 << j); + *data << uint16(enchId); // enchantmentId? } + data->put<uint16>(enchantmentMaskPos, enchantmentMask); + *data << uint16(0); // unknown data->appendPackGUID(item->GetUInt64Value(ITEM_FIELD_CREATOR)); // item creator *data << uint32(0); // seed? } + data->put<uint32>(slotUsedMaskPos, slotUsedMask); } + void Player::SendEquipmentSetList() { uint32 count = 0; @@ -18459,16 +21770,19 @@ void Player::SendEquipmentSetList() data << itr->second.IconName; for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i) data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM)); + ++count; // client have limit but it checked at loading and set } data.put<uint32>(count_pos, count); GetSession()->SendPacket(&data); } + void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset) { if(eqset.Guid != 0) { bool found = false; + for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr) { if((itr->second.Guid == eqset.Guid) && (itr->first == index)) @@ -18477,25 +21791,33 @@ void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset) break; } } + if(!found) // something wrong... { sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index); return; } } + EquipmentSet& eqslot = m_EquipmentSets[index]; + EquipmentSetUpdateState old_state = eqslot.state; + eqslot = eqset; + if(eqset.Guid == 0) { eqslot.Guid = objmgr.GenerateEquipmentSetGuid(); + WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1); data << uint32(index); data.appendPackGUID(eqslot.Guid); GetSession()->SendPacket(&data); } + eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED; } + void Player::_SaveEquipmentSets() { for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();) @@ -18528,6 +21850,7 @@ void Player::_SaveEquipmentSets() } } } + void Player::_SaveBGData() { CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow()); @@ -18539,6 +21862,7 @@ void Player::_SaveBGData() m_bgData.joinPos.GetOrientation(), m_bgData.joinPos.GetMapId(), m_bgData.taxiPath[0], m_bgData.taxiPath[1], m_bgData.mountSpell); } } + void Player::DeleteEquipmentSet(uint64 setGuid) { for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr) @@ -18553,12 +21877,15 @@ void Player::DeleteEquipmentSet(uint64 setGuid) } } } + void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ ) { m_atLoginFlags &= ~f; + if(in_db_also) CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow()); } + void Player::SendClearCooldown( uint32 spell_id, Unit* target ) { WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8); @@ -18566,6 +21893,7 @@ void Player::SendClearCooldown( uint32 spell_id, Unit* target ) data << uint64(target->GetGUID()); SendDirectMessage(&data); } + void Player::ResetMap() { // this may be called during Map::Update @@ -18577,31 +21905,39 @@ void Player::ResetMap() Unit::ResetMap(); GetMapRef().unlink(); } + void Player::SetMap(Map * map) { Unit::SetMap(map); m_mapRef.link(map, this); } + void Player::_LoadGlyphs(QueryResult *result) { // SetPQuery(PLAYER_LOGIN_QUERY_LOADGLYPHS, "SELECT spec, glyph1, glyph2, glyph3, glyph4, glyph5, glyph6 from character_glyphs WHERE guid = '%u'", GUID_LOPART(m_guid)); if (!result) return; + do { Field *fields = result->Fetch(); + uint8 spec = fields[0].GetUInt8(); if (spec >= m_specsCount) continue; + m_Glyphs[spec][0] = fields[1].GetUInt32(); m_Glyphs[spec][1] = fields[2].GetUInt32(); m_Glyphs[spec][2] = fields[3].GetUInt32(); m_Glyphs[spec][3] = fields[4].GetUInt32(); m_Glyphs[spec][4] = fields[5].GetUInt32(); m_Glyphs[spec][5] = fields[6].GetUInt32(); + } while (result->NextRow()); + delete result; } + void Player::_SaveGlyphs() { CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid='%u'",GetGUIDLow()); @@ -18611,6 +21947,7 @@ void Player::_SaveGlyphs() GetGUIDLow(), spec, m_Glyphs[spec][0], m_Glyphs[spec][1], m_Glyphs[spec][2], m_Glyphs[spec][3], m_Glyphs[spec][4], m_Glyphs[spec][5]); } } + void Player::_LoadTalents(QueryResult *result) { // SetPQuery(PLAYER_LOGIN_QUERY_LOADTALENTS, "SELECT spell, spec FROM character_talent WHERE guid = '%u'", GUID_LOPART(m_guid)); @@ -18619,12 +21956,15 @@ void Player::_LoadTalents(QueryResult *result) do { Field *fields = result->Fetch(); + AddTalent(fields[0].GetUInt32(), fields[1].GetUInt32(), false); } while( result->NextRow() ); + delete result; } } + void Player::_SaveTalents() { for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i) @@ -18633,8 +21973,10 @@ void Player::_SaveTalents() { if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED) CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' and spell = '%u' and spec = '%u'", GetGUIDLow(), itr->first, itr->second->spec); + if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED) CharacterDatabase.PExecute("INSERT INTO character_talent (guid,spell,spec) VALUES ('%u', '%u', '%u')", GetGUIDLow(), itr->first, itr->second->spec); + if (itr->second->state == PLAYERSPELL_REMOVED) { delete itr->second; @@ -18648,10 +21990,12 @@ void Player::_SaveTalents() } } } + void Player::UpdateSpecCount(uint8 count) { if(GetSpecsCount() == count) return; + if(count == MIN_TALENT_SPECS) { _SaveActions(); // make sure the button list is cleaned up @@ -18672,57 +22016,76 @@ void Player::UpdateSpecCount(uint8 count) { return; } + SetSpecsCount(count); + SendTalentsInfoData(false); } + void Player::ActivateSpec(uint8 spec) { if (GetActiveSpec() == spec) return; + if (GetSpecsCount() != MAX_TALENT_SPECS) return; + if (GetMap()->IsBattleGround() && !HasAura(44521)) // In BattleGround with no Preparation buff return; + RemoveAllAuras(this->GetGUID(), NULL, false, true); // remove all positive auras (ie: buffs from another spec) + _SaveActions(); + UnsummonPetTemporaryIfAny(); + uint32 const* talentTabIds = GetTalentTabPages(getClass()); + for (uint8 i = 0; i < 3; ++i) { uint32 talentTabId = talentTabIds[i]; + for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId) { TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId); if (!talentInfo) continue; + // skip another tab talents if (talentInfo->TalentTab != talentTabId) continue; + // remove all talent ranks, starting at highest rank for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank) if (talentInfo->RankID[rank] != 0 && HasTalent(talentInfo->RankID[rank], m_activeSpec)) removeSpell(talentInfo->RankID[rank], true); } } + // set glyphs for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot) // remove secondary glyph if (uint32 oldglyph = m_Glyphs[m_activeSpec][slot]) if (GlyphPropertiesEntry const *old_gp = sGlyphPropertiesStore.LookupEntry(oldglyph)) RemoveAurasDueToSpell(old_gp->SpellId); + SetActiveSpec(spec); uint32 spentTalents = 0; + for (uint8 i = 0; i < 3; ++i) { uint32 talentTabId = talentTabIds[i]; + for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId) { TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId); if (!talentInfo) continue; + // skip another tab talents if (talentInfo->TalentTab != talentTabId) continue; + // learn highest talent rank that exists in newly activated spec for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank) { @@ -18734,28 +22097,37 @@ void Player::ActivateSpec(uint8 spec) } } } + // set glyphs - for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot) + for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot) { uint32 glyph = m_Glyphs[m_activeSpec][slot]; + // apply primary glyph if (glyph) if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph)) CastSpell(this, gp->SpellId, true); + SetGlyph(slot, glyph); } + m_usedTalentCount = spentTalents; InitTalentForLevel(); + m_actionButtons.clear(); if (QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type FROM character_action WHERE guid = '%u' AND spec = '%u' ORDER BY button", GetGUIDLow(), m_activeSpec)) _LoadActions(result, false); + ResummonPetTemporaryUnSummonedIfAny(); SendActionButtons(1); + Powers pw = getPowerType(); if (pw != POWER_MANA) SetPower(POWER_MANA, 0); // what on earth is this for?! + SetPower(pw, 0); } + void Player::SetReputation(uint32 factionentry, uint32 value) { GetReputationMgr().SetReputation(sFactionStore.LookupEntry(factionentry),value); |