[9581] Fixed apply damage reduction to melee/ranged damage.
[getmangos.git] / src / game / Player.cpp
blob8a76f985e0aa7e0f8de9aa411a3346b8f9c3240a
1 /*
2 * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "SpellMgr.h"
25 #include "World.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #include "UpdateMask.h"
29 #include "Player.h"
30 #include "Vehicle.h"
31 #include "SkillDiscovery.h"
32 #include "QuestDef.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
35 #include "Channel.h"
36 #include "ChannelMgr.h"
37 #include "MapManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "GridNotifiers.h"
41 #include "GridNotifiersImpl.h"
42 #include "CellImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "ObjectGuid.h"
46 #include "CreatureAI.h"
47 #include "Formulas.h"
48 #include "Group.h"
49 #include "Guild.h"
50 #include "Pet.h"
51 #include "Util.h"
52 #include "Transports.h"
53 #include "Weather.h"
54 #include "BattleGround.h"
55 #include "BattleGroundAV.h"
56 #include "BattleGroundMgr.h"
57 #include "ArenaTeam.h"
58 #include "Chat.h"
59 #include "Database/DatabaseImpl.h"
60 #include "Spell.h"
61 #include "SocialMgr.h"
62 #include "AchievementMgr.h"
64 #include <cmath>
66 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
68 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
69 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
70 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
72 #define SKILL_VALUE(x) PAIR32_LOPART(x)
73 #define SKILL_MAX(x) PAIR32_HIPART(x)
74 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
76 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
77 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
78 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
80 enum CharacterFlags
82 CHARACTER_FLAG_NONE = 0x00000000,
83 CHARACTER_FLAG_UNK1 = 0x00000001,
84 CHARACTER_FLAG_UNK2 = 0x00000002,
85 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
86 CHARACTER_FLAG_UNK4 = 0x00000008,
87 CHARACTER_FLAG_UNK5 = 0x00000010,
88 CHARACTER_FLAG_UNK6 = 0x00000020,
89 CHARACTER_FLAG_UNK7 = 0x00000040,
90 CHARACTER_FLAG_UNK8 = 0x00000080,
91 CHARACTER_FLAG_UNK9 = 0x00000100,
92 CHARACTER_FLAG_UNK10 = 0x00000200,
93 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
94 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
95 CHARACTER_FLAG_UNK13 = 0x00001000,
96 CHARACTER_FLAG_GHOST = 0x00002000,
97 CHARACTER_FLAG_RENAME = 0x00004000,
98 CHARACTER_FLAG_UNK16 = 0x00008000,
99 CHARACTER_FLAG_UNK17 = 0x00010000,
100 CHARACTER_FLAG_UNK18 = 0x00020000,
101 CHARACTER_FLAG_UNK19 = 0x00040000,
102 CHARACTER_FLAG_UNK20 = 0x00080000,
103 CHARACTER_FLAG_UNK21 = 0x00100000,
104 CHARACTER_FLAG_UNK22 = 0x00200000,
105 CHARACTER_FLAG_UNK23 = 0x00400000,
106 CHARACTER_FLAG_UNK24 = 0x00800000,
107 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
108 CHARACTER_FLAG_DECLINED = 0x02000000,
109 CHARACTER_FLAG_UNK27 = 0x04000000,
110 CHARACTER_FLAG_UNK28 = 0x08000000,
111 CHARACTER_FLAG_UNK29 = 0x10000000,
112 CHARACTER_FLAG_UNK30 = 0x20000000,
113 CHARACTER_FLAG_UNK31 = 0x40000000,
114 CHARACTER_FLAG_UNK32 = 0x80000000
117 enum CharacterCustomizeFlags
119 CHAR_CUSTOMIZE_FLAG_NONE = 0x00000000,
120 CHAR_CUSTOMIZE_FLAG_CUSTOMIZE = 0x00000001, // name, gender, etc...
121 CHAR_CUSTOMIZE_FLAG_FACTION = 0x00010000, // name, gender, faction, etc...
122 CHAR_CUSTOMIZE_FLAG_RACE = 0x00100000 // name, gender, race, etc...
125 // corpse reclaim times
126 #define DEATH_EXPIRE_STEP (5*MINUTE)
127 #define MAX_DEATH_COUNT 3
129 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
131 //== PlayerTaxi ================================================
133 PlayerTaxi::PlayerTaxi()
135 // Taxi nodes
136 memset(m_taximask, 0, sizeof(m_taximask));
139 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
141 // class specific initial known nodes
142 switch(chrClass)
144 case CLASS_DEATH_KNIGHT:
146 for(int i = 0; i < TaxiMaskSize; ++i)
147 m_taximask[i] |= sOldContinentsNodesMask[i];
148 break;
152 // race specific initial known nodes: capital and taxi hub masks
153 switch(race)
155 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
156 case RACE_ORC: SetTaximaskNode(23); break; // Orc
157 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
158 case RACE_NIGHTELF: SetTaximaskNode(26);
159 SetTaximaskNode(27); break; // Night Elf
160 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
161 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
162 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
163 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
164 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
165 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
168 // new continent starting masks (It will be accessible only at new map)
169 switch(Player::TeamForRace(race))
171 case ALLIANCE: SetTaximaskNode(100); break;
172 case HORDE: SetTaximaskNode(99); break;
174 // level dependent taxi hubs
175 if(level>=68)
176 SetTaximaskNode(213); //Shattered Sun Staging Area
179 void PlayerTaxi::LoadTaxiMask(const char* data)
181 Tokens tokens = StrSplit(data, " ");
183 int index;
184 Tokens::iterator iter;
185 for (iter = tokens.begin(), index = 0;
186 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
188 // load and set bits only for existed taxi nodes
189 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
193 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
195 if(all)
197 for (uint8 i=0; i<TaxiMaskSize; ++i)
198 data << uint32(sTaxiNodesMask[i]); // all existed nodes
200 else
202 for (uint8 i=0; i<TaxiMaskSize; ++i)
203 data << uint32(m_taximask[i]); // known nodes
207 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
209 ClearTaxiDestinations();
211 Tokens tokens = StrSplit(values," ");
213 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
215 uint32 node = uint32(atol(iter->c_str()));
216 AddTaxiDestination(node);
219 if(m_TaxiDestinations.empty())
220 return true;
222 // Check integrity
223 if(m_TaxiDestinations.size() < 2)
224 return false;
226 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
228 uint32 cost;
229 uint32 path;
230 sObjectMgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
231 if(!path)
232 return false;
235 // can't load taxi path without mount set (quest taxi path?)
236 if(!sObjectMgr.GetTaxiMountDisplayId(GetTaxiSource(),team,true))
237 return false;
239 return true;
242 std::string PlayerTaxi::SaveTaxiDestinationsToString()
244 if(m_TaxiDestinations.empty())
245 return "";
247 std::ostringstream ss;
249 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
250 ss << m_TaxiDestinations[i] << " ";
252 return ss.str();
255 uint32 PlayerTaxi::GetCurrentTaxiPath() const
257 if(m_TaxiDestinations.size() < 2)
258 return 0;
260 uint32 path;
261 uint32 cost;
263 sObjectMgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
265 return path;
268 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
270 ss << "'";
271 for(int i = 0; i < TaxiMaskSize; ++i)
272 ss << taxi.m_taximask[i] << " ";
273 ss << "'";
274 return ss;
277 SpellModifier::SpellModifier( SpellModOp _op, SpellModType _type, int32 _value, SpellEntry const* spellEntry, SpellEffectIndex eff, int16 _charges /*= 0*/ ) : op(_op), type(_type), charges(_charges), value(_value), spellId(spellEntry->Id), lastAffected(NULL)
279 uint32 const* ptr = spellEntry->GetEffectSpellClassMask(eff);
280 mask = uint64(ptr[0]) | (uint64(ptr[1]) << 32);
281 mask2= ptr[2];
284 SpellModifier::SpellModifier( SpellModOp _op, SpellModType _type, int32 _value, Aura const* aura, int16 _charges /*= 0*/ ) : op(_op), type(_type), charges(_charges), value(_value), spellId(aura->GetId()), lastAffected(NULL)
286 uint32 const* ptr = aura->getAuraSpellClassMask();
287 mask = uint64(ptr[0]) | (uint64(ptr[1]) << 32);
288 mask2= ptr[2];
291 bool SpellModifier::isAffectedOnSpell( SpellEntry const *spell ) const
293 SpellEntry const *affect_spell = sSpellStore.LookupEntry(spellId);
294 // False if affect_spell == NULL or spellFamily not equal
295 if (!affect_spell || affect_spell->SpellFamilyName != spell->SpellFamilyName)
296 return false;
297 if (mask & spell->SpellFamilyFlags)
298 return true;
299 if (mask2 & spell->SpellFamilyFlags2)
300 return true;
301 return false;
304 //== Player ====================================================
306 UpdateMask Player::updateVisualBits;
308 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
310 m_transport = 0;
312 m_speakTime = 0;
313 m_speakCount = 0;
315 m_objectType |= TYPEMASK_PLAYER;
316 m_objectTypeId = TYPEID_PLAYER;
318 m_valuesCount = PLAYER_END;
320 m_session = session;
322 m_divider = 0;
324 m_ExtraFlags = 0;
325 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
326 SetAcceptTicket(true);
328 // players always accept
329 if(GetSession()->GetSecurity() == SEC_PLAYER)
330 SetAcceptWhispers(true);
332 m_curSelection = 0;
333 m_lootGuid = 0;
335 m_comboTarget = 0;
336 m_comboPoints = 0;
338 m_usedTalentCount = 0;
339 m_questRewardTalentCount = 0;
341 m_regenTimer = 0;
342 m_weaponChangeTimer = 0;
344 m_zoneUpdateId = 0;
345 m_zoneUpdateTimer = 0;
347 m_areaUpdateId = 0;
349 m_nextSave = sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE);
351 // randomize first save time in range [CONFIG_UINT32_INTERVAL_SAVE] around [CONFIG_UINT32_INTERVAL_SAVE]
352 // this must help in case next save after mass player load after server startup
353 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
355 clearResurrectRequestData();
357 m_SpellModRemoveCount = 0;
359 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
361 m_social = NULL;
363 // group is initialized in the reference constructor
364 SetGroupInvite(NULL);
365 m_groupUpdateMask = 0;
366 m_auraUpdateMask = 0;
368 duel = NULL;
370 m_GuildIdInvited = 0;
371 m_ArenaTeamIdInvited = 0;
373 m_atLoginFlags = AT_LOGIN_NONE;
375 mSemaphoreTeleport_Near = false;
376 mSemaphoreTeleport_Far = false;
378 m_DelayedOperations = 0;
379 m_bCanDelayTeleport = false;
380 m_bHasDelayedTeleport = false;
381 m_teleport_options = 0;
383 pTrader = 0;
384 ClearTrade();
386 m_cinematic = 0;
388 PlayerTalkClass = new PlayerMenu( GetSession() );
389 m_currentBuybackSlot = BUYBACK_SLOT_START;
391 m_DailyQuestChanged = false;
392 m_lastDailyQuestTime = 0;
394 for (int i=0; i<MAX_TIMERS; ++i)
395 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
397 m_MirrorTimerFlags = UNDERWATER_NONE;
398 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
399 m_isInWater = false;
400 m_drunkTimer = 0;
401 m_drunk = 0;
402 m_restTime = 0;
403 m_deathTimer = 0;
404 m_deathExpireTime = 0;
406 m_swingErrorMsg = 0;
408 m_DetectInvTimer = 1*IN_MILISECONDS;
410 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
412 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
413 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
416 m_logintime = time(NULL);
417 m_Last_tick = m_logintime;
418 m_WeaponProficiency = 0;
419 m_ArmorProficiency = 0;
420 m_canParry = false;
421 m_canBlock = false;
422 m_canDualWield = false;
423 m_canTitanGrip = false;
424 m_ammoDPS = 0.0f;
426 m_temporaryUnsummonedPetNumber = 0;
427 //cache for UNIT_CREATED_BY_SPELL to allow
428 //returning reagents for temporarily removed pets
429 //when dying/logging out
430 m_oldpetspell = 0;
432 ////////////////////Rest System/////////////////////
433 time_inn_enter=0;
434 inn_pos_mapid=0;
435 inn_pos_x=0;
436 inn_pos_y=0;
437 inn_pos_z=0;
438 m_rest_bonus=0;
439 rest_type=REST_TYPE_NO;
440 ////////////////////Rest System/////////////////////
442 m_mailsUpdated = false;
443 unReadMails = 0;
444 m_nextMailDelivereTime = 0;
446 m_resetTalentsCost = 0;
447 m_resetTalentsTime = 0;
448 m_itemUpdateQueueBlocked = false;
450 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
451 m_forced_speed_changes[i] = 0;
453 m_stableSlots = 0;
455 /////////////////// Instance System /////////////////////
457 m_HomebindTimer = 0;
458 m_InstanceValid = true;
459 m_dungeonDifficulty = DUNGEON_DIFFICULTY_NORMAL;
460 m_raidDifficulty = RAID_DIFFICULTY_10MAN_NORMAL;
462 m_lastPotionId = 0;
464 m_activeSpec = 0;
465 m_specsCount = 1;
467 for (int i = 0; i < BASEMOD_END; ++i)
469 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
470 m_auraBaseMod[i][PCT_MOD] = 1.0f;
473 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
474 m_baseRatingValue[i] = 0;
476 m_baseSpellPower = 0;
477 m_baseFeralAP = 0;
478 m_baseManaRegen = 0;
479 m_armorPenetrationPct = 0.0f;
481 // Honor System
482 m_lastHonorUpdateTime = time(NULL);
484 // Player summoning
485 m_summon_expire = 0;
486 m_summon_mapid = 0;
487 m_summon_x = 0.0f;
488 m_summon_y = 0.0f;
489 m_summon_z = 0.0f;
491 m_mover = this;
493 m_miniPet = 0;
494 m_contestedPvPTimer = 0;
496 m_declinedname = NULL;
497 m_runes = NULL;
499 m_lastFallTime = 0;
500 m_lastFallZ = 0;
503 Player::~Player ()
505 CleanupsBeforeDelete();
507 // it must be unloaded already in PlayerLogout and accessed only for loggined player
508 //m_social = NULL;
510 // Note: buy back item already deleted from DB when player was saved
511 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
513 if(m_items[i])
514 delete m_items[i];
516 CleanupChannels();
518 //all mailed items should be deleted, also all mail should be deallocated
519 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
520 delete *itr;
522 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
523 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
525 delete PlayerTalkClass;
527 if (m_transport)
529 m_transport->RemovePassenger(this);
532 for(size_t x = 0; x < ItemSetEff.size(); x++)
533 if(ItemSetEff[x])
534 delete ItemSetEff[x];
536 // clean up player-instance binds, may unload some instance saves
537 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
538 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
539 itr->second.save->RemovePlayer(this);
541 delete m_declinedname;
542 delete m_runes;
545 void Player::CleanupsBeforeDelete()
547 if(m_uint32Values) // only for fully created Object
549 TradeCancel(false);
550 DuelComplete(DUEL_INTERUPTED);
552 Unit::CleanupsBeforeDelete();
555 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 */)
557 //FIXME: outfitId not used in player creating
559 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
561 m_name = name;
563 PlayerInfo const* info = sObjectMgr.GetPlayerInfo(race, class_);
564 if(!info)
566 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
567 return false;
570 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
571 m_items[i] = NULL;
573 SetLocationMapId(info->mapId);
574 Relocate(info->positionX,info->positionY,info->positionZ);
576 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
577 if(!cEntry)
579 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
580 return false;
583 SetMap(sMapMgr.CreateMap(info->mapId, this));
585 uint8 powertype = cEntry->powerType;
587 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
588 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
590 setFactionForRace(race);
592 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
594 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
595 InitDisplayIds();
596 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
597 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
598 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
599 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
600 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
602 // -1 is default value
603 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, -1);
605 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
606 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
607 SetByteValue(PLAYER_BYTES_3, 0, gender);
609 SetUInt32Value( PLAYER_GUILDID, 0 );
610 SetUInt32Value( PLAYER_GUILDRANK, 0 );
611 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
613 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
614 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
615 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 0 ); // 0=disabled
616 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
617 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
618 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
619 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
620 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
622 // set starting level
623 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
624 ? sWorld.getConfig(CONFIG_UINT32_START_PLAYER_LEVEL)
625 : sWorld.getConfig(CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL);
627 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
629 uint32 gm_level = sWorld.getConfig(CONFIG_UINT32_START_GM_LEVEL);
630 if(gm_level > start_level)
631 start_level = gm_level;
634 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
636 InitRunes();
638 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_UINT32_START_PLAYER_MONEY));
639 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_UINT32_START_HONOR_POINTS));
640 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_UINT32_START_ARENA_POINTS));
642 // Played time
643 m_Last_tick = time(NULL);
644 m_Played_time[PLAYED_TIME_TOTAL] = 0;
645 m_Played_time[PLAYED_TIME_LEVEL] = 0;
647 // base stats and related field values
648 InitStatsForLevel();
649 InitTaxiNodesForLevel();
650 InitGlyphsForLevel();
651 InitTalentForLevel();
652 InitPrimaryProfessions(); // to max set before any spell added
654 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
655 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
656 SetHealth(GetMaxHealth());
657 if (getPowerType()==POWER_MANA)
659 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
660 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
663 if(getPowerType() == POWER_RUNIC_POWER)
665 SetPower(POWER_RUNE, 8);
666 SetMaxPower(POWER_RUNE, 8);
667 SetPower(POWER_RUNIC_POWER, 0);
668 SetMaxPower(POWER_RUNIC_POWER, 1000);
671 // original spells
672 learnDefaultSpells();
674 // original action bar
675 for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
676 addActionButton(0, action_itr->button,action_itr->action,action_itr->type);
678 // original items
679 CharStartOutfitEntry const* oEntry = NULL;
680 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
682 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
684 if(entry->RaceClassGender == RaceClassGender)
686 oEntry = entry;
687 break;
692 if(oEntry)
694 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
696 if(oEntry->ItemId[j] <= 0)
697 continue;
699 uint32 item_id = oEntry->ItemId[j];
701 // just skip, reported in ObjectMgr::LoadItemPrototypes
702 ItemPrototype const* iProto = ObjectMgr::GetItemPrototype(item_id);
703 if(!iProto)
704 continue;
706 // BuyCount by default
707 int32 count = iProto->BuyCount;
709 // special amount for foor/drink
710 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
712 switch(iProto->Spells[0].SpellCategory)
714 case 11: // food
715 count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4;
716 break;
717 case 59: // drink
718 count = 2;
719 break;
721 if(iProto->Stackable < count)
722 count = iProto->Stackable;
724 // special amount for daggers
725 else if(iProto->Class==ITEM_CLASS_WEAPON && iProto->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER)
727 count = 2; // will placed to 2 slots
730 StoreNewItemInBestSlots(item_id, count);
734 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
735 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
737 // bags and main-hand weapon must equipped at this moment
738 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
739 // or ammo not equipped in special bag
740 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
742 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
744 uint16 eDest;
745 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
746 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
747 if( msg == EQUIP_ERR_OK )
749 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
750 EquipItem( eDest, pItem, true);
752 // move other items to more appropriate slots (ammo not equipped in special bag)
753 else
755 ItemPosCountVec sDest;
756 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
757 if( msg == EQUIP_ERR_OK )
759 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
760 pItem = StoreItem( sDest, pItem, true);
763 // if this is ammo then use it
764 msg = CanUseAmmo( pItem->GetEntry() );
765 if( msg == EQUIP_ERR_OK )
766 SetAmmo( pItem->GetEntry() );
770 // all item positions resolved
772 return true;
775 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
777 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
779 // attempt equip by one
780 while(titem_amount > 0)
782 uint16 eDest;
783 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
784 if( msg != EQUIP_ERR_OK )
785 break;
787 EquipNewItem( eDest, titem_id, true);
788 AutoUnequipOffhandIfNeed();
789 --titem_amount;
792 if(titem_amount == 0)
793 return true; // equipped
795 // attempt store
796 ItemPosCountVec sDest;
797 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
798 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
799 if( msg == EQUIP_ERR_OK )
801 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
802 return true; // stored
805 // item can't be added
806 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
807 return false;
810 // helper function, mainly for script side, but can be used for simple task in mangos also.
811 Item* Player::StoreNewItemInInventorySlot(uint32 itemEntry, uint32 amount)
813 ItemPosCountVec vDest;
815 uint8 msg = CanStoreNewItem(INVENTORY_SLOT_BAG_0, NULL_SLOT, vDest, itemEntry, amount);
817 if (msg == EQUIP_ERR_OK)
819 if (Item* pItem = StoreNewItem(vDest, itemEntry, true, Item::GenerateItemRandomPropertyId(itemEntry)))
820 return pItem;
823 return NULL;
826 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
828 if (int(MaxValue) == DISABLED_MIRROR_TIMER)
830 if (int(CurrentValue) != DISABLED_MIRROR_TIMER)
831 StopMirrorTimer(Type);
832 return;
834 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
835 data << (uint32)Type;
836 data << CurrentValue;
837 data << MaxValue;
838 data << Regen;
839 data << (uint8)0;
840 data << (uint32)0; // spell id
841 GetSession()->SendPacket( &data );
844 void Player::StopMirrorTimer(MirrorTimerType Type)
846 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
847 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
848 data << (uint32)Type;
849 GetSession()->SendPacket( &data );
852 uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
854 if(!isAlive() || isGameMaster())
855 return 0;
857 // Absorb, resist some environmental damage type
858 uint32 absorb = 0;
859 uint32 resist = 0;
860 if (type == DAMAGE_LAVA)
861 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
862 else if (type == DAMAGE_SLIME)
863 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
865 damage-=absorb+resist;
867 DealDamageMods(this,damage,&absorb);
869 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
870 data << uint64(GetGUID());
871 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
872 data << uint32(damage);
873 data << uint32(absorb);
874 data << uint32(resist);
875 SendMessageToSet(&data, true);
877 uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
879 if(!isAlive())
881 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
883 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
884 DurabilityLossAll(0.10f,false);
885 // durability lost message
886 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
887 GetSession()->SendPacket(&data2);
890 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
893 return final_damage;
896 int32 Player::getMaxTimer(MirrorTimerType timer)
898 switch (timer)
900 case FATIGUE_TIMER:
901 if (GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_GMLEVEL))
902 return DISABLED_MIRROR_TIMER;
903 return sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_MAX)*IN_MILISECONDS;
904 case BREATH_TIMER:
906 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) ||
907 GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_GMLEVEL))
908 return DISABLED_MIRROR_TIMER;
909 int32 UnderWaterTime = sWorld.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_MAX)*IN_MILISECONDS;
910 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
911 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
912 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
913 return UnderWaterTime;
915 case FIRE_TIMER:
917 if (!isAlive() || GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_GMLEVEL))
918 return DISABLED_MIRROR_TIMER;
919 return sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_MAX)*IN_MILISECONDS;
921 default:
922 return 0;
924 return 0;
927 void Player::UpdateMirrorTimers()
929 // Desync flags for update on next HandleDrowning
930 if (m_MirrorTimerFlags)
931 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
934 void Player::HandleDrowning(uint32 time_diff)
936 if (!m_MirrorTimerFlags)
937 return;
939 // In water
940 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
942 // Breath timer not activated - activate it
943 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
945 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
946 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
948 else // If activated - do tick
950 m_MirrorTimer[BREATH_TIMER]-=time_diff;
951 // Timer limit - need deal damage
952 if (m_MirrorTimer[BREATH_TIMER] < 0)
954 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
955 // Calculate and deal damage
956 // TODO: Check this formula
957 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
958 EnvironmentalDamage(DAMAGE_DROWNING, damage);
960 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
961 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
964 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
966 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
967 // Need breath regen
968 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
969 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
970 StopMirrorTimer(BREATH_TIMER);
971 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
972 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
975 // In dark water
976 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
978 // Fatigue timer not activated - activate it
979 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
981 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
982 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
984 else
986 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
987 // Timer limit - need deal damage or teleport ghost to graveyard
988 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
990 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
991 if (isAlive()) // Calculate and deal damage
993 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
994 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
996 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
997 RepopAtGraveyard();
999 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
1000 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
1003 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
1005 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
1006 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
1007 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
1008 StopMirrorTimer(FATIGUE_TIMER);
1009 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
1010 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
1013 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
1015 // Breath timer not activated - activate it
1016 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
1017 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
1018 else
1020 m_MirrorTimer[FIRE_TIMER]-=time_diff;
1021 if (m_MirrorTimer[FIRE_TIMER] < 0)
1023 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
1024 // Calculate and deal damage
1025 // TODO: Check this formula
1026 uint32 damage = urand(600, 700);
1027 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
1028 EnvironmentalDamage(DAMAGE_LAVA, damage);
1029 else
1030 EnvironmentalDamage(DAMAGE_SLIME, damage);
1034 else
1035 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
1037 // Recheck timers flag
1038 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1039 for (int i = 0; i< MAX_TIMERS; ++i)
1040 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1042 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1043 break;
1045 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1048 ///The player sobers by 256 every 10 seconds
1049 void Player::HandleSobering()
1051 m_drunkTimer = 0;
1053 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1054 SetDrunkValue(drunk);
1057 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1059 if(value >= 23000)
1060 return DRUNKEN_SMASHED;
1061 if(value >= 12800)
1062 return DRUNKEN_DRUNK;
1063 if(value & 0xFFFE)
1064 return DRUNKEN_TIPSY;
1065 return DRUNKEN_SOBER;
1068 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1070 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1072 m_drunk = newDrunkenValue;
1073 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1075 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1077 // special drunk invisibility detection
1078 if(newDrunkenState >= DRUNKEN_DRUNK)
1079 m_detectInvisibilityMask |= (1<<6);
1080 else
1081 m_detectInvisibilityMask &= ~(1<<6);
1083 if(newDrunkenState == oldDrunkenState)
1084 return;
1086 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1087 data << uint64(GetGUID());
1088 data << uint32(newDrunkenState);
1089 data << uint32(itemId);
1091 SendMessageToSet(&data, true);
1094 void Player::Update( uint32 p_time )
1096 if(!IsInWorld())
1097 return;
1099 // undelivered mail
1100 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1102 SendNewMail();
1103 ++unReadMails;
1105 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1106 m_nextMailDelivereTime = 0;
1109 //used to implement delayed far teleports
1110 SetCanDelayTeleport(true);
1111 Unit::Update( p_time );
1112 SetCanDelayTeleport(false);
1114 // update player only attacks
1115 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1117 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1120 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1122 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1125 time_t now = time (NULL);
1127 UpdatePvPFlag(now);
1129 UpdateContestedPvP(p_time);
1131 UpdateDuelFlag(now);
1133 CheckDuelDistance(now);
1135 UpdateAfkReport(now);
1137 // Update items that have just a limited lifetime
1138 if (now>m_Last_tick)
1139 UpdateItemDuration(uint32(now- m_Last_tick));
1141 if (!m_timedquests.empty())
1143 std::set<uint32>::iterator iter = m_timedquests.begin();
1144 while (iter != m_timedquests.end())
1146 QuestStatusData& q_status = mQuestStatus[*iter];
1147 if( q_status.m_timer <= p_time )
1149 uint32 quest_id = *iter;
1150 ++iter; // current iter will be removed in FailQuest
1151 FailQuest(quest_id);
1153 else
1155 q_status.m_timer -= p_time;
1156 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1157 ++iter;
1162 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1164 Unit *pVictim = getVictim();
1165 if (pVictim && !IsNonMeleeSpellCasted(false))
1167 // default combat reach 10
1168 // TODO add weapon,skill check
1170 float pldistance = ATTACK_DISTANCE;
1172 if (isAttackReady(BASE_ATTACK))
1174 if(!IsWithinDistInMap(pVictim, pldistance))
1176 setAttackTimer(BASE_ATTACK,100);
1177 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1179 SendAttackSwingNotInRange();
1180 m_swingErrorMsg = 1;
1183 //120 degrees of radiant range
1184 else if( !HasInArc( 2*M_PI_F/3, pVictim ))
1186 setAttackTimer(BASE_ATTACK,100);
1187 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1189 SendAttackSwingBadFacingAttack();
1190 m_swingErrorMsg = 2;
1193 else
1195 m_swingErrorMsg = 0; // reset swing error state
1197 // prevent base and off attack in same time, delay attack at 0.2 sec
1198 if(haveOffhandWeapon())
1200 uint32 off_att = getAttackTimer(OFF_ATTACK);
1201 if(off_att < ATTACK_DISPLAY_DELAY)
1202 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1204 AttackerStateUpdate(pVictim, BASE_ATTACK);
1205 resetAttackTimer(BASE_ATTACK);
1209 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1211 if(!IsWithinDistInMap(pVictim, pldistance))
1213 setAttackTimer(OFF_ATTACK,100);
1215 else if( !HasInArc( 2*M_PI_F/3, pVictim ))
1217 setAttackTimer(OFF_ATTACK,100);
1219 else
1221 // prevent base and off attack in same time, delay attack at 0.2 sec
1222 uint32 base_att = getAttackTimer(BASE_ATTACK);
1223 if(base_att < ATTACK_DISPLAY_DELAY)
1224 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1225 // do attack
1226 AttackerStateUpdate(pVictim, OFF_ATTACK);
1227 resetAttackTimer(OFF_ATTACK);
1231 Unit *owner = pVictim->GetOwner();
1232 Unit *u = owner ? owner : pVictim;
1233 if(u->IsPvP() && (!duel || duel->opponent != u))
1235 UpdatePvP(true);
1236 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1241 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1243 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1245 time_t time_inn = time(NULL)-GetTimeInnEnter();
1246 if (time_inn >= 10) //freeze update
1248 float bubble = 0.125f*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_INGAME);
1249 //speed collect rest bonus (section/in hour)
1250 SetRestBonus( float(GetRestBonus()+ time_inn*(GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble ));
1251 UpdateInnerTime(time(NULL));
1256 if (m_regenTimer)
1258 if(p_time >= m_regenTimer)
1259 m_regenTimer = 0;
1260 else
1261 m_regenTimer -= p_time;
1264 if (m_weaponChangeTimer > 0)
1266 if(p_time >= m_weaponChangeTimer)
1267 m_weaponChangeTimer = 0;
1268 else
1269 m_weaponChangeTimer -= p_time;
1272 if (m_zoneUpdateTimer > 0)
1274 if(p_time >= m_zoneUpdateTimer)
1276 uint32 newzone, newarea;
1277 GetZoneAndAreaId(newzone,newarea);
1279 if( m_zoneUpdateId != newzone )
1280 UpdateZone(newzone,newarea); // also update area
1281 else
1283 // use area updates as well
1284 // needed for free far all arenas for example
1285 if( m_areaUpdateId != newarea )
1286 UpdateArea(newarea);
1288 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1291 else
1292 m_zoneUpdateTimer -= p_time;
1295 if (isAlive())
1297 // if no longer casting, set regen power as soon as it is up.
1298 if (!IsUnderLastManaUseEffect())
1299 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
1301 if (!m_regenTimer)
1302 RegenerateAll();
1305 if (m_deathState == JUST_DIED)
1307 KillPlayer();
1310 if(m_nextSave > 0)
1312 if(p_time >= m_nextSave)
1314 // m_nextSave reseted in SaveToDB call
1315 SaveToDB();
1316 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1318 else
1320 m_nextSave -= p_time;
1324 //Handle Water/drowning
1325 HandleDrowning(p_time);
1327 //Handle detect stealth players
1328 if (m_DetectInvTimer > 0)
1330 if (p_time >= m_DetectInvTimer)
1332 HandleStealthedUnitsDetection();
1333 m_DetectInvTimer = 3000;
1335 else
1336 m_DetectInvTimer -= p_time;
1339 // Played time
1340 if (now > m_Last_tick)
1342 uint32 elapsed = uint32(now - m_Last_tick);
1343 m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
1344 m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
1345 m_Last_tick = now;
1348 if (m_drunk)
1350 m_drunkTimer += p_time;
1352 if (m_drunkTimer > 10*IN_MILISECONDS)
1353 HandleSobering();
1356 // not auto-free ghost from body in instances
1357 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1359 if(p_time >= m_deathTimer)
1361 m_deathTimer = 0;
1362 BuildPlayerRepop();
1363 RepopAtGraveyard();
1365 else
1366 m_deathTimer -= p_time;
1369 UpdateEnchantTime(p_time);
1370 UpdateHomebindTime(p_time);
1372 // group update
1373 SendUpdateToOutOfRangeGroupMembers();
1375 Pet* pet = GetPet();
1376 if(pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1378 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1381 //we should execute delayed teleports only for alive(!) players
1382 //because we don't want player's ghost teleported from graveyard
1383 if(IsHasDelayedTeleport() && isAlive())
1384 TeleportTo(m_teleport_dest, m_teleport_options);
1387 void Player::setDeathState(DeathState s)
1389 uint32 ressSpellId = 0;
1391 bool cur = isAlive();
1393 if(s == JUST_DIED && cur)
1395 // drunken state is cleared on death
1396 SetDrunkValue(0);
1397 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1398 ClearComboPoints();
1400 clearResurrectRequestData();
1402 // remove form before other mods to prevent incorrect stats calculation
1403 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1405 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1406 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1408 // remove uncontrolled pets
1409 RemoveMiniPet();
1411 // save value before aura remove in Unit::setDeathState
1412 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1414 // passive spell
1415 if(!ressSpellId)
1416 ressSpellId = GetResurrectionSpellId();
1417 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1418 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1419 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1421 Unit::setDeathState(s);
1423 // restore resurrection spell id for player after aura remove
1424 if(s == JUST_DIED && cur && ressSpellId)
1425 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1427 if(isAlive() && !cur)
1429 //clear aura case after resurrection by another way (spells will be applied before next death)
1430 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1432 // restore default warrior stance
1433 if(getClass()== CLASS_WARRIOR)
1434 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1438 bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1440 // 0 1 2 3 4 5 6 7
1441 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
1442 // 8 9 10 11 12 13 14
1443 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
1444 // 15 16 17 18 19 20
1445 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive "
1447 Field *fields = result->Fetch();
1449 uint32 guid = fields[0].GetUInt32();
1450 uint8 pRace = fields[2].GetUInt8();
1451 uint8 pClass = fields[3].GetUInt8();
1453 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(pRace, pClass);
1454 if(!info)
1456 sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
1457 return false;
1460 *p_data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
1461 *p_data << fields[1].GetString(); // name
1462 *p_data << uint8(pRace); // race
1463 *p_data << uint8(pClass); // class
1464 *p_data << uint8(fields[4].GetUInt8()); // gender
1466 uint32 playerBytes = fields[5].GetUInt32();
1467 *p_data << uint8(playerBytes); // skin
1468 *p_data << uint8(playerBytes >> 8); // face
1469 *p_data << uint8(playerBytes >> 16); // hair style
1470 *p_data << uint8(playerBytes >> 24); // hair color
1472 uint32 playerBytes2 = fields[6].GetUInt32();
1473 *p_data << uint8(playerBytes2 & 0xFF); // facial hair
1475 *p_data << uint8(fields[7].GetUInt8()); // level
1476 *p_data << uint32(fields[8].GetUInt32()); // zone
1477 *p_data << uint32(fields[9].GetUInt32()); // map
1479 *p_data << fields[10].GetFloat(); // x
1480 *p_data << fields[11].GetFloat(); // y
1481 *p_data << fields[12].GetFloat(); // z
1483 *p_data << uint32(fields[13].GetUInt32()); // guild id
1485 uint32 char_flags = 0;
1486 uint32 playerFlags = fields[14].GetUInt32();
1487 uint32 atLoginFlags = fields[15].GetUInt32();
1488 if(playerFlags & PLAYER_FLAGS_HIDE_HELM)
1489 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1490 if(playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
1491 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1492 if(playerFlags & PLAYER_FLAGS_GHOST)
1493 char_flags |= CHARACTER_FLAG_GHOST;
1494 if(atLoginFlags & AT_LOGIN_RENAME)
1495 char_flags |= CHARACTER_FLAG_RENAME;
1496 if(sWorld.getConfig(CONFIG_BOOL_DECLINED_NAMES_USED))
1498 if(!fields[20].GetCppString().empty())
1499 char_flags |= CHARACTER_FLAG_DECLINED;
1501 else
1502 char_flags |= CHARACTER_FLAG_DECLINED;
1504 *p_data << uint32(char_flags); // character flags
1505 // character customize flags
1506 *p_data << uint32(atLoginFlags & AT_LOGIN_CUSTOMIZE ? CHAR_CUSTOMIZE_FLAG_CUSTOMIZE : CHAR_CUSTOMIZE_FLAG_NONE);
1507 // First login
1508 *p_data << uint8(atLoginFlags & AT_LOGIN_FIRST ? 1 : 0);
1510 // Pets info
1512 uint32 petDisplayId = 0;
1513 uint32 petLevel = 0;
1514 uint32 petFamily = 0;
1516 // show pet at selection character in character list only for non-ghost character
1517 if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1519 uint32 entry = fields[16].GetUInt32();
1520 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1521 if(cInfo)
1523 petDisplayId = fields[17].GetUInt32();
1524 petLevel = fields[18].GetUInt32();
1525 petFamily = cInfo->family;
1529 *p_data << uint32(petDisplayId);
1530 *p_data << uint32(petLevel);
1531 *p_data << uint32(petFamily);
1534 // TODO: do not access data field here
1535 Tokens data = StrSplit(fields[19].GetCppString(), " ");
1537 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1539 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1540 uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
1541 const ItemPrototype * proto = ObjectMgr::GetItemPrototype(item_id);
1542 if(!proto)
1544 *p_data << uint32(0);
1545 *p_data << uint8(0);
1546 *p_data << uint32(0);
1547 continue;
1550 SpellItemEnchantmentEntry const *enchant = NULL;
1552 uint32 enchants = GetUInt32ValueFromArray(data, visualbase + 1);
1553 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1555 // values stored in 2 uint16
1556 uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16);
1557 if(!enchantId)
1558 continue;
1560 if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId)))
1561 break;
1564 *p_data << uint32(proto->DisplayInfoID);
1565 *p_data << uint8(proto->InventoryType);
1566 *p_data << uint32(enchant ? enchant->aura_id : 0);
1568 *p_data << uint32(0); // first bag display id
1569 *p_data << uint8(0); // first bag inventory type
1570 *p_data << uint32(0); // enchant?
1572 return true;
1575 bool Player::ToggleAFK()
1577 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1579 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1581 // afk player not allowed in battleground
1582 if(state && InBattleGround())
1583 LeaveBattleground();
1585 return state;
1588 bool Player::ToggleDND()
1590 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1592 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1595 uint8 Player::chatTag() const
1597 // it's bitmask
1598 // 0x8 - ??
1599 // 0x4 - gm
1600 // 0x2 - dnd
1601 // 0x1 - afk
1602 if(isGMChat())
1603 return 4;
1604 else if(isDND())
1605 return 3;
1606 if(isAFK())
1607 return 1;
1608 else
1609 return 0;
1612 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1614 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1616 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1617 return false;
1620 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1621 Pet* pet = GetPet();
1623 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1625 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1626 // don't let gm level > 1 either
1627 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1628 return false;
1630 // client without expansion support
1631 if(GetSession()->Expansion() < mEntry->Expansion())
1633 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1635 if(GetTransport())
1636 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1638 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1640 return false; // normal client can't teleport to this map...
1642 else
1644 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1647 // if we were on a transport, leave
1648 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1650 m_transport->RemovePassenger(this);
1651 m_transport = NULL;
1652 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
1655 // The player was ported to another map and looses the duel immediately.
1656 // We have to perform this check before the teleport, otherwise the
1657 // ObjectAccessor won't find the flag.
1658 if (duel && GetMapId() != mapid)
1660 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1661 if (obj)
1662 DuelComplete(DUEL_FLED);
1665 // reset movement flags at teleport, because player will continue move with these flags after teleport
1666 m_movementInfo.SetMovementFlags(MOVEFLAG_NONE);
1668 if ((GetMapId() == mapid) && (!m_transport))
1670 //lets reset far teleport flag if it wasn't reset during chained teleports
1671 SetSemaphoreTeleportFar(false);
1672 //setup delayed teleport flag
1673 SetDelayedTeleportFlag(IsCanDelayTeleport());
1674 //if teleport spell is casted in Unit::Update() func
1675 //then we need to delay it until update process will be finished
1676 if(IsHasDelayedTeleport())
1678 SetSemaphoreTeleportNear(true);
1679 //lets save teleport destination for player
1680 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1681 m_teleport_options = options;
1682 return true;
1685 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1687 //same map, only remove pet if out of range for new position
1688 if(pet && !pet->IsWithinDist3d(x, y, z, GetMap()->GetVisibilityDistance()))
1689 UnsummonPetTemporaryIfAny();
1692 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1693 CombatStop();
1695 // this will be used instead of the current location in SaveToDB
1696 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1697 SetFallInformation(0, z);
1699 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1700 // at client packet MSG_MOVE_TELEPORT_ACK
1701 SetSemaphoreTeleportNear(true);
1702 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1703 if(!GetSession()->PlayerLogout())
1705 WorldPacket data;
1706 BuildTeleportAckMsg(&data, x, y, z, orientation);
1707 GetSession()->SendPacket(&data);
1710 else
1712 // far teleport to another map
1713 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1714 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1716 // Check enter rights before map getting to avoid creating instance copy for player
1717 // this check not dependent from map instance copy and same for all instance copies of selected map
1718 if (!sMapMgr.CanPlayerEnter(mapid, this))
1719 return false;
1721 // If the map is not created, assume it is possible to enter it.
1722 // It will be created in the WorldPortAck.
1723 Map *map = sMapMgr.FindMap(mapid);
1724 if (!map || map->CanEnter(this))
1726 //lets reset near teleport flag if it wasn't reset during chained teleports
1727 SetSemaphoreTeleportNear(false);
1728 //setup delayed teleport flag
1729 SetDelayedTeleportFlag(IsCanDelayTeleport());
1730 //if teleport spell is casted in Unit::Update() func
1731 //then we need to delay it until update process will be finished
1732 if(IsHasDelayedTeleport())
1734 SetSemaphoreTeleportFar(true);
1735 //lets save teleport destination for player
1736 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1737 m_teleport_options = options;
1738 return true;
1741 SetSelection(0);
1743 CombatStop();
1745 ResetContestedPvP();
1747 // remove player from battleground on far teleport (when changing maps)
1748 if(BattleGround const* bg = GetBattleGround())
1750 // Note: at battleground join battleground id set before teleport
1751 // and we already will found "current" battleground
1752 // just need check that this is targeted map or leave
1753 if(bg->GetMapId() != mapid)
1754 LeaveBattleground(false); // don't teleport to entry point
1757 // remove pet on map change
1758 if (pet)
1759 UnsummonPetTemporaryIfAny();
1761 // remove all dyn objects
1762 RemoveAllDynObjects();
1764 // stop spellcasting
1765 // not attempt interrupt teleportation spell at caster teleport
1766 if(!(options & TELE_TO_SPELL))
1767 if(IsNonMeleeSpellCasted(true))
1768 InterruptNonMeleeSpells(true);
1770 //remove auras before removing from map...
1771 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1773 if(!GetSession()->PlayerLogout())
1775 // send transfer packets
1776 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1777 data << uint32(mapid);
1778 if (m_transport)
1780 data << uint32(m_transport->GetEntry());
1781 data << uint32(GetMapId());
1783 GetSession()->SendPacket(&data);
1785 data.Initialize(SMSG_NEW_WORLD, (20));
1786 if (m_transport)
1788 data << uint32(mapid);
1789 data << float(m_movementInfo.GetTransportPos()->x);
1790 data << float(m_movementInfo.GetTransportPos()->y);
1791 data << float(m_movementInfo.GetTransportPos()->z);
1792 data << float(m_movementInfo.GetTransportPos()->o);
1794 else
1796 data << uint32(mapid);
1797 data << float(x);
1798 data << float(y);
1799 data << float(z);
1800 data << float(orientation);
1802 GetSession()->SendPacket( &data );
1803 SendSavedInstances();
1806 // remove from old map now
1807 if(oldmap)
1808 oldmap->Remove(this, false);
1810 // new final coordinates
1811 float final_x = x;
1812 float final_y = y;
1813 float final_z = z;
1814 float final_o = orientation;
1816 if(m_transport)
1818 final_x += m_movementInfo.GetTransportPos()->x;
1819 final_y += m_movementInfo.GetTransportPos()->y;
1820 final_z += m_movementInfo.GetTransportPos()->z;
1821 final_o += m_movementInfo.GetTransportPos()->o;
1824 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1825 SetFallInformation(0, final_z);
1826 // if the player is saved before worldport ack (at logout for example)
1827 // this will be used instead of the current location in SaveToDB
1829 // move packet sent by client always after far teleport
1830 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1831 SetSemaphoreTeleportFar(true);
1833 else
1834 return false;
1836 return true;
1839 bool Player::TeleportToBGEntryPoint()
1841 ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
1842 ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
1843 return TeleportTo(m_bgData.joinPos);
1846 void Player::ProcessDelayedOperations()
1848 if(m_DelayedOperations == 0)
1849 return;
1851 if(m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
1853 ResurrectPlayer(0.0f, false);
1855 if(GetMaxHealth() > m_resurrectHealth)
1856 SetHealth( m_resurrectHealth );
1857 else
1858 SetHealth( GetMaxHealth() );
1860 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
1861 SetPower(POWER_MANA, m_resurrectMana );
1862 else
1863 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
1865 SetPower(POWER_RAGE, 0 );
1866 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
1868 SpawnCorpseBones();
1871 if(m_DelayedOperations & DELAYED_SAVE_PLAYER)
1873 SaveToDB();
1876 if(m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
1878 CastSpell(this, 26013, true); // Deserter
1881 if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
1883 if (m_bgData.mountSpell)
1885 CastSpell(this, m_bgData.mountSpell, true);
1886 m_bgData.mountSpell = 0;
1890 if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
1892 if (m_bgData.HasTaxiPath())
1894 m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
1895 m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
1896 m_bgData.ClearTaxiPath();
1898 ContinueTaxiFlight();
1902 //we have executed ALL delayed ops, so clear the flag
1903 m_DelayedOperations = 0;
1906 void Player::AddToWorld()
1908 ///- Do not add/remove the player from the object storage
1909 ///- It will crash when updating the ObjectAccessor
1910 ///- The player should only be added when logging in
1911 Unit::AddToWorld();
1913 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1915 if(m_items[i])
1916 m_items[i]->AddToWorld();
1920 void Player::RemoveFromWorld()
1922 // cleanup
1923 if(IsInWorld())
1925 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1926 UnsummonAllTotems();
1927 RemoveMiniPet();
1930 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1932 if(m_items[i])
1933 m_items[i]->RemoveFromWorld();
1936 ///- Do not add/remove the player from the object storage
1937 ///- It will crash when updating the ObjectAccessor
1938 ///- The player should only be removed when logging out
1939 Unit::RemoveFromWorld();
1942 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1944 float addRage;
1946 float rageconversion = float((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911f;
1948 if(attacker)
1950 addRage = ((damage/rageconversion*7.5f + weaponSpeedHitFactor)/2.0f);
1952 // talent who gave more rage on attack
1953 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1955 else
1957 addRage = damage/rageconversion*2.5f;
1959 // Berserker Rage effect
1960 if (HasAura(18499, EFFECT_INDEX_0))
1961 addRage *= 1.3f;
1964 addRage *= sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_INCOME);
1966 ModifyPower(POWER_RAGE, uint32(addRage*10));
1969 void Player::RegenerateAll(uint32 diff)
1971 // Not in combat or they have regeneration
1972 if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1973 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1975 RegenerateHealth(diff);
1976 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1978 Regenerate(POWER_RAGE, diff);
1979 if(getClass() == CLASS_DEATH_KNIGHT)
1980 Regenerate(POWER_RUNIC_POWER, diff);
1984 Regenerate(POWER_ENERGY, diff);
1986 Regenerate(POWER_MANA, diff);
1988 if (getClass() == CLASS_DEATH_KNIGHT)
1989 Regenerate(POWER_RUNE, diff);
1991 m_regenTimer = REGEN_TIME_FULL;
1994 // diff contains the time in milliseconds since last regen.
1995 void Player::Regenerate(Powers power, uint32 diff)
1997 uint32 curValue = GetPower(power);
1998 uint32 maxValue = GetMaxPower(power);
2000 float addvalue = 0.0f;
2002 switch (power)
2004 case POWER_MANA:
2006 bool recentCast = IsUnderLastManaUseEffect();
2007 float ManaIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_MANA);
2008 if (recentCast)
2010 // Mangos Updates Mana in intervals of 2s, which is correct
2011 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
2013 else
2015 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
2017 } break;
2018 case POWER_RAGE: // Regenerate rage
2020 float RageDecreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_LOSS);
2021 addvalue = 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
2022 } break;
2023 case POWER_ENERGY: // Regenerate energy (rogue)
2024 addvalue = 20;
2025 break;
2026 case POWER_RUNIC_POWER:
2028 float RunicPowerDecreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RUNICPOWER_LOSS);
2029 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
2030 } break;
2031 case POWER_RUNE:
2033 if (getClass() != CLASS_DEATH_KNIGHT)
2034 break;
2036 for(uint32 rune = 0; rune < MAX_RUNES; ++rune)
2038 if(uint16 cd = GetRuneCooldown(rune)) // if we have cooldown, reduce it...
2040 uint32 cd_diff = diff;
2041 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
2042 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
2043 if ((*i)->GetModifier()->m_miscvalue == power && (*i)->GetMiscBValue()==GetCurrentRune(rune))
2044 cd_diff = cd_diff * ((*i)->GetModifier()->m_amount + 100) / 100.0f;
2046 SetRuneCooldown(rune, (cd < cd_diff) ? 0 : cd - cd_diff);
2049 } break;
2050 case POWER_FOCUS:
2051 case POWER_HAPPINESS:
2052 case POWER_HEALTH:
2053 break;
2056 // Mana regen calculated in Player::UpdateManaRegen()
2057 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
2058 if(power != POWER_MANA)
2060 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
2061 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
2062 if ((*i)->GetModifier()->m_miscvalue == power)
2063 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
2066 // addvalue computed on a 2sec basis. => update to diff time
2067 addvalue *= float(diff) / REGEN_TIME_FULL;
2069 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
2071 curValue += uint32(addvalue);
2072 if (curValue > maxValue)
2073 curValue = maxValue;
2075 else
2077 if(curValue <= uint32(addvalue))
2078 curValue = 0;
2079 else
2080 curValue -= uint32(addvalue);
2082 SetPower(power, curValue);
2085 void Player::RegenerateHealth(uint32 diff)
2087 uint32 curValue = GetHealth();
2088 uint32 maxValue = GetMaxHealth();
2090 if (curValue >= maxValue) return;
2092 float HealthIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_HEALTH);
2094 float addvalue = 0.0f;
2096 // polymorphed case
2097 if ( IsPolymorphed() )
2098 addvalue = (float)GetMaxHealth()/3;
2099 // normal regen case (maybe partly in combat case)
2100 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
2102 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
2103 if (!isInCombat())
2105 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
2106 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
2107 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
2109 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
2110 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
2112 if(!IsStandState())
2113 addvalue *= 1.5;
2116 // always regeneration bonus (including combat)
2117 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
2119 if(addvalue < 0)
2120 addvalue = 0;
2122 addvalue *= (float)diff / REGEN_TIME_FULL;
2124 ModifyHealth(int32(addvalue));
2127 Creature* Player::GetNPCIfCanInteractWith(ObjectGuid guid, uint32 npcflagmask)
2129 // some basic checks
2130 if (guid.IsEmpty() || !IsInWorld() || isInFlight())
2131 return NULL;
2133 // exist (we need look pets also for some interaction (quest/etc)
2134 Creature *unit = GetMap()->GetCreatureOrPetOrVehicle(guid);
2135 if (!unit)
2136 return NULL;
2138 // appropriate npc type
2139 if (npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
2140 return NULL;
2142 if (npcflagmask == UNIT_NPC_FLAG_STABLEMASTER)
2144 if (getClass() != CLASS_HUNTER)
2145 return NULL;
2148 // if a dead unit should be able to talk - the creature must be alive and have special flags
2149 if (!unit->isAlive())
2150 return NULL;
2152 if (isAlive() && unit->isInvisibleForAlive())
2153 return NULL;
2155 // not allow interaction under control, but allow with own pets
2156 if (unit->GetCharmerGUID())
2157 return NULL;
2159 // not enemy
2160 if (unit->IsHostileTo(this))
2161 return NULL;
2163 // not unfriendly
2164 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
2165 if(factionTemplate->faction)
2166 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
2167 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
2168 return NULL;
2170 // not too far
2171 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
2172 return NULL;
2174 return unit;
2177 GameObject* Player::GetGameObjectIfCanInteractWith(ObjectGuid guid, uint32 gameobject_type) const
2179 // some basic checks
2180 if (guid.IsEmpty() || !IsInWorld() || isInFlight())
2181 return NULL;
2183 if (GameObject *go = GetMap()->GetGameObject(guid))
2185 if (uint32(go->GetGoType()) == gameobject_type || gameobject_type == MAX_GAMEOBJECT_TYPE)
2187 float maxdist;
2188 switch(go->GetGoType())
2190 // TODO: find out how the client calculates the maximal usage distance to spellless working
2191 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2192 case GAMEOBJECT_TYPE_GUILD_BANK:
2193 case GAMEOBJECT_TYPE_MAILBOX:
2194 maxdist = 10.0f;
2195 break;
2196 case GAMEOBJECT_TYPE_FISHINGHOLE:
2197 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2198 break;
2199 default:
2200 maxdist = INTERACTION_DISTANCE;
2201 break;
2204 if (go->IsWithinDistInMap(this, maxdist) && go->isSpawned())
2205 return go;
2207 sLog.outError("GetGameObjectIfCanInteractWith: 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,
2208 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2211 return NULL;
2214 bool Player::IsUnderWater() const
2216 return IsInWater() &&
2217 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2220 void Player::SetInWater(bool apply)
2222 if(m_isInWater==apply)
2223 return;
2225 //define player in water by opcodes
2226 //move player's guid into HateOfflineList of those mobs
2227 //which can't swim and move guid back into ThreatList when
2228 //on surface.
2229 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2230 m_isInWater = apply;
2232 // remove auras that need water/land
2233 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2235 getHostileRefManager().updateThreatTables();
2238 struct SetGameMasterOnHelper
2240 explicit SetGameMasterOnHelper() {}
2241 void operator()(Unit* unit) const
2243 unit->setFaction(35);
2244 unit->getHostileRefManager().setOnlineOfflineState(false);
2248 struct SetGameMasterOffHelper
2250 explicit SetGameMasterOffHelper(uint32 _faction) : faction(_faction) {}
2251 void operator()(Unit* unit) const
2253 unit->setFaction(faction);
2254 unit->getHostileRefManager().setOnlineOfflineState(true);
2256 uint32 faction;
2259 void Player::SetGameMaster(bool on)
2261 if(on)
2263 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2264 setFaction(35);
2265 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2267 CallForAllControlledUnits(SetGameMasterOnHelper(),true,true,true,false);
2269 SetFFAPvP(false);
2270 ResetContestedPvP();
2272 getHostileRefManager().setOnlineOfflineState(false);
2273 CombatStopWithPets();
2275 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2277 else
2279 // restore phase
2280 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2281 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2283 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2284 setFactionForRace(getRace());
2285 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2287 CallForAllControlledUnits(SetGameMasterOffHelper(getFaction()),true,true,true,false);
2289 // restore FFA PvP Server state
2290 if(sWorld.IsFFAPvPRealm())
2291 SetFFAPvP(true);
2293 // restore FFA PvP area state, remove not allowed for GM mounts
2294 UpdateArea(m_areaUpdateId);
2296 getHostileRefManager().setOnlineOfflineState(true);
2299 UpdateVisibilityForPlayer();
2302 void Player::SetGMVisible(bool on)
2304 if(on)
2306 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2308 // Reapply stealth/invisibility if active or show if not any
2309 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2310 SetVisibility(VISIBILITY_GROUP_STEALTH);
2311 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2312 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2313 else
2314 SetVisibility(VISIBILITY_ON);
2316 else
2318 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2320 SetAcceptWhispers(false);
2321 SetGameMaster(true);
2323 SetVisibility(VISIBILITY_OFF);
2327 bool Player::IsGroupVisibleFor(Player* p) const
2329 switch(sWorld.getConfig(CONFIG_UINT32_GROUP_VISIBILITY))
2331 default: return IsInSameGroupWith(p);
2332 case 1: return IsInSameRaidWith(p);
2333 case 2: return GetTeam()==p->GetTeam();
2337 bool Player::IsInSameGroupWith(Player const* p) const
2339 return (p==this || (GetGroup() != NULL &&
2340 GetGroup()->SameSubGroup((Player*)this, (Player*)p)));
2343 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2344 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2345 void Player::UninviteFromGroup()
2347 Group* group = GetGroupInvite();
2348 if(!group)
2349 return;
2351 group->RemoveInvite(this);
2353 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2355 if(group->IsCreated())
2357 group->Disband(true);
2358 sObjectMgr.RemoveGroup(group);
2360 else
2361 group->RemoveAllInvites();
2363 delete group;
2367 void Player::RemoveFromGroup(Group* group, uint64 guid)
2369 if(group)
2371 if (group->RemoveMember(guid, 0) <= 1)
2373 // group->Disband(); already disbanded in RemoveMember
2374 sObjectMgr.RemoveGroup(group);
2375 delete group;
2376 // removemember sets the player's group pointer to NULL
2381 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2383 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2384 data << uint64(victim ? victim->GetGUID() : 0); // guid
2385 data << uint32(GivenXP+RestXP); // given experience
2386 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2387 if(victim)
2389 data << uint32(GivenXP); // experience without rested bonus
2390 data << float(1); // 1 - none 0 - 100% group bonus output
2392 data << uint8(0); // new 2.4.0
2393 GetSession()->SendPacket(&data);
2396 void Player::GiveXP(uint32 xp, Unit* victim)
2398 if ( xp < 1 )
2399 return;
2401 if(!isAlive())
2402 return;
2404 uint32 level = getLevel();
2406 // XP to money conversion processed in Player::RewardQuest
2407 if(level >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2408 return;
2410 if(victim)
2412 // handle SPELL_AURA_MOD_KILL_XP_PCT auras
2413 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT);
2414 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2415 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2417 else
2419 // handle SPELL_AURA_MOD_QUEST_XP_PCT auras
2420 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT);
2421 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2422 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2425 // XP resting bonus for kill
2426 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2428 SendLogXPGain(xp,victim,rested_bonus_xp);
2430 uint32 curXP = GetUInt32Value(PLAYER_XP);
2431 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2432 uint32 newXP = curXP + xp + rested_bonus_xp;
2434 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
2436 newXP -= nextLvlXP;
2438 if ( level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
2439 GiveLevel(level + 1);
2441 level = getLevel();
2442 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2445 SetUInt32Value(PLAYER_XP, newXP);
2448 // Update player to next level
2449 // Current player experience not update (must be update by caller)
2450 void Player::GiveLevel(uint32 level)
2452 if ( level == getLevel() )
2453 return;
2455 PlayerLevelInfo info;
2456 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2458 PlayerClassLevelInfo classInfo;
2459 sObjectMgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2461 // send levelup info to client
2462 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2463 data << uint32(level);
2464 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2465 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2466 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2467 data << uint32(0);
2468 data << uint32(0);
2469 data << uint32(0);
2470 data << uint32(0);
2471 data << uint32(0);
2472 data << uint32(0);
2473 // end for
2474 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2475 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2477 GetSession()->SendPacket(&data);
2479 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(level));
2481 //update level, max level of skills
2482 m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
2484 _ApplyAllLevelScaleItemMods(false);
2486 SetLevel(level);
2488 UpdateSkillsForLevel ();
2490 // save base values (bonuses already included in stored stats
2491 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2492 SetCreateStat(Stats(i), info.stats[i]);
2494 SetCreateHealth(classInfo.basehealth);
2495 SetCreateMana(classInfo.basemana);
2497 InitTalentForLevel();
2498 InitTaxiNodesForLevel();
2499 InitGlyphsForLevel();
2501 UpdateAllStats();
2503 // set current level health and mana/energy to maximum after applying all mods.
2504 SetHealth(GetMaxHealth());
2505 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2506 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2507 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2508 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2509 SetPower(POWER_FOCUS, 0);
2510 SetPower(POWER_HAPPINESS, 0);
2512 _ApplyAllLevelScaleItemMods(true);
2514 // update level to hunter/summon pet
2515 if (Pet* pet = GetPet())
2516 pet->SynchronizeLevelWithOwner();
2518 if (MailLevelReward const* mailReward = sObjectMgr.GetMailLevelReward(level,getRaceMask()))
2519 MailDraft(mailReward->mailTemplateId).SendMailTo(this,MailSender(MAIL_CREATURE,mailReward->senderEntry));
2521 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2524 void Player::InitTalentForLevel()
2526 uint32 level = getLevel();
2527 // talents base at level diff ( talents = level - 9 but some can be used already)
2528 if(level < 10)
2530 // Remove all talent points
2531 if(m_usedTalentCount > 0) // Free any used talents
2533 resetTalents(true);
2534 SetFreeTalentPoints(0);
2537 else
2539 uint32 talentPointsForLevel = CalculateTalentsPoints();
2541 // if used more that have then reset
2542 if(m_usedTalentCount > talentPointsForLevel)
2544 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2545 resetTalents(true);
2546 else
2547 SetFreeTalentPoints(0);
2549 // else update amount of free points
2550 else
2551 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2554 if(!GetSession()->PlayerLoading())
2555 SendTalentsInfoData(false); // update at client
2558 void Player::InitStatsForLevel(bool reapplyMods)
2560 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2561 _RemoveAllStatBonuses();
2563 PlayerClassLevelInfo classInfo;
2564 sObjectMgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2566 PlayerLevelInfo info;
2567 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2569 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) );
2570 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(getLevel()));
2572 // reset before any aura state sources (health set/aura apply)
2573 SetUInt32Value(UNIT_FIELD_AURASTATE, 0);
2575 UpdateSkillsForLevel ();
2577 // set default cast time multiplier
2578 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2580 // reset size before reapply auras
2581 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2583 // save base values (bonuses already included in stored stats
2584 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2585 SetCreateStat(Stats(i), info.stats[i]);
2587 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2588 SetStat(Stats(i), info.stats[i]);
2590 SetCreateHealth(classInfo.basehealth);
2592 //set create powers
2593 SetCreateMana(classInfo.basemana);
2595 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2597 InitStatBuffMods();
2599 //reset rating fields values
2600 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2601 SetUInt32Value(index, 0);
2603 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2604 for (int i = 0; i < 7; ++i)
2606 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2607 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2608 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2611 //reset attack power, damage and attack speed fields
2612 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2613 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2614 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2616 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2617 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2618 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2619 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2620 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2621 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2623 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2624 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2625 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2626 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2627 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2628 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2630 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2631 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2632 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2633 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2635 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2636 for (uint8 i = 0; i < 7; ++i)
2637 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2639 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2640 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2641 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2643 // Dodge percentage
2644 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2646 // set armor (resistance 0) to original value (create_agility*2)
2647 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2648 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2649 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2650 // set other resistance to original value (0)
2651 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2653 SetResistance(SpellSchools(i), 0);
2654 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2655 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2658 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2659 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2660 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2662 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2663 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2665 // Reset no reagent cost field
2666 for(int i = 0; i < 3; ++i)
2667 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2668 // Init data for form but skip reapply item mods for form
2669 InitDataForForm(reapplyMods);
2671 // save new stats
2672 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2673 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2675 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2677 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2678 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2680 // cleanup unit flags (will be re-applied if need at aura load).
2681 RemoveFlag( UNIT_FIELD_FLAGS,
2682 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2683 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2684 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2685 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2686 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2687 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2689 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2691 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2692 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2694 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2695 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2697 // restore if need some important flags
2698 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2700 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2701 _ApplyAllStatBonuses();
2703 // set current level health and mana/energy to maximum after applying all mods.
2704 SetHealth(GetMaxHealth());
2705 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2706 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2707 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2708 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2709 SetPower(POWER_FOCUS, 0);
2710 SetPower(POWER_HAPPINESS, 0);
2711 SetPower(POWER_RUNIC_POWER, 0);
2713 // update level to hunter/summon pet
2714 if (Pet* pet = GetPet())
2715 pet->SynchronizeLevelWithOwner();
2718 void Player::SendInitialSpells()
2720 time_t curTime = time(NULL);
2721 time_t infTime = curTime + infinityCooldownDelayCheck;
2723 uint16 spellCount = 0;
2725 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2726 data << uint8(0);
2728 size_t countPos = data.wpos();
2729 data << uint16(spellCount); // spell count placeholder
2731 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2733 if(itr->second.state == PLAYERSPELL_REMOVED)
2734 continue;
2736 if(!itr->second.active || itr->second.disabled)
2737 continue;
2739 data << uint32(itr->first);
2740 data << uint16(0); // it's not slot id
2742 spellCount +=1;
2745 data.put<uint16>(countPos,spellCount); // write real count value
2747 uint16 spellCooldowns = m_spellCooldowns.size();
2748 data << uint16(spellCooldowns);
2749 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2751 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2752 if(!sEntry)
2753 continue;
2755 data << uint32(itr->first);
2757 data << uint16(itr->second.itemid); // cast item id
2758 data << uint16(sEntry->Category); // spell category
2760 // send infinity cooldown in special format
2761 if(itr->second.end >= infTime)
2763 data << uint32(1); // cooldown
2764 data << uint32(0x80000000); // category cooldown
2765 continue;
2768 time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILISECONDS : 0;
2770 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2772 data << uint32(0); // cooldown
2773 data << uint32(cooldown); // category cooldown
2775 else
2777 data << uint32(cooldown); // cooldown
2778 data << uint32(0); // category cooldown
2782 GetSession()->SendPacket(&data);
2784 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2787 void Player::RemoveMail(uint32 id)
2789 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2791 if ((*itr)->messageID == id)
2793 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2794 m_mail.erase(itr);
2795 return;
2800 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2802 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2803 data << (uint32) mailId;
2804 data << (uint32) mailAction;
2805 data << (uint32) mailError;
2806 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2807 data << (uint32) equipError;
2808 else if( mailAction == MAIL_ITEM_TAKEN )
2810 data << (uint32) item_guid; // item guid low?
2811 data << (uint32) item_count; // item count?
2813 GetSession()->SendPacket(&data);
2816 void Player::SendNewMail()
2818 // deliver undelivered mail
2819 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2820 data << (uint32) 0;
2821 GetSession()->SendPacket(&data);
2824 void Player::UpdateNextMailTimeAndUnreads()
2826 // calculate next delivery time (min. from non-delivered mails
2827 // and recalculate unReadMail
2828 time_t cTime = time(NULL);
2829 m_nextMailDelivereTime = 0;
2830 unReadMails = 0;
2831 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2833 if((*itr)->deliver_time > cTime)
2835 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2836 m_nextMailDelivereTime = (*itr)->deliver_time;
2838 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2839 ++unReadMails;
2843 void Player::AddNewMailDeliverTime(time_t deliver_time)
2845 if(deliver_time <= time(NULL)) // ready now
2847 ++unReadMails;
2848 SendNewMail();
2850 else // not ready and no have ready mails
2852 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2853 m_nextMailDelivereTime = deliver_time;
2857 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2859 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2860 if (!spellInfo)
2862 // do character spell book cleanup (all characters)
2863 if(!IsInWorld() && !learning) // spell load case
2865 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2866 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2868 else
2869 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2871 return false;
2874 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2876 // do character spell book cleanup (all characters)
2877 if(!IsInWorld() && !learning) // spell load case
2879 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2880 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2882 else
2883 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2885 return false;
2888 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2890 bool dependent_set = false;
2891 bool disabled_case = false;
2892 bool superceded_old = false;
2894 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2895 if (itr != m_spells.end())
2897 uint32 next_active_spell_id = 0;
2898 // fix activate state for non-stackable low rank (and find next spell for !active case)
2899 if(!SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
2901 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
2902 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2904 if(HasSpell(next_itr->second))
2906 // high rank already known so this must !active
2907 active = false;
2908 next_active_spell_id = next_itr->second;
2909 break;
2914 // not do anything if already known in expected state
2915 if(itr->second.state != PLAYERSPELL_REMOVED && itr->second.active == active &&
2916 itr->second.dependent == dependent && itr->second.disabled == disabled)
2918 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2919 itr->second.state = PLAYERSPELL_UNCHANGED;
2921 return false;
2924 // dependent spell known as not dependent, overwrite state
2925 if (itr->second.state != PLAYERSPELL_REMOVED && !itr->second.dependent && dependent)
2927 itr->second.dependent = dependent;
2928 if (itr->second.state != PLAYERSPELL_NEW)
2929 itr->second.state = PLAYERSPELL_CHANGED;
2930 dependent_set = true;
2933 // update active state for known spell
2934 if(itr->second.active != active && itr->second.state != PLAYERSPELL_REMOVED && !itr->second.disabled)
2936 itr->second.active = active;
2938 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2939 itr->second.state = PLAYERSPELL_UNCHANGED;
2940 else if(itr->second.state != PLAYERSPELL_NEW)
2941 itr->second.state = PLAYERSPELL_CHANGED;
2943 if(active)
2945 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2946 CastSpell (this,spell_id,true);
2948 else if(IsInWorld())
2950 if(next_active_spell_id)
2952 // update spell ranks in spellbook and action bar
2953 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2954 data << uint32(spell_id);
2955 data << uint32(next_active_spell_id);
2956 GetSession()->SendPacket( &data );
2958 else
2960 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2961 data << uint32(spell_id);
2962 GetSession()->SendPacket(&data);
2966 return active; // learn (show in spell book if active now)
2969 if(itr->second.disabled != disabled && itr->second.state != PLAYERSPELL_REMOVED)
2971 if(itr->second.state != PLAYERSPELL_NEW)
2972 itr->second.state = PLAYERSPELL_CHANGED;
2973 itr->second.disabled = disabled;
2975 if(disabled)
2976 return false;
2978 disabled_case = true;
2980 else switch(itr->second.state)
2982 case PLAYERSPELL_UNCHANGED: // known saved spell
2983 return false;
2984 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2986 m_spells.erase(itr);
2987 state = PLAYERSPELL_CHANGED;
2988 break; // need re-add
2990 default: // known not saved yet spell (new or modified)
2992 // can be in case spell loading but learned at some previous spell loading
2993 if(!IsInWorld() && !learning && !dependent_set)
2994 itr->second.state = PLAYERSPELL_UNCHANGED;
2996 return false;
3001 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
3003 // talent: unlearn all other talent ranks (high and low)
3004 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
3006 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
3008 for(int i=0; i < MAX_TALENT_RANK; ++i)
3010 // skip learning spell and no rank spell case
3011 uint32 rankSpellId = talentInfo->RankID[i];
3012 if(!rankSpellId || rankSpellId==spell_id)
3013 continue;
3015 removeSpell(rankSpellId,false,false);
3019 // non talent spell: learn low ranks (recursive call)
3020 else if(uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id))
3022 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
3023 addSpell(prev_spell,active,true,true,disabled);
3024 else // at normal learning
3025 learnSpell(prev_spell,true);
3028 PlayerSpell newspell;
3029 newspell.state = state;
3030 newspell.active = active;
3031 newspell.dependent = dependent;
3032 newspell.disabled = disabled;
3034 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
3035 if(newspell.active && !newspell.disabled && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
3037 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
3039 if(itr2->second.state == PLAYERSPELL_REMOVED) continue;
3040 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
3041 if(!i_spellInfo) continue;
3043 if( sSpellMgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
3045 if(itr2->second.active)
3047 if(sSpellMgr.IsHighRankOfSpell(spell_id,itr2->first))
3049 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3051 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3052 data << uint32(itr2->first);
3053 data << uint32(spell_id);
3054 GetSession()->SendPacket( &data );
3057 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
3058 itr2->second.active = false;
3059 if(itr2->second.state != PLAYERSPELL_NEW)
3060 itr2->second.state = PLAYERSPELL_CHANGED;
3061 superceded_old = true; // new spell replace old in action bars and spell book.
3063 else if(sSpellMgr.IsHighRankOfSpell(itr2->first,spell_id))
3065 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3067 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3068 data << uint32(spell_id);
3069 data << uint32(itr2->first);
3070 GetSession()->SendPacket( &data );
3073 // mark new spell as disable (not learned yet for client and will not learned)
3074 newspell.active = false;
3075 if(newspell.state != PLAYERSPELL_NEW)
3076 newspell.state = PLAYERSPELL_CHANGED;
3083 m_spells[spell_id] = newspell;
3085 // return false if spell disabled
3086 if (newspell.disabled)
3087 return false;
3090 uint32 talentCost = GetTalentSpellCost(spell_id);
3092 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3093 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3094 if (talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
3096 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3097 CastSpell(this, spell_id, true);
3099 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3100 else if (IsPassiveSpell(spell_id))
3102 if (IsNeedCastPassiveSpellAtLearn(spellInfo))
3103 CastSpell(this, spell_id, true);
3105 else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
3107 CastSpell(this, spell_id, true);
3108 return false;
3111 // update used talent points count
3112 m_usedTalentCount += talentCost;
3114 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3115 if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
3117 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3118 SetFreePrimaryProfessions(freeProfs-1);
3121 // add dependent skills
3122 uint16 maxskill = GetMaxSkillValueForLevel();
3124 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3126 SkillLineAbilityMapBounds skill_bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3128 if (spellLearnSkill)
3130 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
3131 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
3133 if (skill_value < spellLearnSkill->value)
3134 skill_value = spellLearnSkill->value;
3136 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
3138 if (skill_max_value < new_skill_max_value)
3139 skill_max_value = new_skill_max_value;
3141 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
3143 else
3145 // not ranked skills
3146 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3148 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3149 if (!pSkill)
3150 continue;
3152 if (HasSkill(pSkill->id))
3153 continue;
3155 if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3156 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3157 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3159 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
3161 case SKILL_RANGE_LANGUAGE:
3162 SetSkill(pSkill->id, 300, 300 );
3163 break;
3164 case SKILL_RANGE_LEVEL:
3165 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
3166 break;
3167 case SKILL_RANGE_MONO:
3168 SetSkill(pSkill->id, 1, 1 );
3169 break;
3170 default:
3171 break;
3177 // learn dependent spells
3178 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3180 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3182 if (!itr2->second.autoLearned)
3184 if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
3185 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
3186 else // at normal learning
3187 learnSpell(itr2->second.spell,true);
3191 if (!GetSession()->PlayerLoading())
3193 // not ranked skills
3194 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3196 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3197 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3200 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3203 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3204 return active && !disabled && !superceded_old;
3207 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3209 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3210 // talent dependent passives activated at form apply have proper stance data
3211 bool need_cast = (!spellInfo->Stances || (m_form != 0 && (spellInfo->Stances & (1<<(m_form-1)))));
3213 //Check CasterAuraStates
3214 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3217 void Player::learnSpell(uint32 spell_id, bool dependent)
3219 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3221 bool disabled = (itr != m_spells.end()) ? itr->second.disabled : false;
3222 bool active = disabled ? itr->second.active : true;
3224 bool learning = addSpell(spell_id,active,true,dependent,false);
3226 // learn all disabled higher ranks (recursive)
3227 if(disabled)
3229 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3230 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3232 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3233 if (iter != m_spells.end() && iter->second.disabled)
3234 learnSpell(i->second,false);
3238 // prevent duplicated entires in spell book, also not send if not in world (loading)
3239 if(!learning || !IsInWorld ())
3240 return;
3242 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3243 data << uint32(spell_id);
3244 GetSession()->SendPacket(&data);
3247 void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bool sendUpdate)
3249 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3250 if (itr == m_spells.end())
3251 return;
3253 if (itr->second.state == PLAYERSPELL_REMOVED || (disabled && itr->second.disabled))
3254 return;
3256 // unlearn non talent higher ranks (recursive)
3257 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3258 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3259 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3260 removeSpell(itr2->second,disabled,false);
3262 // re-search, it can be corrupted in prev loop
3263 itr = m_spells.find(spell_id);
3264 if (itr == m_spells.end())
3265 return; // already unleared
3267 bool cur_active = itr->second.active;
3268 bool cur_dependent = itr->second.dependent;
3270 if (disabled)
3272 itr->second.disabled = disabled;
3273 if(itr->second.state != PLAYERSPELL_NEW)
3274 itr->second.state = PLAYERSPELL_CHANGED;
3276 else
3278 if(itr->second.state == PLAYERSPELL_NEW)
3279 m_spells.erase(itr);
3280 else
3281 itr->second.state = PLAYERSPELL_REMOVED;
3284 RemoveAurasDueToSpell(spell_id);
3286 // remove pet auras
3287 for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
3288 if(PetAura const* petSpell = sSpellMgr.GetPetAura(spell_id, SpellEffectIndex(i)))
3289 RemovePetAura(petSpell);
3291 // free talent points
3292 uint32 talentCosts = GetTalentSpellCost(spell_id);
3293 if(talentCosts > 0)
3295 if(talentCosts < m_usedTalentCount)
3296 m_usedTalentCount -= talentCosts;
3297 else
3298 m_usedTalentCount = 0;
3301 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3302 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3304 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3305 if(freeProfs <= sWorld.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL))
3306 SetFreePrimaryProfessions(freeProfs);
3309 // remove dependent skill
3310 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3311 if(spellLearnSkill)
3313 uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id);
3314 if(!prev_spell) // first rank, remove skill
3315 SetSkill(spellLearnSkill->skill,0,0);
3316 else
3318 // search prev. skill setting by spell ranks chain
3319 SpellLearnSkillNode const* prevSkill = sSpellMgr.GetSpellLearnSkill(prev_spell);
3320 while(!prevSkill && prev_spell)
3322 prev_spell = sSpellMgr.GetPrevSpellInChain(prev_spell);
3323 prevSkill = sSpellMgr.GetSpellLearnSkill(sSpellMgr.GetFirstSpellInChain(prev_spell));
3326 if (!prevSkill) // not found prev skill setting, remove skill
3327 SetSkill(spellLearnSkill->skill,0,0);
3328 else // set to prev. skill setting values
3330 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3331 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3333 if (skill_value > prevSkill->value)
3334 skill_value = prevSkill->value;
3336 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3338 if (skill_max_value > new_skill_max_value)
3339 skill_max_value = new_skill_max_value;
3341 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3346 else
3348 // not ranked skills
3349 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3351 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
3353 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3354 if (!pSkill)
3355 continue;
3357 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
3358 pSkill->categoryId != SKILL_CATEGORY_CLASS ||// not unlearn class skills (spellbook/talent pages)
3359 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3360 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3362 // not reset skills for professions and racial abilities
3363 if ((pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3364 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0))
3365 continue;
3367 SetSkill(pSkill->id, 0, 0 );
3372 // remove dependent spells
3373 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3375 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3376 removeSpell(itr2->second.spell, disabled);
3378 // activate lesser rank in spellbook/action bar, and cast it if need
3379 bool prev_activate = false;
3381 if (uint32 prev_id = sSpellMgr.GetPrevSpellInChain (spell_id))
3383 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3385 // if talent then lesser rank also talent and need learn
3386 if (talentCosts)
3388 if(learn_low_rank)
3389 learnSpell (prev_id,false);
3391 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3392 else if (cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
3394 // need manually update dependence state (learn spell ignore like attempts)
3395 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3396 if (prev_itr != m_spells.end())
3398 if (prev_itr->second.dependent != cur_dependent)
3400 prev_itr->second.dependent = cur_dependent;
3401 if (prev_itr->second.state != PLAYERSPELL_NEW)
3402 prev_itr->second.state = PLAYERSPELL_CHANGED;
3405 // now re-learn if need re-activate
3406 if (cur_active && !prev_itr->second.active && learn_low_rank)
3408 if (addSpell(prev_id,true,false,prev_itr->second.dependent,prev_itr->second.disabled))
3410 // downgrade spell ranks in spellbook and action bar
3411 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3412 data << uint32(spell_id);
3413 data << uint32(prev_id);
3414 GetSession()->SendPacket( &data );
3415 prev_activate = true;
3422 // remove from spell book if not replaced by lesser rank
3423 if (!prev_activate && sendUpdate)
3425 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3426 data << uint32(spell_id);
3427 GetSession()->SendPacket(&data);
3431 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3433 m_spellCooldowns.erase(spell_id);
3435 if(update)
3436 SendClearCooldown(spell_id, this);
3439 void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
3441 SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
3442 if (ct == sSpellCategoryStore.end())
3443 return;
3445 const SpellCategorySet& ct_set = ct->second;
3446 for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
3448 if (ct_set.find(i->first) != ct_set.end())
3449 RemoveSpellCooldown((i++)->first, update);
3450 else
3451 ++i;
3455 void Player::RemoveArenaSpellCooldowns()
3457 // remove cooldowns on spells that has < 15 min CD
3458 SpellCooldowns::iterator itr, next;
3459 // iterate spell cooldowns
3460 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3462 next = itr;
3463 ++next;
3464 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3465 // check if spellentry is present and if the cooldown is less than 15 mins
3466 if( entry &&
3467 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3468 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3470 // remove & notify
3471 RemoveSpellCooldown(itr->first, true);
3476 void Player::RemoveAllSpellCooldown()
3478 if(!m_spellCooldowns.empty())
3480 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3481 SendClearCooldown(itr->first, this);
3483 m_spellCooldowns.clear();
3487 void Player::_LoadSpellCooldowns(QueryResult *result)
3489 // some cooldowns can be already set at aura loading...
3491 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3493 if(result)
3495 time_t curTime = time(NULL);
3499 Field *fields = result->Fetch();
3501 uint32 spell_id = fields[0].GetUInt32();
3502 uint32 item_id = fields[1].GetUInt32();
3503 time_t db_time = (time_t)fields[2].GetUInt64();
3505 if(!sSpellStore.LookupEntry(spell_id))
3507 sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3508 continue;
3511 // skip outdated cooldown
3512 if(db_time <= curTime)
3513 continue;
3515 AddSpellCooldown(spell_id, item_id, db_time);
3517 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3519 while( result->NextRow() );
3521 delete result;
3525 void Player::_SaveSpellCooldowns()
3527 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3529 time_t curTime = time(NULL);
3530 time_t infTime = curTime + infinityCooldownDelayCheck;
3532 /* copied following sql-code partly from achievementmgr */
3533 bool first_round = true;
3534 std::ostringstream ss;
3536 // remove outdated and save active
3537 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3539 if(itr->second.end <= curTime)
3540 m_spellCooldowns.erase(itr++);
3541 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3543 if (first_round)
3545 ss << "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ";
3546 first_round = false;
3548 // next new/changed record prefix
3549 else
3550 ss << ", ";
3551 ss << "(" << GetGUIDLow() << "," << itr->first << "," << itr->second.itemid << "," << uint64(itr->second.end) << ")";
3552 ++itr;
3554 else
3555 ++itr;
3558 // if something changed execute
3559 if (!first_round)
3560 CharacterDatabase.Execute( ss.str().c_str() );
3563 uint32 Player::resetTalentsCost() const
3565 // The first time reset costs 1 gold
3566 if(m_resetTalentsCost < 1*GOLD)
3567 return 1*GOLD;
3568 // then 5 gold
3569 else if(m_resetTalentsCost < 5*GOLD)
3570 return 5*GOLD;
3571 // After that it increases in increments of 5 gold
3572 else if(m_resetTalentsCost < 10*GOLD)
3573 return 10*GOLD;
3574 else
3576 time_t months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3577 if(months > 0)
3579 // This cost will be reduced by a rate of 5 gold per month
3580 int32 new_cost = int32((m_resetTalentsCost) - 5*GOLD*months);
3581 // to a minimum of 10 gold.
3582 return uint32(new_cost < 10*GOLD ? 10*GOLD : new_cost);
3584 else
3586 // After that it increases in increments of 5 gold
3587 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3588 // until it hits a cap of 50 gold.
3589 if(new_cost > 50*GOLD)
3590 new_cost = 50*GOLD;
3591 return new_cost;
3596 bool Player::resetTalents(bool no_cost)
3598 // not need after this call
3599 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3600 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
3602 uint32 talentPointsForLevel = CalculateTalentsPoints();
3604 if (m_usedTalentCount == 0)
3606 SetFreeTalentPoints(talentPointsForLevel);
3607 return false;
3610 uint32 cost = 0;
3612 if(!no_cost)
3614 cost = resetTalentsCost();
3616 if (GetMoney() < cost)
3618 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3619 return false;
3623 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3625 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3627 if (!talentInfo) continue;
3629 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3631 if(!talentTabInfo)
3632 continue;
3634 // unlearn only talents for character class
3635 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3636 // to prevent unexpected lost normal learned spell skip another class talents
3637 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3638 continue;
3640 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3642 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3644 if(itr->second.state == PLAYERSPELL_REMOVED || itr->second.disabled)
3646 ++itr;
3647 continue;
3650 // remove learned spells (all ranks)
3651 uint32 itrFirstId = sSpellMgr.GetFirstSpellInChain(itr->first);
3653 // unlearn if first rank is talent or learned by talent
3654 if (itrFirstId == talentInfo->RankID[j])
3656 removeSpell(itr->first,!IsPassiveSpell(itr->first),false);
3657 itr = GetSpellMap().begin();
3658 continue;
3660 else if (sSpellMgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3662 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3663 itr = GetSpellMap().begin();
3664 continue;
3666 else
3667 ++itr;
3672 SetFreeTalentPoints(talentPointsForLevel);
3674 if(!no_cost)
3676 ModifyMoney(-(int32)cost);
3677 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3678 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3680 m_resetTalentsCost = cost;
3681 m_resetTalentsTime = time(NULL);
3684 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3685 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3686 /* when prev line will dropped use next line
3687 if(Pet* pet = GetPet())
3689 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3690 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3695 if(m_canTitanGrip)
3697 m_canTitanGrip = false;
3698 if(sWorld.getConfig(CONFIG_BOOL_OFFHAND_CHECK_AT_TALENTS_RESET))
3699 AutoUnequipOffhandIfNeed();
3702 return true;
3705 Mail* Player::GetMail(uint32 id)
3707 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3709 if ((*itr)->messageID == id)
3711 return (*itr);
3714 return NULL;
3717 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3719 if(target == this)
3721 Object::_SetCreateBits(updateMask, target);
3723 else
3725 for(uint16 index = 0; index < m_valuesCount; index++)
3727 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3728 updateMask->SetBit(index);
3733 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3735 if(target == this)
3737 Object::_SetUpdateBits(updateMask, target);
3739 else
3741 Object::_SetUpdateBits(updateMask, target);
3742 *updateMask &= updateVisualBits;
3746 void Player::InitVisibleBits()
3748 updateVisualBits.SetCount(PLAYER_END);
3750 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3751 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3752 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3753 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3754 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3755 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3756 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3757 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3758 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3759 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3760 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3761 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3762 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3763 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3764 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3765 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3766 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3767 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3768 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3769 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3770 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3771 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3772 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3773 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3774 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3775 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3776 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3777 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3778 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3779 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3780 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3781 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3782 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3783 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3784 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3785 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3786 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3787 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3788 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3789 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3790 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3791 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3792 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3793 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3794 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3795 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3796 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3797 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3798 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3799 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3800 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3801 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3802 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3803 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3804 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3806 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3807 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3808 updateVisualBits.SetBit(PLAYER_FLAGS);
3809 updateVisualBits.SetBit(PLAYER_GUILDID);
3810 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3811 updateVisualBits.SetBit(PLAYER_BYTES);
3812 updateVisualBits.SetBit(PLAYER_BYTES_2);
3813 updateVisualBits.SetBit(PLAYER_BYTES_3);
3814 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3815 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3817 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3818 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += MAX_QUEST_OFFSET)
3819 updateVisualBits.SetBit(i);
3821 // Players visible items are not inventory stuff
3822 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3824 uint32 offset = i * 2;
3826 // item entry
3827 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3828 // enchant
3829 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3832 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3835 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3837 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3839 if(m_items[i] == NULL)
3840 continue;
3842 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3845 if(target == this)
3847 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3849 if(m_items[i] == NULL)
3850 continue;
3852 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3854 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3856 if(m_items[i] == NULL)
3857 continue;
3859 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3863 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3866 void Player::DestroyForPlayer( Player *target, bool anim ) const
3868 Unit::DestroyForPlayer( target, anim );
3870 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3872 if(m_items[i] == NULL)
3873 continue;
3875 m_items[i]->DestroyForPlayer( target );
3878 if(target == this)
3880 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3882 if(m_items[i] == NULL)
3883 continue;
3885 m_items[i]->DestroyForPlayer( target );
3887 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3889 if(m_items[i] == NULL)
3890 continue;
3892 m_items[i]->DestroyForPlayer( target );
3897 bool Player::HasSpell(uint32 spell) const
3899 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3900 return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED &&
3901 !itr->second.disabled);
3904 bool Player::HasActiveSpell(uint32 spell) const
3906 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3907 return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED &&
3908 itr->second.active && !itr->second.disabled);
3911 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3913 if (!trainer_spell)
3914 return TRAINER_SPELL_RED;
3916 if (!trainer_spell->learnedSpell)
3917 return TRAINER_SPELL_RED;
3919 // known spell
3920 if(HasSpell(trainer_spell->learnedSpell))
3921 return TRAINER_SPELL_GRAY;
3923 // check race/class requirement
3924 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3925 return TRAINER_SPELL_RED;
3927 // check level requirement
3928 if(getLevel() < trainer_spell->reqLevel)
3929 return TRAINER_SPELL_RED;
3931 if(SpellChainNode const* spell_chain = sSpellMgr.GetSpellChainNode(trainer_spell->learnedSpell))
3933 // check prev.rank requirement
3934 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3935 return TRAINER_SPELL_RED;
3937 // check additional spell requirement
3938 if(spell_chain->req && !HasSpell(spell_chain->req))
3939 return TRAINER_SPELL_RED;
3942 // check skill requirement
3943 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3944 return TRAINER_SPELL_RED;
3946 // exist, already checked at loading
3947 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3949 // secondary prof. or not prof. spell
3950 uint32 skill = spell->EffectMiscValue[1];
3952 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3953 return TRAINER_SPELL_GREEN;
3955 // check primary prof. limit
3956 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
3957 return TRAINER_SPELL_GREEN_DISABLED;
3959 return TRAINER_SPELL_GREEN;
3962 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3964 uint32 guid = GUID_LOPART(playerguid);
3966 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3967 // bones will be deleted by corpse/bones deleting thread shortly
3968 sObjectAccessor.ConvertCorpseForPlayer(playerguid);
3970 // remove from guild
3971 uint32 guildId = GetGuildIdFromDB(playerguid);
3972 if(guildId != 0)
3974 Guild* guild = sObjectMgr.GetGuildById(guildId);
3975 if(guild)
3976 guild->DelMember(guid);
3979 // remove from arena teams
3980 LeaveAllArenaTeams(playerguid);
3982 // the player was uninvited already on logout so just remove from group
3983 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", guid);
3984 if(resultGroup)
3986 uint32 groupId = (*resultGroup)[0].GetUInt32();
3987 delete resultGroup;
3988 if (Group* group = sObjectMgr.GetGroupById(groupId))
3989 RemoveFromGroup(group, playerguid);
3992 // remove signs from petitions (also remove petitions if owner);
3993 RemovePetitionsAndSigns(playerguid, 10);
3995 // return back all mails with COD and Item 0 1 2 3 4 5 6 7
3996 QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,messageType,mailTemplateId,sender,subject,itemTextId,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid);
3997 if(resultMail)
4001 Field *fields = resultMail->Fetch();
4003 uint32 mail_id = fields[0].GetUInt32();
4004 uint16 mailType = fields[1].GetUInt16();
4005 uint16 mailTemplateId= fields[2].GetUInt16();
4006 uint32 sender = fields[3].GetUInt32();
4007 std::string subject = fields[4].GetCppString();
4008 uint32 itemTextId = fields[5].GetUInt32();
4009 uint32 money = fields[6].GetUInt32();
4010 bool has_items = fields[7].GetBool();
4012 //we can return mail now
4013 //so firstly delete the old one
4014 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
4016 // mail not from player
4017 if (mailType != MAIL_NORMAL)
4019 if(has_items)
4020 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
4021 continue;
4024 MailDraft draft(subject, itemTextId);
4025 if (mailTemplateId)
4026 draft = MailDraft(mailTemplateId,false); // itesm already included
4028 if(has_items)
4030 // data needs to be at first place for Item::LoadFromDB
4031 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT data,item_guid,item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id);
4032 if(resultItems)
4036 Field *fields2 = resultItems->Fetch();
4038 uint32 item_guidlow = fields2[1].GetUInt32();
4039 uint32 item_template = fields2[2].GetUInt32();
4041 ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_template);
4042 if(!itemProto)
4044 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
4045 continue;
4048 Item *pItem = NewItemOrBag(itemProto);
4049 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
4051 pItem->FSetState(ITEM_REMOVED);
4052 pItem->SaveToDB(); // it also deletes item object !
4053 continue;
4056 draft.AddItem(pItem);
4058 while (resultItems->NextRow());
4060 delete resultItems;
4064 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
4066 uint32 pl_account = sObjectMgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
4068 draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender);
4070 while (resultMail->NextRow());
4072 delete resultMail;
4075 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
4076 // Get guids of character's pets, will deleted in transaction
4077 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
4079 // NOW we can finally clear other DB data related to character
4080 CharacterDatabase.BeginTransaction();
4081 if (resultPets)
4085 Field *fields3 = resultPets->Fetch();
4086 uint32 petguidlow = fields3[0].GetUInt32();
4087 Pet::DeleteFromDB(petguidlow);
4088 } while (resultPets->NextRow());
4089 delete resultPets;
4092 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
4093 CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid);
4094 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
4095 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
4096 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
4097 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
4098 CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid = '%u'",guid);
4099 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
4100 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
4101 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
4102 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
4103 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
4104 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",guid);
4105 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
4106 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u'",guid);
4107 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
4108 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
4109 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
4110 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
4111 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
4112 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
4113 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
4114 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
4115 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
4116 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
4117 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
4118 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
4119 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u'",guid);
4120 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid);
4121 CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid);
4122 CharacterDatabase.CommitTransaction();
4124 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4125 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
4128 void Player::SetMovement(PlayerMovementType pType)
4130 WorldPacket data;
4131 switch(pType)
4133 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
4134 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
4135 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
4136 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
4137 default:
4138 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
4139 return;
4141 data << GetPackGUID();
4142 data << uint32(0);
4143 GetSession()->SendPacket( &data );
4146 /* Preconditions:
4147 - a resurrectable corpse must not be loaded for the player (only bones)
4148 - the player must be in world
4150 void Player::BuildPlayerRepop()
4152 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
4153 data << GetPackGUID();
4154 GetSession()->SendPacket(&data);
4156 if(getRace() == RACE_NIGHTELF)
4157 CastSpell(this, 20584, true); // auras SPELL_AURA_INCREASE_SPEED(+speed in wisp form), SPELL_AURA_INCREASE_SWIM_SPEED(+swim speed in wisp form), SPELL_AURA_TRANSFORM (to wisp form)
4158 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4160 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4161 // there must be SMSG.STOP_MIRROR_TIMER
4162 // there we must send 888 opcode
4164 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4165 if(GetCorpse())
4167 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4168 assert(false);
4171 // create a corpse and place it at the player's location
4172 CreateCorpse();
4173 Corpse *corpse = GetCorpse();
4174 if(!corpse)
4176 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4177 return;
4179 GetMap()->Add(corpse);
4181 // convert player body to ghost
4182 SetHealth( 1 );
4184 SetMovement(MOVE_WATER_WALK);
4185 if(!GetSession()->isLogingOut())
4186 SetMovement(MOVE_UNROOT);
4188 // BG - remove insignia related
4189 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
4191 SendCorpseReclaimDelay();
4193 // to prevent cheating
4194 corpse->ResetGhostTime();
4196 StopMirrorTimers(); //disable timers(bars)
4198 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
4200 // set and clear other
4201 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
4204 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
4206 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
4207 data << uint32(-1);
4208 data << float(0);
4209 data << float(0);
4210 data << float(0);
4211 GetSession()->SendPacket(&data);
4213 // speed change, land walk
4215 // remove death flag + set aura
4216 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4217 if(getRace() == RACE_NIGHTELF)
4218 RemoveAurasDueToSpell(20584); // speed bonuses
4219 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4221 setDeathState(ALIVE);
4223 SetMovement(MOVE_LAND_WALK);
4224 SetMovement(MOVE_UNROOT);
4226 m_deathTimer = 0;
4228 // set health/powers (0- will be set in caller)
4229 if(restore_percent>0.0f)
4231 SetHealth(uint32(GetMaxHealth()*restore_percent));
4232 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4233 SetPower(POWER_RAGE, 0);
4234 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4237 // trigger update zone for alive state zone updates
4238 uint32 newzone, newarea;
4239 GetZoneAndAreaId(newzone,newarea);
4240 UpdateZone(newzone,newarea);
4242 // update visibility
4243 UpdateVisibilityForPlayer();
4245 if(!applySickness)
4246 return;
4248 //Characters from level 1-10 are not affected by resurrection sickness.
4249 //Characters from level 11-19 will suffer from one minute of sickness
4250 //for each level they are above 10.
4251 //Characters level 20 and up suffer from ten minutes of sickness.
4252 int32 startLevel = sWorld.getConfig(CONFIG_INT32_DEATH_SICKNESS_LEVEL);
4254 if(int32(getLevel()) >= startLevel)
4256 // set resurrection sickness
4257 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4259 // not full duration
4260 if(int32(getLevel()) < startLevel+9)
4262 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4264 for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
4266 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,SpellEffectIndex(i)))
4268 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4269 Aur->SendAuraUpdate(false);
4276 void Player::KillPlayer()
4278 SetMovement(MOVE_ROOT);
4280 StopMirrorTimers(); //disable timers(bars)
4282 setDeathState(CORPSE);
4283 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4285 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4286 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4288 // 6 minutes until repop at graveyard
4289 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4291 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4293 // don't create corpse at this moment, player might be falling
4295 // update visibility
4296 UpdateObjectVisibility();
4299 void Player::CreateCorpse()
4301 // prevent existence 2 corpse for player
4302 SpawnCorpseBones();
4304 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4306 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4307 SetPvPDeath(false);
4309 if(!corpse->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4311 delete corpse;
4312 return;
4315 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4316 _pb = GetUInt32Value(PLAYER_BYTES);
4317 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4319 uint8 race = (uint8)(_uf);
4320 uint8 skin = (uint8)(_pb);
4321 uint8 face = (uint8)(_pb >> 8);
4322 uint8 hairstyle = (uint8)(_pb >> 16);
4323 uint8 haircolor = (uint8)(_pb >> 24);
4324 uint8 facialhair = (uint8)(_pb2);
4326 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4327 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4329 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4330 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4332 uint32 flags = CORPSE_FLAG_UNK2;
4333 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4334 flags |= CORPSE_FLAG_HIDE_HELM;
4335 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4336 flags |= CORPSE_FLAG_HIDE_CLOAK;
4337 if(InBattleGround() && !InArena())
4338 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4339 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4341 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4343 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4345 uint32 iDisplayID;
4346 uint32 iIventoryType;
4347 uint32 _cfi;
4348 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4350 if(m_items[i])
4352 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4353 iIventoryType = m_items[i]->GetProto()->InventoryType;
4355 _cfi = iDisplayID | (iIventoryType << 24);
4356 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi);
4360 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4361 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4362 assert(entry);
4363 if(entry->map_type != MAP_BATTLEGROUND)
4364 corpse->SaveToDB();
4366 // register for player, but not show
4367 sObjectAccessor.AddCorpse(corpse);
4370 void Player::SpawnCorpseBones()
4372 if(sObjectAccessor.ConvertCorpseForPlayer(GetGUID()))
4373 if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
4374 SaveToDB(); // prevent loading as ghost without corpse
4377 Corpse* Player::GetCorpse() const
4379 return sObjectAccessor.GetCorpseForPlayerGUID(GetGUID());
4382 void Player::DurabilityLossAll(double percent, bool inventory)
4384 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4385 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4386 DurabilityLoss(pItem,percent);
4388 if(inventory)
4390 // bags not have durability
4391 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4393 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4394 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4395 DurabilityLoss(pItem,percent);
4397 // keys not have durability
4398 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4400 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4401 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4402 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4403 if(Item* pItem = GetItemByPos( i, j ))
4404 DurabilityLoss(pItem,percent);
4408 void Player::DurabilityLoss(Item* item, double percent)
4410 if(!item )
4411 return;
4413 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4415 if(!pMaxDurability)
4416 return;
4418 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4420 if(pDurabilityLoss < 1 )
4421 pDurabilityLoss = 1;
4423 DurabilityPointsLoss(item,pDurabilityLoss);
4426 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4428 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4429 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4430 DurabilityPointsLoss(pItem,points);
4432 if(inventory)
4434 // bags not have durability
4435 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4437 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4438 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4439 DurabilityPointsLoss(pItem,points);
4441 // keys not have durability
4442 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4444 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4445 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4446 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4447 if(Item* pItem = GetItemByPos( i, j ))
4448 DurabilityPointsLoss(pItem,points);
4452 void Player::DurabilityPointsLoss(Item* item, int32 points)
4454 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4455 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4456 int32 pNewDurability = pOldDurability - points;
4458 if (pNewDurability < 0)
4459 pNewDurability = 0;
4460 else if (pNewDurability > pMaxDurability)
4461 pNewDurability = pMaxDurability;
4463 if (pOldDurability != pNewDurability)
4465 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4466 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4467 _ApplyItemMods(item,item->GetSlot(), false);
4469 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4471 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4472 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4473 _ApplyItemMods(item,item->GetSlot(), true);
4475 item->SetState(ITEM_CHANGED, this);
4479 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4481 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4482 DurabilityPointsLoss(pItem,1);
4485 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4487 uint32 TotalCost = 0;
4488 // equipped, backpack, bags itself
4489 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4490 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4492 // bank, buyback and keys not repaired
4494 // items in inventory bags
4495 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4496 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4497 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4498 return TotalCost;
4501 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4503 Item* item = GetItemByPos(pos);
4505 uint32 TotalCost = 0;
4506 if(!item)
4507 return TotalCost;
4509 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4510 if(!maxDurability)
4511 return TotalCost;
4513 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4515 if(cost)
4517 uint32 LostDurability = maxDurability - curDurability;
4518 if(LostDurability>0)
4520 ItemPrototype const *ditemProto = item->GetProto();
4522 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4523 if(!dcost)
4525 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4526 return TotalCost;
4529 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4530 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4531 if(!dQualitymodEntry)
4533 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4534 return TotalCost;
4537 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4538 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4540 costs = uint32(costs * discountMod);
4542 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4543 costs = 1;
4545 if (guildBank)
4547 if (GetGuildId()==0)
4549 DEBUG_LOG("You are not member of a guild");
4550 return TotalCost;
4553 Guild *pGuild = sObjectMgr.GetGuildById(GetGuildId());
4554 if (!pGuild)
4555 return TotalCost;
4557 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4559 DEBUG_LOG("You do not have rights to withdraw for repairs");
4560 return TotalCost;
4563 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4565 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4566 return TotalCost;
4569 if (pGuild->GetGuildBankMoney() < costs)
4571 DEBUG_LOG("There is not enough money in bank");
4572 return TotalCost;
4575 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4576 TotalCost = costs;
4578 else if (GetMoney() < costs)
4580 DEBUG_LOG("You do not have enough money");
4581 return TotalCost;
4583 else
4584 ModifyMoney( -int32(costs) );
4588 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4589 item->SetState(ITEM_CHANGED, this);
4591 // reapply mods for total broken and repaired item if equipped
4592 if(IsEquipmentPos(pos) && !curDurability)
4593 _ApplyItemMods(item,pos & 255, true);
4594 return TotalCost;
4597 void Player::RepopAtGraveyard()
4599 // note: this can be called also when the player is alive
4600 // for example from WorldSession::HandleMovementOpcodes
4602 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4604 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4605 if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport())
4607 ResurrectPlayer(0.5f);
4608 SpawnCorpseBones();
4611 WorldSafeLocsEntry const *ClosestGrave = NULL;
4613 // Special handle for battleground maps
4614 if( BattleGround *bg = GetBattleGround() )
4615 ClosestGrave = bg->GetClosestGraveYard(this);
4616 else
4617 ClosestGrave = sObjectMgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4619 // stop countdown until repop
4620 m_deathTimer = 0;
4622 // if no grave found, stay at the current location
4623 // and don't show spirit healer location
4624 if(ClosestGrave)
4626 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4627 if(isDead()) // not send if alive, because it used in TeleportTo()
4629 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4630 data << ClosestGrave->map_id;
4631 data << ClosestGrave->x;
4632 data << ClosestGrave->y;
4633 data << ClosestGrave->z;
4634 GetSession()->SendPacket(&data);
4639 void Player::JoinedChannel(Channel *c)
4641 m_channels.push_back(c);
4644 void Player::LeftChannel(Channel *c)
4646 m_channels.remove(c);
4649 void Player::CleanupChannels()
4651 while(!m_channels.empty())
4653 Channel* ch = *m_channels.begin();
4654 m_channels.erase(m_channels.begin()); // remove from player's channel list
4655 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4656 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4657 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4660 sLog.outDebug("Player: channels cleaned up!");
4663 void Player::UpdateLocalChannels(uint32 newZone )
4665 if(m_channels.empty())
4666 return;
4668 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4669 if(!current_zone)
4670 return;
4672 ChannelMgr* cMgr = channelMgr(GetTeam());
4673 if(!cMgr)
4674 return;
4676 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4678 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4680 next = i; ++next;
4682 // skip non built-in channels
4683 if(!(*i)->IsConstant())
4684 continue;
4686 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4687 if(!ch)
4688 continue;
4690 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4691 continue;
4693 // new channel
4694 char new_channel_name_buf[100];
4695 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4696 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4698 if((*i)!=new_channel)
4700 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4702 // leave old channel
4703 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4704 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4705 LeftChannel(*i); // remove from player's channel list
4706 cMgr->LeftChannel(name); // delete if empty
4709 sLog.outDebug("Player: channels cleaned up!");
4712 void Player::LeaveLFGChannel()
4714 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4716 if((*i)->IsLFG())
4718 (*i)->Leave(GetGUID());
4719 break;
4724 void Player::UpdateDefense()
4726 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_DEFENSE);
4728 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4730 // update dependent from defense skill part
4731 UpdateDefenseBonusesMod();
4735 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4737 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4739 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4740 return;
4743 float val = 1.0f;
4745 switch(modType)
4747 case FLAT_MOD:
4748 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4749 break;
4750 case PCT_MOD:
4751 if(amount <= -100.0f)
4752 amount = -200.0f;
4754 val = (100.0f + amount) / 100.0f;
4755 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4756 break;
4759 if(!CanModifyStats())
4760 return;
4762 switch(modGroup)
4764 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4765 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4766 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4767 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4768 default: break;
4772 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4774 if(modGroup >= BASEMOD_END || modType > MOD_END)
4776 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4777 return 0.0f;
4780 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4781 return 0.0f;
4783 return m_auraBaseMod[modGroup][modType];
4786 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4788 if(modGroup >= BASEMOD_END)
4790 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4791 return 0.0f;
4794 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4795 return 0.0f;
4797 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4800 uint32 Player::GetShieldBlockValue() const
4802 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4804 value = (value < 0) ? 0 : value;
4806 return uint32(value);
4809 float Player::GetMeleeCritFromAgility()
4811 uint32 level = getLevel();
4812 uint32 pclass = getClass();
4814 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4816 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4817 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4818 if (critBase==NULL || critRatio==NULL)
4819 return 0.0f;
4821 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4822 return crit*100.0f;
4825 float Player::GetDodgeFromAgility()
4827 // Table for base dodge values
4828 float dodge_base[MAX_CLASSES] = {
4829 0.0075f, // Warrior
4830 0.00652f, // Paladin
4831 -0.0545f, // Hunter
4832 -0.0059f, // Rogue
4833 0.03183f, // Priest
4834 0.0114f, // DK
4835 0.0167f, // Shaman
4836 0.034575f, // Mage
4837 0.02011f, // Warlock
4838 0.0f, // ??
4839 -0.0187f // Druid
4841 // Crit/agility to dodge/agility coefficient multipliers
4842 float crit_to_dodge[MAX_CLASSES] = {
4843 1.1f, // Warrior
4844 1.0f, // Paladin
4845 1.6f, // Hunter
4846 2.0f, // Rogue
4847 1.0f, // Priest
4848 1.0f, // DK?
4849 1.0f, // Shaman
4850 1.0f, // Mage
4851 1.0f, // Warlock
4852 0.0f, // ??
4853 1.7f // Druid
4856 uint32 level = getLevel();
4857 uint32 pclass = getClass();
4859 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4861 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4862 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4863 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4864 return 0.0f;
4866 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4867 return dodge*100.0f;
4870 float Player::GetSpellCritFromIntellect()
4872 uint32 level = getLevel();
4873 uint32 pclass = getClass();
4875 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4877 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4878 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4879 if (critBase==NULL || critRatio==NULL)
4880 return 0.0f;
4882 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4883 return crit*100.0f;
4886 float Player::GetRatingCoefficient(CombatRating cr) const
4888 uint32 level = getLevel();
4890 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4892 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4893 if (Rating == NULL)
4894 return 1.0f; // By default use minimum coefficient (not must be called)
4896 return Rating->ratio;
4899 float Player::GetRatingBonusValue(CombatRating cr) const
4901 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4904 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4906 switch (attType)
4908 case BASE_ATTACK:
4909 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4910 case OFF_ATTACK:
4911 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4912 default:
4913 break;
4915 return 0.0f;
4918 float Player::OCTRegenHPPerSpirit()
4920 uint32 level = getLevel();
4921 uint32 pclass = getClass();
4923 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4925 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4926 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4927 if (baseRatio==NULL || moreRatio==NULL)
4928 return 0.0f;
4930 // Formula from PaperDollFrame script
4931 float spirit = GetStat(STAT_SPIRIT);
4932 float baseSpirit = spirit;
4933 if (baseSpirit>50) baseSpirit = 50;
4934 float moreSpirit = spirit - baseSpirit;
4935 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4936 return regen;
4939 float Player::OCTRegenMPPerSpirit()
4941 uint32 level = getLevel();
4942 uint32 pclass = getClass();
4944 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4946 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4947 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4948 if (moreRatio==NULL)
4949 return 0.0f;
4951 // Formula get from PaperDollFrame script
4952 float spirit = GetStat(STAT_SPIRIT);
4953 float regen = spirit * moreRatio->ratio;
4954 return regen;
4957 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4959 m_baseRatingValue[cr]+=(apply ? value : -value);
4961 // explicit affected values
4962 switch (cr)
4964 case CR_HASTE_MELEE:
4966 float RatingChange = value / GetRatingCoefficient(cr);
4967 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4968 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4969 break;
4971 case CR_HASTE_RANGED:
4973 float RatingChange = value / GetRatingCoefficient(cr);
4974 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4975 break;
4977 case CR_HASTE_SPELL:
4979 float RatingChange = value / GetRatingCoefficient(cr);
4980 ApplyCastTimePercentMod(RatingChange,apply);
4981 break;
4985 UpdateRating(cr);
4988 void Player::UpdateRating(CombatRating cr)
4990 int32 amount = m_baseRatingValue[cr];
4991 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4992 // stat used stored in miscValueB for this aura
4993 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4994 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4995 if ((*i)->GetMiscValue() & (1<<cr))
4996 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4997 if (amount < 0)
4998 amount = 0;
4999 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
5001 bool affectStats = CanModifyStats();
5003 switch (cr)
5005 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
5006 case CR_DEFENSE_SKILL:
5007 UpdateDefenseBonusesMod();
5008 break;
5009 case CR_DODGE:
5010 UpdateDodgePercentage();
5011 break;
5012 case CR_PARRY:
5013 UpdateParryPercentage();
5014 break;
5015 case CR_BLOCK:
5016 UpdateBlockPercentage();
5017 break;
5018 case CR_HIT_MELEE:
5019 UpdateMeleeHitChances();
5020 break;
5021 case CR_HIT_RANGED:
5022 UpdateRangedHitChances();
5023 break;
5024 case CR_HIT_SPELL:
5025 UpdateSpellHitChances();
5026 break;
5027 case CR_CRIT_MELEE:
5028 if(affectStats)
5030 UpdateCritPercentage(BASE_ATTACK);
5031 UpdateCritPercentage(OFF_ATTACK);
5033 break;
5034 case CR_CRIT_RANGED:
5035 if(affectStats)
5036 UpdateCritPercentage(RANGED_ATTACK);
5037 break;
5038 case CR_CRIT_SPELL:
5039 if(affectStats)
5040 UpdateAllSpellCritChances();
5041 break;
5042 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
5043 case CR_HIT_TAKEN_RANGED:
5044 break;
5045 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
5046 break;
5047 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
5048 case CR_CRIT_TAKEN_RANGED:
5049 break;
5050 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
5051 break;
5052 case CR_HASTE_MELEE: // Implemented in Player::ApplyRatingMod
5053 case CR_HASTE_RANGED:
5054 case CR_HASTE_SPELL:
5055 break;
5056 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
5057 case CR_WEAPON_SKILL_OFFHAND:
5058 case CR_WEAPON_SKILL_RANGED:
5059 break;
5060 case CR_EXPERTISE:
5061 if(affectStats)
5063 UpdateExpertise(BASE_ATTACK);
5064 UpdateExpertise(OFF_ATTACK);
5066 break;
5067 case CR_ARMOR_PENETRATION:
5068 if(affectStats)
5069 UpdateArmorPenetration();
5070 break;
5074 void Player::UpdateAllRatings()
5076 for(int cr = 0; cr < MAX_COMBAT_RATING; ++cr)
5077 UpdateRating(CombatRating(cr));
5080 void Player::SetRegularAttackTime()
5082 for(int i = 0; i < MAX_ATTACK; ++i)
5084 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i),true,false);
5085 if (tmpitem)
5087 ItemPrototype const *proto = tmpitem->GetProto();
5088 if(proto->Delay)
5089 SetAttackTime(WeaponAttackType(i), proto->Delay);
5090 else
5091 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
5096 //skill+step, checking for max value
5097 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
5099 if(!skill_id)
5100 return false;
5102 SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
5103 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5104 return false;
5106 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5107 uint32 data = GetUInt32Value(valueIndex);
5108 uint32 value = SKILL_VALUE(data);
5109 uint32 max = SKILL_MAX(data);
5111 if ((!max) || (!value) || (value >= max))
5112 return false;
5114 if (value*512 < max*urand(0,512))
5116 uint32 new_value = value+step;
5117 if(new_value > max)
5118 new_value = max;
5120 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,max));
5121 if(itr->second.uState != SKILL_NEW)
5122 itr->second.uState = SKILL_CHANGED;
5123 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
5124 return true;
5127 return false;
5130 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
5132 if ( SkillValue >= GrayLevel )
5133 return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREY)*10;
5134 if ( SkillValue >= GreenLevel )
5135 return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREEN)*10;
5136 if ( SkillValue >= YellowLevel )
5137 return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_YELLOW)*10;
5138 return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_ORANGE)*10;
5141 bool Player::UpdateCraftSkill(uint32 spellid)
5143 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
5145 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spellid);
5147 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
5149 if (_spell_idx->second->skillId)
5151 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
5153 // Alchemy Discoveries here
5154 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
5155 if (spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
5157 if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
5158 learnSpell(discoveredSpell,false);
5161 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_CRAFTING);
5163 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
5164 _spell_idx->second->max_value,
5165 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
5166 _spell_idx->second->min_value),
5167 craft_skill_gain);
5170 return false;
5173 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
5175 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
5177 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING);
5179 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5180 switch (SkillId)
5182 case SKILL_HERBALISM:
5183 case SKILL_LOCKPICKING:
5184 case SKILL_JEWELCRAFTING:
5185 case SKILL_INSCRIPTION:
5186 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5187 case SKILL_SKINNING:
5188 if( sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS)==0)
5189 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5190 else
5191 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
5192 case SKILL_MINING:
5193 if (sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS)==0)
5194 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5195 else
5196 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
5198 return false;
5201 bool Player::UpdateFishingSkill()
5203 sLog.outDebug("UpdateFishingSkill");
5205 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5207 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5209 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING);
5211 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5214 // levels sync. with spell requirement for skill levels to learn
5215 // bonus abilities in sSkillLineAbilityStore
5216 // Used only to avoid scan DBC at each skill grow
5217 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5219 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5221 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5222 if ( !SkillId )
5223 return false;
5225 if(Chance <= 0) // speedup in 0 chance case
5227 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5228 return false;
5231 SkillStatusMap::iterator itr = mSkillStatus.find(SkillId);
5232 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5233 return false;
5235 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5237 uint32 data = GetUInt32Value(valueIndex);
5238 uint16 SkillValue = SKILL_VALUE(data);
5239 uint16 MaxValue = SKILL_MAX(data);
5241 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5242 return false;
5244 int32 Roll = irand(1,1000);
5246 if ( Roll <= Chance )
5248 uint32 new_value = SkillValue+step;
5249 if(new_value > MaxValue)
5250 new_value = MaxValue;
5252 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,MaxValue));
5253 if(itr->second.uState != SKILL_NEW)
5254 itr->second.uState = SKILL_CHANGED;
5255 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5257 if((SkillValue < *bsl && new_value >= *bsl))
5259 learnSkillRewardedSpells( SkillId, new_value);
5260 break;
5263 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5264 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5265 return true;
5268 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5269 return false;
5272 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5274 // no skill gain in pvp
5275 Unit *pVictim = getVictim();
5276 if(pVictim && pVictim->IsCharmerOrOwnerPlayerOrPlayerItself())
5277 return;
5279 if(IsInFeralForm())
5280 return; // always maximized SKILL_FERAL_COMBAT in fact
5282 if(m_form == FORM_TREE)
5283 return; // use weapon but not skill up
5285 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_WEAPON);
5287 switch(attType)
5289 case BASE_ATTACK:
5291 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5293 if (!tmpitem)
5294 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5295 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5296 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5297 break;
5299 case OFF_ATTACK:
5300 case RANGED_ATTACK:
5302 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5303 if (tmpitem)
5304 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5305 break;
5308 UpdateAllCritPercentages();
5311 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5313 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5314 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5315 uint32 moblevel = pVictim->getLevelForTarget(this);
5316 if(moblevel < greylevel)
5317 return;
5319 if (moblevel > plevel + 5)
5320 moblevel = plevel + 5;
5322 uint32 lvldif = moblevel - greylevel;
5323 if(lvldif < 3)
5324 lvldif = 3;
5326 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5327 if(skilldif <= 0)
5328 return;
5330 float chance = float(3 * lvldif * skilldif) / plevel;
5331 if(!defence)
5333 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5334 chance *= 0.1f * GetStat(STAT_INTELLECT);
5337 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5339 if(roll_chance_f(chance))
5341 if(defence)
5342 UpdateDefense();
5343 else
5344 UpdateWeaponSkill(attType);
5346 else
5347 return;
5350 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5352 SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid);
5353 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5354 return;
5356 uint32 bonusIndex = PLAYER_SKILL_BONUS_INDEX(itr->second.pos);
5358 uint32 bonus_val = GetUInt32Value(bonusIndex);
5359 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5360 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5362 if(talent) // permanent bonus stored in high part
5363 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5364 else // temporary/item bonus stored in low part
5365 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5368 void Player::UpdateSkillsForLevel()
5370 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5371 uint32 maxSkill = GetMaxSkillValueForLevel();
5373 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_BOOL_ALWAYS_MAX_SKILL_FOR_LEVEL);
5375 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5377 if(itr->second.uState == SKILL_DELETED)
5378 continue;
5380 uint32 pskill = itr->first;
5382 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5383 if(!pSkill)
5384 continue;
5386 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5387 continue;
5389 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5390 uint32 data = GetUInt32Value(valueIndex);
5391 uint32 max = SKILL_MAX(data);
5392 uint32 val = SKILL_VALUE(data);
5394 /// update only level dependent max skill values
5395 if(max!=1)
5397 /// maximize skill always
5398 if(alwaysMaxSkill)
5400 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(maxSkill,maxSkill));
5401 if(itr->second.uState != SKILL_NEW)
5402 itr->second.uState = SKILL_CHANGED;
5404 else if(max != maxconfskill) /// update max skill value if current max skill not maximized
5406 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(val,maxSkill));
5407 if(itr->second.uState != SKILL_NEW)
5408 itr->second.uState = SKILL_CHANGED;
5414 void Player::UpdateSkillsToMaxSkillsForLevel()
5416 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5418 if(itr->second.uState == SKILL_DELETED)
5419 continue;
5421 uint32 pskill = itr->first;
5422 if( IsProfessionOrRidingSkill(pskill))
5423 continue;
5424 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5425 uint32 data = GetUInt32Value(valueIndex);
5427 uint32 max = SKILL_MAX(data);
5429 if(max > 1)
5431 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(max,max));
5432 if(itr->second.uState != SKILL_NEW)
5433 itr->second.uState = SKILL_CHANGED;
5436 if(pskill == SKILL_DEFENSE)
5437 UpdateDefenseBonusesMod();
5441 // This functions sets a skill line value (and adds if doesn't exist yet)
5442 // To "remove" a skill line, set it's values to zero
5443 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5445 if(!id)
5446 return;
5448 SkillStatusMap::iterator itr = mSkillStatus.find(id);
5450 //has skill
5451 if(itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED)
5453 if(currVal)
5455 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),MAKE_SKILL_VALUE(currVal,maxVal));
5456 if(itr->second.uState != SKILL_NEW)
5457 itr->second.uState = SKILL_CHANGED;
5458 learnSkillRewardedSpells(id, currVal);
5459 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5460 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5462 else //remove
5464 // clear skill fields
5465 SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos),0);
5466 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),0);
5467 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos),0);
5469 // mark as deleted or simply remove from map if not saved yet
5470 if(itr->second.uState != SKILL_NEW)
5471 itr->second.uState = SKILL_DELETED;
5472 else
5473 mSkillStatus.erase(itr);
5475 // remove all spells that related to this skill
5476 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5477 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5478 if (pAbility->skillId==id)
5479 removeSpell(sSpellMgr.GetFirstSpellInChain(pAbility->spellId));
5482 else if(currVal) //add
5484 for (int i=0; i < PLAYER_MAX_SKILLS; ++i)
5485 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5487 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5488 if(!pSkill)
5490 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5491 return;
5493 // enable unlearn button for primary professions only
5494 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5495 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5496 else
5497 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5498 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5499 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5500 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5502 // insert new entry or update if not deleted old entry yet
5503 if(itr != mSkillStatus.end())
5505 itr->second.pos = i;
5506 itr->second.uState = SKILL_CHANGED;
5508 else
5509 mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW)));
5511 // apply skill bonuses
5512 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5514 // temporary bonuses
5515 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5516 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5517 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5518 (*j)->ApplyModifier(true);
5520 // permanent bonuses
5521 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5522 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5523 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5524 (*j)->ApplyModifier(true);
5526 // Learn all spells for skill
5527 learnSkillRewardedSpells(id, currVal);
5528 return;
5533 bool Player::HasSkill(uint32 skill) const
5535 if(!skill)
5536 return false;
5538 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5539 return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED);
5542 uint16 Player::GetSkillValue(uint32 skill) const
5544 if(!skill)
5545 return 0;
5547 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5548 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5549 return 0;
5551 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5553 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5554 result += SKILL_TEMP_BONUS(bonus);
5555 result += SKILL_PERM_BONUS(bonus);
5556 return result < 0 ? 0 : result;
5559 uint16 Player::GetMaxSkillValue(uint32 skill) const
5561 if(!skill)
5562 return 0;
5564 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5565 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5566 return 0;
5568 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5570 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5571 result += SKILL_TEMP_BONUS(bonus);
5572 result += SKILL_PERM_BONUS(bonus);
5573 return result < 0 ? 0 : result;
5576 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5578 if(!skill)
5579 return 0;
5581 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5582 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5583 return 0;
5585 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5588 uint16 Player::GetBaseSkillValue(uint32 skill) const
5590 if(!skill)
5591 return 0;
5593 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5594 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5595 return 0;
5597 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5598 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5599 return result < 0 ? 0 : result;
5602 uint16 Player::GetPureSkillValue(uint32 skill) const
5604 if(!skill)
5605 return 0;
5607 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5608 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5609 return 0;
5611 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5614 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5616 if(!skill)
5617 return 0;
5619 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5620 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5621 return 0;
5623 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5626 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5628 if(!skill)
5629 return 0;
5631 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5632 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5633 return 0;
5635 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5638 void Player::SendInitialActionButtons() const
5640 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5642 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5643 data << uint8(1); // can be 0, 1, 2 (talent spec)
5644 ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
5645 for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button)
5647 ActionButtonList::const_iterator itr = currentActionButtonList.find(button);
5648 if(itr != currentActionButtonList.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5649 data << uint32(itr->second.packedData);
5650 else
5651 data << uint32(0);
5654 GetSession()->SendPacket( &data );
5655 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5658 bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Player* player, bool msg)
5660 if(button >= MAX_ACTION_BUTTONS)
5662 if (msg)
5664 if (player)
5665 sLog.outError( "Action %u not added into button %u for player %s: button must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTONS );
5666 else
5667 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action, button, MAX_ACTION_BUTTONS );
5670 return false;
5673 if(action >= MAX_ACTION_BUTTON_ACTION_VALUE)
5675 if (msg)
5677 if (player)
5678 sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTON_ACTION_VALUE );
5679 else
5680 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action, button, MAX_ACTION_BUTTON_ACTION_VALUE );
5682 return false;
5685 switch(type)
5687 case ACTION_BUTTON_SPELL:
5688 if(!sSpellStore.LookupEntry(action))
5690 if (msg)
5692 if (player)
5693 sLog.outError( "Spell action %u not added into button %u for player %s: spell not exist", action, button, player->GetName() );
5694 else
5695 sLog.outError( "Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action, button );
5697 return false;
5700 if(player && !player->HasSpell(action))
5702 if (msg)
5703 sLog.outError( "Spell action %u not added into button %u for player %s: player don't known this spell", action, button, player->GetName() );
5704 return false;
5706 break;
5707 case ACTION_BUTTON_ITEM:
5708 if(!ObjectMgr::GetItemPrototype(action))
5710 if (msg)
5712 if (player)
5713 sLog.outError( "Item action %u not added into button %u for player %s: item not exist", action, button, player->GetName() );
5714 else
5715 sLog.outError( "Table `playercreateinfo_action` have item action %u into button %u: item not exist", action, button );
5717 return false;
5719 break;
5720 default:
5721 break; // other cases not checked at this moment
5724 return true;
5727 ActionButton* Player::addActionButton(uint8 spec, uint8 button, uint32 action, uint8 type)
5729 // check action only for active spec (so not check at copy/load passive spec)
5730 if (spec == GetActiveSpec() && !IsActionButtonDataValid(button,action,type,this))
5731 return NULL;
5733 // it create new button (NEW state) if need or return existed
5734 ActionButton& ab = m_actionButtons[spec][button];
5736 // set data and update to CHANGED if not NEW
5737 ab.SetActionAndType(action,ActionButtonType(type));
5739 sLog.outDetail("Player '%u' Added Action '%u' (type %u) to Button '%u' for spec %u", GetGUIDLow(), action, uint32(type), button, spec);
5740 return &ab;
5743 void Player::removeActionButton(uint8 spec, uint8 button)
5745 ActionButtonList& currentActionButtonList = m_actionButtons[spec];
5746 ActionButtonList::iterator buttonItr = currentActionButtonList.find(button);
5747 if (buttonItr == currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
5748 return;
5750 if (buttonItr->second.uState == ACTIONBUTTON_NEW)
5751 currentActionButtonList.erase(buttonItr); // new and not saved
5752 else
5753 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5755 sLog.outDetail("Action Button '%u' Removed from Player '%u' for spec %u", button, GetGUIDLow(), spec);
5758 ActionButton const* Player::GetActionButton(uint8 button)
5760 ActionButtonList& currentActionButtonList = m_actionButtons[m_activeSpec];
5761 ActionButtonList::iterator buttonItr = currentActionButtonList.find(button);
5762 if (buttonItr==currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
5763 return NULL;
5765 return &buttonItr->second;
5768 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5770 // prevent crash when a bad coord is sent by the client
5771 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5773 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5774 return false;
5777 Map *m = GetMap();
5779 const float old_x = GetPositionX();
5780 const float old_y = GetPositionY();
5781 const float old_z = GetPositionZ();
5782 const float old_r = GetOrientation();
5784 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5786 if (teleport || old_x != x || old_y != y || old_z != z)
5787 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5788 else
5789 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5791 // move and update visible state if need
5792 m->PlayerRelocation(this, x, y, z, orientation);
5794 // reread after Map::Relocation
5795 m = GetMap();
5796 x = GetPositionX();
5797 y = GetPositionY();
5798 z = GetPositionZ();
5800 // group update
5801 if(GetGroup() && (old_x != x || old_y != y))
5802 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5805 // code block for underwater state update
5806 UpdateUnderwaterState(m, x, y, z);
5808 CheckExploreSystem();
5810 return true;
5813 void Player::SaveRecallPosition()
5815 m_recallMap = GetMapId();
5816 m_recallX = GetPositionX();
5817 m_recallY = GetPositionY();
5818 m_recallZ = GetPositionZ();
5819 m_recallO = GetOrientation();
5822 void Player::SendMessageToSet(WorldPacket *data, bool self)
5824 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5825 if(_map)
5827 _map->MessageBroadcast(this, data, self);
5828 return;
5831 //if player is not in world and map in not created/already destroyed
5832 //no need to create one, just send packet for itself!
5833 if(self)
5834 GetSession()->SendPacket(data);
5837 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5839 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5840 if(_map)
5842 _map->MessageDistBroadcast(this, data, dist, self);
5843 return;
5846 if(self)
5847 GetSession()->SendPacket(data);
5850 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5852 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5853 if(_map)
5855 _map->MessageDistBroadcast(this, data, dist, self, own_team_only);
5856 return;
5859 if(self)
5860 GetSession()->SendPacket(data);
5863 void Player::SendDirectMessage(WorldPacket *data)
5865 GetSession()->SendPacket(data);
5868 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5870 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5871 data << uint32(CinematicSequenceId);
5872 SendDirectMessage(&data);
5875 void Player::SendMovieStart(uint32 MovieId)
5877 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5878 data << uint32(MovieId);
5879 SendDirectMessage(&data);
5882 void Player::CheckExploreSystem()
5884 if (!isAlive())
5885 return;
5887 if (isInFlight())
5888 return;
5890 uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5891 if(areaFlag==0xffff)
5892 return;
5893 int offset = areaFlag / 32;
5895 if(offset >= 128)
5897 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);
5898 return;
5901 uint32 val = (uint32)(1 << (areaFlag % 32));
5902 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5904 if( !(currFields & val) )
5906 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5908 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5910 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5911 if(!p)
5913 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5915 else if(p->area_level > 0)
5917 uint32 area = p->ID;
5918 if (getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
5920 SendExplorationExperience(area,0);
5922 else
5924 int32 diff = int32(getLevel()) - p->area_level;
5925 uint32 XP = 0;
5926 if (diff < -5)
5928 XP = uint32(sObjectMgr.GetBaseXP(getLevel()+5)*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
5930 else if (diff > 5)
5932 int32 exploration_percent = (100-((diff-5)*5));
5933 if (exploration_percent > 100)
5934 exploration_percent = 100;
5935 else if (exploration_percent < 0)
5936 exploration_percent = 0;
5938 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
5940 else
5942 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
5945 GiveXP( XP, NULL );
5946 SendExplorationExperience(area,XP);
5948 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5953 uint32 Player::TeamForRace(uint8 race)
5955 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5956 if(!rEntry)
5958 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5959 return ALLIANCE;
5962 switch(rEntry->TeamID)
5964 case 7: return ALLIANCE;
5965 case 1: return HORDE;
5968 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5969 return ALLIANCE;
5972 uint32 Player::getFactionForRace(uint8 race)
5974 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5975 if(!rEntry)
5977 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5978 return 0;
5981 return rEntry->FactionID;
5984 void Player::setFactionForRace(uint8 race)
5986 m_team = TeamForRace(race);
5987 setFaction( getFactionForRace(race) );
5990 ReputationRank Player::GetReputationRank(uint32 faction) const
5992 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5993 return GetReputationMgr().GetRank(factionEntry);
5996 //Calculate total reputation percent player gain with quest/creature level
5997 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5999 float percent = 100.0f;
6001 float rate = for_quest ? sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_KILL);
6003 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
6004 percent *= rate;
6006 float repMod = (float)GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
6008 if (!for_quest)
6009 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
6011 percent += rep > 0 ? repMod : -repMod;
6013 if (percent <= 0.0f)
6014 return 0;
6016 return int32(sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_GAIN)*rep*percent/100.0f);
6019 //Calculates how many reputation points player gains in victim's enemy factions
6020 void Player::RewardReputation(Unit *pVictim, float rate)
6022 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
6023 return;
6025 ReputationOnKillEntry const* Rep = sObjectMgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
6027 if(!Rep)
6028 return;
6030 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
6032 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
6033 donerep1 = int32(donerep1*rate);
6034 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
6035 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
6036 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
6037 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
6039 // Wiki: Team factions value divided by 2
6040 if (factionEntry1 && Rep->is_teamaward1)
6042 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
6043 if(team1_factionEntry)
6044 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
6048 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
6050 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
6051 donerep2 = int32(donerep2*rate);
6052 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
6053 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
6054 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
6055 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
6057 // Wiki: Team factions value divided by 2
6058 if (factionEntry2 && Rep->is_teamaward2)
6060 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
6061 if(team2_factionEntry)
6062 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
6067 //Calculate how many reputation points player gain with the quest
6068 void Player::RewardReputation(Quest const *pQuest)
6070 // quest reputation reward/loss
6071 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
6073 if (!pQuest->RewRepFaction[i])
6074 continue;
6076 // For future, this row should be used as "override". Example quests are 10298 and 10870.
6077 // Typically, no diplomacy mod must apply to the final value (flat). Note the formula must be (finalValue = DBvalue/100)
6078 if (pQuest->RewRepValue[i])
6080 int32 rep = CalculateReputationGain(GetQuestLevelForPlayer(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
6082 if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
6083 GetReputationMgr().ModifyReputation(factionEntry, rep);
6085 else
6087 uint32 row = ((pQuest->RewRepValueId[i] < 0) ? 1 : 0) + 1;
6088 uint32 field = abs(pQuest->RewRepValueId[i]);
6090 if (const QuestFactionRewardEntry *pRow = sQuestFactionRewardStore.LookupEntry(row))
6092 int32 repPoints = pRow->rewardValue[field];
6094 if (!repPoints)
6095 continue;
6097 repPoints = CalculateReputationGain(GetQuestLevelForPlayer(pQuest), repPoints, pQuest->RewRepFaction[i], true);
6099 if (const FactionEntry* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
6100 GetReputationMgr().ModifyReputation(factionEntry, repPoints);
6105 // TODO: implement reputation spillover
6108 void Player::UpdateArenaFields(void)
6110 /* arena calcs go here */
6113 void Player::UpdateHonorFields()
6115 /// called when rewarding honor and at each save
6116 time_t now = time(NULL);
6117 time_t today = (time(NULL) / DAY) * DAY;
6119 if(m_lastHonorUpdateTime < today)
6121 time_t yesterday = today - DAY;
6123 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
6125 // update yesterday's contribution
6126 if(m_lastHonorUpdateTime >= yesterday )
6128 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
6130 // this is the first update today, reset today's contribution
6131 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
6132 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
6134 else
6136 // no honor/kills yesterday or today, reset
6137 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
6138 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
6142 m_lastHonorUpdateTime = now;
6145 ///Calculate the amount of honor gained based on the victim
6146 ///and the size of the group for which the honor is divided
6147 ///An exact honor value can also be given (overriding the calcs)
6148 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
6150 // do not reward honor in arenas, but enable onkill spellproc
6151 if(InArena())
6153 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
6154 return false;
6156 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
6157 return false;
6159 return true;
6162 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6163 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
6164 return false;
6166 uint64 victim_guid = 0;
6167 uint32 victim_rank = 0;
6169 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6170 UpdateHonorFields();
6172 if(honor <= 0)
6174 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
6175 return false;
6177 victim_guid = uVictim->GetGUID();
6179 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6181 Player *pVictim = (Player *)uVictim;
6183 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6184 return false;
6186 float f = 1; //need for total kills (?? need more info)
6187 uint32 k_grey = 0;
6188 uint32 k_level = getLevel();
6189 uint32 v_level = pVictim->getLevel();
6192 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6193 // [0] Just name
6194 // [1..14] Alliance honor titles and player name
6195 // [15..28] Horde honor titles and player name
6196 // [29..38] Other title and player name
6197 // [39+] Nothing
6198 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6199 // Get Killer titles, CharTitlesEntry::bit_index
6200 // Ranks:
6201 // title[1..14] -> rank[5..18]
6202 // title[15..28] -> rank[5..18]
6203 // title[other] -> 0
6204 if (victim_title == 0)
6205 victim_guid = 0; // Don't show HK: <rank> message, only log.
6206 else if (victim_title < 15)
6207 victim_rank = victim_title + 4;
6208 else if (victim_title < 29)
6209 victim_rank = victim_title - 14 + 4;
6210 else
6211 victim_guid = 0; // Don't show HK: <rank> message, only log.
6214 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6216 if(v_level<=k_grey)
6217 return false;
6219 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6221 int32 v_rank =1; //need more info
6223 honor = ((f * diff_level * (190 + v_rank*10))/6);
6224 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6226 // count the number of playerkills in one day
6227 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6228 // and those in a lifetime
6229 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6230 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
6231 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
6232 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
6234 else
6236 Creature *cVictim = (Creature *)uVictim;
6238 if (!cVictim->isRacialLeader())
6239 return false;
6241 honor = 100; // ??? need more info
6242 victim_rank = 19; // HK: Leader
6246 if (uVictim != NULL)
6248 honor *= sWorld.getConfig(CONFIG_FLOAT_RATE_HONOR);
6249 honor *= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN) + 100.0f)/100.0f;
6251 if(groupsize > 1)
6252 honor /= groupsize;
6254 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6257 // honor - for show honor points in log
6258 // victim_guid - for show victim name in log
6259 // victim_rank [1..4] HK: <dishonored rank>
6260 // victim_rank [5..19] HK: <alliance\horde rank>
6261 // victim_rank [0,20+] HK: <>
6262 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6263 data << (uint32) honor;
6264 data << (uint64) victim_guid;
6265 data << (uint32) victim_rank;
6267 GetSession()->SendPacket(&data);
6269 // add honor points
6270 ModifyHonorPoints(int32(honor));
6272 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6273 return true;
6276 void Player::ModifyHonorPoints( int32 value )
6278 if(value < 0)
6280 if (GetHonorPoints() > sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS))
6281 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS) + value);
6282 else
6283 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6285 else
6286 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS));
6289 void Player::ModifyArenaPoints( int32 value )
6291 if(value < 0)
6293 if (GetArenaPoints() > sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS))
6294 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS) + value);
6295 else
6296 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6298 else
6299 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS));
6302 uint32 Player::GetGuildIdFromDB(uint64 guid)
6304 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6305 if(!result)
6306 return 0;
6308 uint32 id = result->Fetch()[0].GetUInt32();
6309 delete result;
6310 return id;
6313 uint32 Player::GetRankFromDB(uint64 guid)
6315 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6316 if( result )
6318 uint32 v = result->Fetch()[0].GetUInt32();
6319 delete result;
6320 return v;
6322 else
6323 return 0;
6326 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6328 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);
6329 if(!result)
6330 return 0;
6332 uint32 id = (*result)[0].GetUInt32();
6333 delete result;
6334 return id;
6337 uint32 Player::GetZoneIdFromDB(uint64 guid)
6339 uint32 guidLow = GUID_LOPART(guid);
6340 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6341 if (!result)
6342 return 0;
6343 Field* fields = result->Fetch();
6344 uint32 zone = fields[0].GetUInt32();
6345 delete result;
6347 if (!zone)
6349 // stored zone is zero, use generic and slow zone detection
6350 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6351 if( !result )
6352 return 0;
6353 fields = result->Fetch();
6354 uint32 map = fields[0].GetUInt32();
6355 float posx = fields[1].GetFloat();
6356 float posy = fields[2].GetFloat();
6357 float posz = fields[3].GetFloat();
6358 delete result;
6360 zone = sMapMgr.GetZoneId(map,posx,posy,posz);
6362 if (zone > 0)
6363 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6366 return zone;
6369 uint32 Player::GetLevelFromDB(uint64 guid)
6371 QueryResult *result = CharacterDatabase.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid) );
6372 if (!result)
6373 return 0;
6375 Field* fields = result->Fetch();
6376 uint32 level = fields[0].GetUInt32();
6377 delete result;
6379 return level;
6382 void Player::UpdateArea(uint32 newArea)
6384 // FFA_PVP flags are area and not zone id dependent
6385 // so apply them accordingly
6386 m_areaUpdateId = newArea;
6388 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6390 if(area && (area->flags & AREA_FLAG_ARENA))
6392 if(!isGameMaster())
6393 SetFFAPvP(true);
6395 else
6397 // remove ffa flag only if not ffapvp realm
6398 // removal in sanctuaries and capitals is handled in zone update
6399 if(IsFFAPvP() && !sWorld.IsFFAPvPRealm())
6400 SetFFAPvP(false);
6403 UpdateAreaDependentAuras(newArea);
6406 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6408 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6409 if(!zone)
6410 return;
6412 if(m_zoneUpdateId != newZone)
6414 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6416 if (sWorld.getConfig(CONFIG_BOOL_WEATHER))
6418 if(Weather *wth = sWorld.FindWeather(zone->ID))
6419 wth->SendWeatherUpdateToPlayer(this);
6420 else if(!sWorld.AddWeather(zone->ID))
6422 // send fine weather packet to remove old zone's weather
6423 Weather::SendFineWeatherUpdateToPlayer(this);
6428 m_zoneUpdateId = newZone;
6429 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6431 // zone changed, so area changed as well, update it
6432 UpdateArea(newArea);
6434 // in PvP, any not controlled zone (except zone->team == 6, default case)
6435 // in PvE, only opposition team capital
6436 switch(zone->team)
6438 case AREATEAM_ALLY:
6439 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6440 break;
6441 case AREATEAM_HORDE:
6442 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6443 break;
6444 case AREATEAM_NONE:
6445 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6446 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6447 break;
6448 default: // 6 in fact
6449 pvpInfo.inHostileArea = false;
6450 break;
6453 if(pvpInfo.inHostileArea) // in hostile area
6455 if(!IsPvP() || pvpInfo.endTimer != 0)
6456 UpdatePvP(true, true);
6458 else // in friendly area
6460 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6461 pvpInfo.endTimer = time(0); // start toggle-off
6464 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6466 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6467 if(sWorld.IsFFAPvPRealm())
6468 SetFFAPvP(false);
6470 else
6472 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6475 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6477 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6478 SetRestType(REST_TYPE_IN_CITY);
6479 InnEnter(time(0),GetMapId(),0,0,0);
6481 if(sWorld.IsFFAPvPRealm())
6482 SetFFAPvP(false);
6484 else // anywhere else
6486 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6488 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6490 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6492 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6493 SetRestType(REST_TYPE_NO);
6495 if(sWorld.IsFFAPvPRealm())
6496 SetFFAPvP(true);
6499 else // not in tavern (leave city then)
6501 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6502 SetRestType(REST_TYPE_NO);
6504 // Set player to FFA PVP when not in rested environment.
6505 if(sWorld.IsFFAPvPRealm())
6506 SetFFAPvP(true);
6511 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6512 // if player resurrected at teleport this will be applied in resurrect code
6513 if(isAlive())
6514 DestroyZoneLimitedItem( true, newZone );
6516 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6517 AutoUnequipOffhandIfNeed();
6519 // recent client version not send leave/join channel packets for built-in local channels
6520 UpdateLocalChannels( newZone );
6522 // group update
6523 if(GetGroup())
6524 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6526 UpdateZoneDependentAuras(newZone);
6529 //If players are too far way of duel flag... then player loose the duel
6530 void Player::CheckDuelDistance(time_t currTime)
6532 if(!duel)
6533 return;
6535 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6536 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6537 if(!obj)
6538 return;
6540 if(duel->outOfBound == 0)
6542 if(!IsWithinDistInMap(obj, 50))
6544 duel->outOfBound = currTime;
6546 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6547 GetSession()->SendPacket(&data);
6550 else
6552 if(IsWithinDistInMap(obj, 40))
6554 duel->outOfBound = 0;
6556 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6557 GetSession()->SendPacket(&data);
6559 else if(currTime >= (duel->outOfBound+10))
6561 DuelComplete(DUEL_FLED);
6566 void Player::DuelComplete(DuelCompleteType type)
6568 // duel not requested
6569 if(!duel)
6570 return;
6572 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6573 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6574 GetSession()->SendPacket(&data);
6575 duel->opponent->GetSession()->SendPacket(&data);
6577 if(type != DUEL_INTERUPTED)
6579 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6580 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6581 data << duel->opponent->GetName();
6582 data << GetName();
6583 SendMessageToSet(&data,true);
6586 if (type == DUEL_WON)
6588 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6589 if (duel->opponent)
6590 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6593 //Remove Duel Flag object
6594 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6595 if(obj)
6596 duel->initiator->RemoveGameObject(obj,true);
6598 /* remove auras */
6599 std::vector<uint32> auras2remove;
6600 AuraMap const& vAuras = duel->opponent->GetAuras();
6601 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6603 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6604 auras2remove.push_back(i->second->GetId());
6607 for(size_t i=0; i<auras2remove.size(); ++i)
6608 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6610 auras2remove.clear();
6611 AuraMap const& auras = GetAuras();
6612 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6614 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6615 auras2remove.push_back(i->second->GetId());
6617 for(size_t i=0; i<auras2remove.size(); ++i)
6618 RemoveAurasDueToSpell(auras2remove[i]);
6620 // cleanup combo points
6621 if(GetComboTarget()==duel->opponent->GetGUID())
6622 ClearComboPoints();
6623 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6624 ClearComboPoints();
6626 if(duel->opponent->GetComboTarget()==GetGUID())
6627 duel->opponent->ClearComboPoints();
6628 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6629 duel->opponent->ClearComboPoints();
6631 //cleanups
6632 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6633 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6634 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6635 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6637 delete duel->opponent->duel;
6638 duel->opponent->duel = NULL;
6639 delete duel;
6640 duel = NULL;
6643 //---------------------------------------------------------//
6645 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6647 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6648 return;
6650 // not apply/remove mods for broken item
6651 if(item->IsBroken())
6652 return;
6654 ItemPrototype const *proto = item->GetProto();
6656 if(!proto)
6657 return;
6659 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6661 uint32 attacktype = Player::GetAttackBySlot(slot);
6662 if(attacktype < MAX_ATTACK)
6663 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6665 _ApplyItemBonuses(proto,slot,apply);
6667 if( slot==EQUIPMENT_SLOT_RANGED )
6668 _ApplyAmmoBonuses();
6670 ApplyItemEquipSpell(item,apply);
6671 ApplyEnchantment(item, apply);
6673 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6674 CorrectMetaGemEnchants(slot, apply);
6676 sLog.outDebug("_ApplyItemMods complete.");
6679 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
6681 if (slot >= INVENTORY_SLOT_BAG_END || !proto)
6682 return;
6684 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
6685 if (only_level_scale && !ssd)
6686 return;
6688 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6689 uint32 ssd_level = getLevel();
6690 if (ssd && ssd_level > ssd->MaxLevel)
6691 ssd_level = ssd->MaxLevel;
6693 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
6694 if (only_level_scale && !ssv)
6695 return;
6697 for (uint32 i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6699 uint32 statType = 0;
6700 int32 val = 0;
6701 // If set ScalingStatDistribution need get stats and values from it
6702 if (ssd && ssv)
6704 if (ssd->StatMod[i] < 0)
6705 continue;
6706 statType = ssd->StatMod[i];
6707 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6709 else
6711 if (i >= proto->StatsCount)
6712 continue;
6713 statType = proto->ItemStat[i].ItemStatType;
6714 val = proto->ItemStat[i].ItemStatValue;
6717 if(val == 0)
6718 continue;
6720 switch (statType)
6722 case ITEM_MOD_MANA:
6723 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6724 break;
6725 case ITEM_MOD_HEALTH: // modify HP
6726 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6727 break;
6728 case ITEM_MOD_AGILITY: // modify agility
6729 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6730 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6731 break;
6732 case ITEM_MOD_STRENGTH: //modify strength
6733 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6734 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6735 break;
6736 case ITEM_MOD_INTELLECT: //modify intellect
6737 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6738 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6739 break;
6740 case ITEM_MOD_SPIRIT: //modify spirit
6741 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6742 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6743 break;
6744 case ITEM_MOD_STAMINA: //modify stamina
6745 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6746 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6747 break;
6748 case ITEM_MOD_DEFENSE_SKILL_RATING:
6749 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6750 break;
6751 case ITEM_MOD_DODGE_RATING:
6752 ApplyRatingMod(CR_DODGE, int32(val), apply);
6753 break;
6754 case ITEM_MOD_PARRY_RATING:
6755 ApplyRatingMod(CR_PARRY, int32(val), apply);
6756 break;
6757 case ITEM_MOD_BLOCK_RATING:
6758 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6759 break;
6760 case ITEM_MOD_HIT_MELEE_RATING:
6761 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6762 break;
6763 case ITEM_MOD_HIT_RANGED_RATING:
6764 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6765 break;
6766 case ITEM_MOD_HIT_SPELL_RATING:
6767 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6768 break;
6769 case ITEM_MOD_CRIT_MELEE_RATING:
6770 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6771 break;
6772 case ITEM_MOD_CRIT_RANGED_RATING:
6773 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6774 break;
6775 case ITEM_MOD_CRIT_SPELL_RATING:
6776 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6777 break;
6778 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6779 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6780 break;
6781 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6782 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6783 break;
6784 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6785 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6786 break;
6787 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6788 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6789 break;
6790 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6791 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6792 break;
6793 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6794 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6795 break;
6796 case ITEM_MOD_HASTE_MELEE_RATING:
6797 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6798 break;
6799 case ITEM_MOD_HASTE_RANGED_RATING:
6800 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6801 break;
6802 case ITEM_MOD_HASTE_SPELL_RATING:
6803 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6804 break;
6805 case ITEM_MOD_HIT_RATING:
6806 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6807 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6808 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6809 break;
6810 case ITEM_MOD_CRIT_RATING:
6811 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6812 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6813 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6814 break;
6815 case ITEM_MOD_HIT_TAKEN_RATING:
6816 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6817 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6818 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6819 break;
6820 case ITEM_MOD_CRIT_TAKEN_RATING:
6821 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6822 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6823 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6824 break;
6825 case ITEM_MOD_RESILIENCE_RATING:
6826 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6827 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6828 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6829 break;
6830 case ITEM_MOD_HASTE_RATING:
6831 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6832 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6833 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6834 break;
6835 case ITEM_MOD_EXPERTISE_RATING:
6836 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6837 break;
6838 case ITEM_MOD_ATTACK_POWER:
6839 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6840 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6841 break;
6842 case ITEM_MOD_RANGED_ATTACK_POWER:
6843 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6844 break;
6845 case ITEM_MOD_MANA_REGENERATION:
6846 ApplyManaRegenBonus(int32(val), apply);
6847 break;
6848 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6849 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6850 break;
6851 case ITEM_MOD_SPELL_POWER:
6852 ApplySpellPowerBonus(int32(val), apply);
6853 break;
6854 // depricated item mods
6855 case ITEM_MOD_FERAL_ATTACK_POWER:
6856 case ITEM_MOD_SPELL_HEALING_DONE:
6857 case ITEM_MOD_SPELL_DAMAGE_DONE:
6858 break;
6862 // Apply Spell Power from ScalingStatValue if set
6863 if(ssv)
6865 if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
6866 ApplySpellPowerBonus(spellbonus, apply);
6869 // If set ScalingStatValue armor get it or use item armor
6870 uint32 armor = proto->Armor;
6871 if (ssv)
6873 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6874 armor = ssvarmor;
6876 // Add armor bonus from ArmorDamageModifier if > 0
6877 if (proto->ArmorDamageModifier > 0)
6878 armor += uint32(proto->ArmorDamageModifier);
6880 if (armor)
6881 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6883 if (proto->Block)
6884 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6886 if (proto->HolyRes)
6887 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6889 if (proto->FireRes)
6890 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6892 if (proto->NatureRes)
6893 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6895 if (proto->FrostRes)
6896 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6898 if (proto->ShadowRes)
6899 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6901 if (proto->ArcaneRes)
6902 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6904 WeaponAttackType attType = BASE_ATTACK;
6905 float damage = 0.0f;
6907 if( slot == EQUIPMENT_SLOT_RANGED && (
6908 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6909 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6911 attType = RANGED_ATTACK;
6913 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6915 attType = OFF_ATTACK;
6918 float minDamage = proto->Damage[0].DamageMin;
6919 float maxDamage = proto->Damage[0].DamageMax;
6920 int32 extraDPS = 0;
6921 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6922 if (ssv)
6924 if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue)))
6926 float average = extraDPS * proto->Delay / 1000.0f;
6927 minDamage = 0.7f * average;
6928 maxDamage = 1.3f * average;
6931 if (minDamage > 0 )
6933 damage = apply ? minDamage : BASE_MINDAMAGE;
6934 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6935 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6938 if (maxDamage > 0 )
6940 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6941 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6944 // Apply feral bonus from ScalingStatValue if set
6945 if (ssv)
6947 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6948 ApplyFeralAPBonus(feral_bonus, apply);
6950 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6951 if(getClass() == CLASS_DRUID)
6953 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6954 if (feral_bonus > 0)
6955 ApplyFeralAPBonus(feral_bonus, apply);
6958 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6959 return;
6961 if (proto->Delay)
6963 if(slot == EQUIPMENT_SLOT_RANGED)
6964 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6965 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6966 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6967 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6968 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6971 if(CanModifyStats() && (damage || proto->Delay))
6972 UpdateDamagePhysical(attType);
6975 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6977 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6978 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6979 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6981 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6982 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6983 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6985 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6986 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6987 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6990 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6992 // generic not weapon specific case processes in aura code
6993 if(aura->GetSpellProto()->EquippedItemClass == -1)
6994 return;
6996 BaseModGroup mod = BASEMOD_END;
6997 switch(attackType)
6999 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
7000 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
7001 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
7002 default: return;
7005 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
7007 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
7011 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
7013 // ignore spell mods for not wands
7014 Modifier const* modifier = aura->GetModifier();
7015 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
7016 return;
7018 // generic not weapon specific case processes in aura code
7019 if(aura->GetSpellProto()->EquippedItemClass == -1)
7020 return;
7022 UnitMods unitMod = UNIT_MOD_END;
7023 switch(attackType)
7025 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
7026 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
7027 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
7028 default: return;
7031 UnitModifierType unitModType = TOTAL_VALUE;
7032 switch(modifier->m_auraname)
7034 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
7035 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
7036 default: return;
7039 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
7041 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
7045 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
7047 if(!item)
7048 return;
7050 ItemPrototype const *proto = item->GetProto();
7051 if(!proto)
7052 return;
7054 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7056 _Spell const& spellData = proto->Spells[i];
7058 // no spell
7059 if(!spellData.SpellId )
7060 continue;
7062 // wrong triggering type
7063 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
7064 continue;
7066 // check if it is valid spell
7067 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
7068 if(!spellproto)
7069 continue;
7071 ApplyEquipSpell(spellproto,item,apply,form_change);
7075 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
7077 if(apply)
7079 // Cannot be used in this stance/form
7080 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
7081 return;
7083 if(form_change) // check aura active state from other form
7085 bool found = false;
7086 for (int k=0; k < MAX_EFFECT_INDEX; ++k)
7088 spellEffectPair spair = spellEffectPair(spellInfo->Id, SpellEffectIndex(k));
7089 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
7091 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
7093 found = true;
7094 break;
7097 if(found)
7098 break;
7101 if(found) // and skip re-cast already active aura at form change
7102 return;
7105 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
7107 CastSpell(this,spellInfo,true,item);
7109 else
7111 if(form_change) // check aura compatibility
7113 // Cannot be used in this stance/form
7114 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
7115 return; // and remove only not compatible at form change
7118 if(item)
7119 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
7120 else
7121 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
7125 void Player::UpdateEquipSpellsAtFormChange()
7127 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7129 if(m_items[i] && !m_items[i]->IsBroken())
7131 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
7132 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
7136 // item set bonuses not dependent from item broken state
7137 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
7139 ItemSetEffect* eff = ItemSetEff[setindex];
7140 if(!eff)
7141 continue;
7143 for(uint32 y=0;y<8; ++y)
7145 SpellEntry const* spellInfo = eff->spells[y];
7146 if(!spellInfo)
7147 continue;
7149 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
7150 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
7155 void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
7157 Item *item = GetWeaponForAttack(attType, true, false);
7158 if(!item)
7159 return;
7161 ItemPrototype const *proto = item->GetProto();
7162 if(!proto)
7163 return;
7165 if (!Target || Target == this )
7166 return;
7168 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7170 _Spell const& spellData = proto->Spells[i];
7172 // no spell
7173 if(!spellData.SpellId )
7174 continue;
7176 // wrong triggering type
7177 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7178 continue;
7180 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7181 if(!spellInfo)
7183 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7184 continue;
7187 // not allow proc extra attack spell at extra attack
7188 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7189 return;
7191 float chance = (float)spellInfo->procChance;
7193 if(spellData.SpellPPMRate)
7195 uint32 WeaponSpeed = proto->Delay;
7196 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7198 else if(chance > 100.0f)
7200 chance = GetWeaponProcChance();
7203 if (roll_chance_f(chance))
7204 CastSpell(Target, spellInfo->Id, true, item);
7207 // item combat enchantments
7208 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7210 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7211 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7212 if(!pEnchant) continue;
7213 for (int s = 0; s < 3; ++s)
7215 if (pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7216 continue;
7218 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7219 if (!spellInfo)
7221 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7222 continue;
7225 // Use first rank to access spell item enchant procs
7226 float ppmRate = sSpellMgr.GetItemEnchantProcChance(spellInfo->Id);
7228 float chance = ppmRate
7229 ? GetPPMProcChance(proto->Delay, ppmRate)
7230 : pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7233 ApplySpellMod(spellInfo->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
7234 ApplySpellMod(spellInfo->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
7236 if (roll_chance_f(chance))
7238 if(IsPositiveSpell(pEnchant->spellid[s]))
7239 CastSpell(this, pEnchant->spellid[s], true, item);
7240 else
7241 CastSpell(Target, pEnchant->spellid[s], true, item);
7247 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7249 ItemPrototype const* proto = item->GetProto();
7250 // special learning case
7251 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7253 uint32 learn_spell_id = proto->Spells[0].SpellId;
7254 uint32 learning_spell_id = proto->Spells[1].SpellId;
7256 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7257 if (!spellInfo)
7259 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7260 SendEquipError(EQUIP_ERR_NONE, item);
7261 return;
7264 Spell *spell = new Spell(this, spellInfo, false);
7265 spell->m_CastItem = item;
7266 spell->m_cast_count = cast_count; //set count of casts
7267 spell->m_currentBasePoints[0] = learning_spell_id;
7268 spell->prepare(&targets);
7269 return;
7272 // use triggered flag only for items with many spell casts and for not first cast
7273 int count = 0;
7275 // item spells casted at use
7276 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7278 _Spell const& spellData = proto->Spells[i];
7280 // no spell
7281 if(!spellData.SpellId)
7282 continue;
7284 // wrong triggering type
7285 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7286 continue;
7288 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7289 if(!spellInfo)
7291 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7292 continue;
7295 Spell *spell = new Spell(this, spellInfo, (count > 0));
7296 spell->m_CastItem = item;
7297 spell->m_cast_count = cast_count; // set count of casts
7298 spell->m_glyphIndex = glyphIndex; // glyph index
7299 spell->prepare(&targets);
7301 ++count;
7304 // Item enchantments spells casted at use
7305 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7307 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7308 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7309 if(!pEnchant) continue;
7310 for (int s = 0; s < 3; ++s)
7312 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7313 continue;
7315 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7316 if (!spellInfo)
7318 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7319 continue;
7322 Spell *spell = new Spell(this, spellInfo, (count > 0));
7323 spell->m_CastItem = item;
7324 spell->m_cast_count = cast_count; // set count of casts
7325 spell->m_glyphIndex = glyphIndex; // glyph index
7326 spell->prepare(&targets);
7328 ++count;
7333 void Player::_RemoveAllItemMods()
7335 sLog.outDebug("_RemoveAllItemMods start.");
7337 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7339 if(m_items[i])
7341 ItemPrototype const *proto = m_items[i]->GetProto();
7342 if(!proto)
7343 continue;
7345 // item set bonuses not dependent from item broken state
7346 if(proto->ItemSet)
7347 RemoveItemsSetItem(this,proto);
7349 if(m_items[i]->IsBroken())
7350 continue;
7352 ApplyItemEquipSpell(m_items[i],false);
7353 ApplyEnchantment(m_items[i], false);
7357 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7359 if(m_items[i])
7361 if(m_items[i]->IsBroken())
7362 continue;
7363 ItemPrototype const *proto = m_items[i]->GetProto();
7364 if(!proto)
7365 continue;
7367 uint32 attacktype = Player::GetAttackBySlot(i);
7368 if(attacktype < MAX_ATTACK)
7369 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7371 _ApplyItemBonuses(proto,i, false);
7373 if( i == EQUIPMENT_SLOT_RANGED )
7374 _ApplyAmmoBonuses();
7378 sLog.outDebug("_RemoveAllItemMods complete.");
7381 void Player::_ApplyAllItemMods()
7383 sLog.outDebug("_ApplyAllItemMods start.");
7385 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7387 if(m_items[i])
7389 if(m_items[i]->IsBroken())
7390 continue;
7392 ItemPrototype const *proto = m_items[i]->GetProto();
7393 if(!proto)
7394 continue;
7396 uint32 attacktype = Player::GetAttackBySlot(i);
7397 if(attacktype < MAX_ATTACK)
7398 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7400 _ApplyItemBonuses(proto,i, true);
7402 if( i == EQUIPMENT_SLOT_RANGED )
7403 _ApplyAmmoBonuses();
7407 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7409 if(m_items[i])
7411 ItemPrototype const *proto = m_items[i]->GetProto();
7412 if(!proto)
7413 continue;
7415 // item set bonuses not dependent from item broken state
7416 if(proto->ItemSet)
7417 AddItemsSetItem(this,m_items[i]);
7419 if(m_items[i]->IsBroken())
7420 continue;
7422 ApplyItemEquipSpell(m_items[i],true);
7423 ApplyEnchantment(m_items[i], true);
7427 sLog.outDebug("_ApplyAllItemMods complete.");
7430 void Player::_ApplyAllLevelScaleItemMods(bool apply)
7432 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7434 if(m_items[i])
7436 if(m_items[i]->IsBroken())
7437 continue;
7439 ItemPrototype const *proto = m_items[i]->GetProto();
7440 if(!proto)
7441 continue;
7443 _ApplyItemBonuses(proto,i, apply, true);
7448 void Player::_ApplyAmmoBonuses()
7450 // check ammo
7451 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7452 if(!ammo_id)
7453 return;
7455 float currentAmmoDPS;
7457 ItemPrototype const *ammo_proto = ObjectMgr::GetItemPrototype( ammo_id );
7458 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7459 currentAmmoDPS = 0.0f;
7460 else
7461 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7463 if(currentAmmoDPS == GetAmmoDPS())
7464 return;
7466 m_ammoDPS = currentAmmoDPS;
7468 if(CanModifyStats())
7469 UpdateDamagePhysical(RANGED_ATTACK);
7472 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7474 if(!ammo_proto)
7475 return false;
7477 // check ranged weapon
7478 Item *weapon = GetWeaponForAttack( RANGED_ATTACK, true, false );
7479 if (!weapon)
7480 return false;
7482 ItemPrototype const* weapon_proto = weapon->GetProto();
7483 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7484 return false;
7486 // check ammo ws. weapon compatibility
7487 switch(weapon_proto->SubClass)
7489 case ITEM_SUBCLASS_WEAPON_BOW:
7490 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7491 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7492 return false;
7493 break;
7494 case ITEM_SUBCLASS_WEAPON_GUN:
7495 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7496 return false;
7497 break;
7498 default:
7499 return false;
7502 return true;
7505 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7506 Called by remove insignia spell effect */
7507 void Player::RemovedInsignia(Player* looterPlr)
7509 if (!GetBattleGroundId())
7510 return;
7512 // If not released spirit, do it !
7513 if(m_deathTimer > 0)
7515 m_deathTimer = 0;
7516 BuildPlayerRepop();
7517 RepopAtGraveyard();
7520 Corpse *corpse = GetCorpse();
7521 if (!corpse)
7522 return;
7524 // We have to convert player corpse to bones, not to be able to resurrect there
7525 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7526 Corpse *bones = sObjectAccessor.ConvertCorpseForPlayer(GetGUID(),true);
7527 if (!bones)
7528 return;
7530 // Now we must make bones lootable, and send player loot
7531 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7533 // We store the level of our player in the gold field
7534 // We retrieve this information at Player::SendLoot()
7535 bones->loot.gold = getLevel();
7536 bones->lootRecipient = looterPlr;
7537 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7540 void Player::SendLootRelease(ObjectGuid guid)
7542 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7543 data << guid;
7544 data << uint8(1);
7545 SendDirectMessage( &data );
7548 void Player::SendLoot(ObjectGuid guid, LootType loot_type)
7550 if (uint64 lguid = GetLootGUID())
7551 m_session->DoLootRelease(lguid);
7553 Loot *loot = 0;
7554 PermissionTypes permission = ALL_PERMISSION;
7556 sLog.outDebug("Player::SendLoot");
7557 switch(guid.GetHigh())
7559 case HIGHGUID_GAMEOBJECT:
7561 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7562 GameObject *go = GetMap()->GetGameObject(guid);
7564 // not check distance for GO in case owned GO (fishing bobber case, for example)
7565 // And permit out of range GO with no owner in case fishing hole
7566 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7568 SendLootRelease(guid);
7569 return;
7572 loot = &go->loot;
7574 if (go->getLootState() == GO_READY)
7576 uint32 lootid = go->GetGOInfo()->GetLootId();
7577 if ((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S))
7578 if (BattleGround *bg = GetBattleGround())
7579 if (bg->GetTypeID() == BATTLEGROUND_AV)
7580 if (!(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(go->GetEntry(), GetTeam())))
7582 SendLootRelease(guid);
7583 return;
7586 if (lootid)
7588 sLog.outDebug(" if(lootid)");
7589 loot->clear();
7590 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7593 if (loot_type == LOOT_FISHING)
7594 go->getFishLoot(loot,this);
7596 go->SetLootState(GO_ACTIVATED);
7598 break;
7600 case HIGHGUID_ITEM:
7602 Item *item = GetItemByGuid( guid );
7604 if (!item)
7606 SendLootRelease(guid);
7607 return;
7610 loot = &item->loot;
7612 if (!item->m_lootGenerated)
7614 item->m_lootGenerated = true;
7615 loot->clear();
7617 switch(loot_type)
7619 case LOOT_DISENCHANTING:
7620 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7621 break;
7622 case LOOT_PROSPECTING:
7623 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7624 break;
7625 case LOOT_MILLING:
7626 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7627 break;
7628 default:
7629 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7630 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7631 break;
7634 break;
7636 case HIGHGUID_CORPSE: // remove insignia
7638 Corpse *bones = GetMap()->GetCorpse(guid);
7640 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7642 SendLootRelease(guid);
7643 return;
7646 loot = &bones->loot;
7648 if (!bones->lootForBody)
7650 bones->lootForBody = true;
7651 uint32 pLevel = bones->loot.gold;
7652 bones->loot.clear();
7653 if (GetBattleGround()->GetTypeID() == BATTLEGROUND_AV)
7654 loot->FillLoot(0, LootTemplates_Creature, this, false);
7655 // It may need a better formula
7656 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7657 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY) );
7660 if (bones->lootRecipient != this)
7661 permission = NONE_PERMISSION;
7662 break;
7664 case HIGHGUID_UNIT:
7666 Creature *creature = GetMap()->GetCreature(guid);
7668 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7669 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7671 SendLootRelease(guid);
7672 return;
7675 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7677 SendLootRelease(guid);
7678 return;
7681 loot = &creature->loot;
7683 if (loot_type == LOOT_PICKPOCKETING)
7685 if (!creature->lootForPickPocketed)
7687 creature->lootForPickPocketed = true;
7688 loot->clear();
7690 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7691 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7693 // Generate extra money for pick pocket loot
7694 const uint32 a = urand(0, creature->getLevel()/2);
7695 const uint32 b = urand(0, getLevel()/2);
7696 loot->gold = uint32(10 * (a + b) * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY));
7699 else
7701 // the player whose group may loot the corpse
7702 Player *recipient = creature->GetLootRecipient();
7703 if (!recipient)
7705 creature->SetLootRecipient(this);
7706 recipient = this;
7709 if (creature->lootForPickPocketed)
7711 creature->lootForPickPocketed = false;
7712 loot->clear();
7715 if (!creature->lootForBody)
7717 creature->lootForBody = true;
7718 loot->clear();
7720 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7721 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7723 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7725 if (Group* group = recipient->GetGroup())
7727 group->UpdateLooterGuid(creature,true);
7729 switch (group->GetLootMethod())
7731 case GROUP_LOOT:
7732 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7733 group->GroupLoot(recipient->GetGUID(), loot, creature);
7734 break;
7735 case NEED_BEFORE_GREED:
7736 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7737 break;
7738 case MASTER_LOOT:
7739 group->MasterLoot(recipient->GetGUID(), loot, creature);
7740 break;
7741 default:
7742 break;
7747 // possible only if creature->lootForBody && loot->empty() at spell cast check
7748 if (loot_type == LOOT_SKINNING)
7750 loot->clear();
7751 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7753 // set group rights only for loot_type != LOOT_SKINNING
7754 else
7756 if(Group* group = GetGroup())
7758 if (group == recipient->GetGroup())
7760 if (group->GetLootMethod() == FREE_FOR_ALL)
7761 permission = ALL_PERMISSION;
7762 else if (group->GetLooterGuid() == GetGUID())
7764 if (group->GetLootMethod() == MASTER_LOOT)
7765 permission = MASTER_PERMISSION;
7766 else
7767 permission = ALL_PERMISSION;
7769 else
7770 permission = GROUP_PERMISSION;
7772 else
7773 permission = NONE_PERMISSION;
7775 else if (recipient == this)
7776 permission = ALL_PERMISSION;
7777 else
7778 permission = NONE_PERMISSION;
7781 break;
7783 default:
7785 sLog.outError("%s is unsupported for looting.", guid.GetString().c_str());
7786 return;
7790 SetLootGUID(guid);
7792 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7793 switch(loot_type)
7795 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7796 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7797 default: break;
7800 // need know merged fishing/corpse loot type for achievements
7801 loot->loot_type = loot_type;
7803 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7805 data << guid;
7806 data << uint8(loot_type);
7807 data << LootView(*loot, this, permission);
7809 SendDirectMessage(&data);
7811 // add 'this' player as one of the players that are looting 'loot'
7812 if (permission != NONE_PERMISSION)
7813 loot->AddLooter(GetGUID());
7815 if (loot_type == LOOT_CORPSE && !guid.IsItem())
7816 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7819 void Player::SendNotifyLootMoneyRemoved()
7821 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7822 GetSession()->SendPacket( &data );
7825 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7827 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7828 data << uint8(lootSlot);
7829 GetSession()->SendPacket( &data );
7832 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7834 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7835 data << Field;
7836 data << Value;
7837 GetSession()->SendPacket(&data);
7840 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7842 // data depends on zoneid/mapid...
7843 BattleGround* bg = GetBattleGround();
7844 uint16 NumberOfFields = 0;
7845 uint32 mapid = GetMapId();
7847 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7849 // may be exist better way to do this...
7850 switch(zoneid)
7852 case 0:
7853 case 1:
7854 case 4:
7855 case 8:
7856 case 10:
7857 case 11:
7858 case 12:
7859 case 36:
7860 case 38:
7861 case 40:
7862 case 41:
7863 case 51:
7864 case 267:
7865 case 1519:
7866 case 1537:
7867 case 2257:
7868 case 2918:
7869 NumberOfFields = 8;
7870 break;
7871 case 139:
7872 NumberOfFields = 41;
7873 break;
7874 case 1377:
7875 NumberOfFields = 15;
7876 break;
7877 case 2597:
7878 NumberOfFields = 83;
7879 break;
7880 case 3277:
7881 NumberOfFields = 16;
7882 break;
7883 case 3358:
7884 case 3820:
7885 NumberOfFields = 40;
7886 break;
7887 case 3483:
7888 NumberOfFields = 27;
7889 break;
7890 case 3518:
7891 NumberOfFields = 39;
7892 break;
7893 case 3519:
7894 NumberOfFields = 38;
7895 break;
7896 case 3521:
7897 NumberOfFields = 37;
7898 break;
7899 case 3698:
7900 case 3702:
7901 case 3968:
7902 NumberOfFields = 11;
7903 break;
7904 case 3703:
7905 NumberOfFields = 11;
7906 break;
7907 default:
7908 NumberOfFields = 12;
7909 break;
7912 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7913 data << uint32(mapid); // mapid
7914 data << uint32(zoneid); // zone id
7915 data << uint32(areaid); // area id, new 2.1.0
7916 data << uint16(NumberOfFields); // count of uint64 blocks
7917 data << uint32(0x8d8) << uint32(0x0); // 1
7918 data << uint32(0x8d7) << uint32(0x0); // 2
7919 data << uint32(0x8d6) << uint32(0x0); // 3
7920 data << uint32(0x8d5) << uint32(0x0); // 4
7921 data << uint32(0x8d4) << uint32(0x0); // 5
7922 data << uint32(0x8d3) << uint32(0x0); // 6
7923 // 7 1 - Arena season in progress, 0 - end of season
7924 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_BOOL_ARENA_SEASON_IN_PROGRESS));
7925 // 8 Arena season id
7926 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID));
7927 if(mapid == 530) // Outland
7929 data << uint32(0x9bf) << uint32(0x0); // 7
7930 data << uint32(0x9bd) << uint32(0xF); // 8
7931 data << uint32(0x9bb) << uint32(0xF); // 9
7933 switch(zoneid)
7935 case 1:
7936 case 11:
7937 case 12:
7938 case 38:
7939 case 40:
7940 case 51:
7941 case 1519:
7942 case 1537:
7943 case 2257:
7944 break;
7945 case 2597: // AV
7946 if (bg && bg->GetTypeID() == BATTLEGROUND_AV)
7947 bg->FillInitialWorldStates(data);
7948 else
7950 data << uint32(0x7ae) << uint32(0x1); // 7 snowfall n
7951 data << uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
7952 data << uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
7953 data << uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
7954 data << uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
7955 data << uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
7956 data << uint32(0x567) << uint32(0x1); // 13 frostwolfe c
7957 data << uint32(0x566) << uint32(0x1); // 14 frostwolfw c
7958 data << uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
7959 data << uint32(0x544) << uint32(0x0); // 16 ice grave a_a
7960 data << uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
7961 data << uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
7962 data << uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
7963 data << uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
7964 data << uint32(0x574) << uint32(0x0); // 21 1396 unk
7965 data << uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
7966 data << uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
7967 data << uint32(0x56f) << uint32(0x0); // 24 1391 unk
7968 data << uint32(0x56e) << uint32(0x0); // 25 iceblood a
7969 data << uint32(0x56d) << uint32(0x0); // 26 towerp a
7970 data << uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
7971 data << uint32(0x56b) << uint32(0x0); // 28 froswolfw a
7972 data << uint32(0x56a) << uint32(0x1); // 29 1386 unk
7973 data << uint32(0x569) << uint32(0x1); // 30 iceblood c
7974 data << uint32(0x568) << uint32(0x1); // 31 towerp c
7975 data << uint32(0x565) << uint32(0x0); // 32 stoneh tower a
7976 data << uint32(0x564) << uint32(0x0); // 33 icewing tower a
7977 data << uint32(0x563) << uint32(0x0); // 34 dunn a
7978 data << uint32(0x562) << uint32(0x0); // 35 duns a
7979 data << uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
7980 data << uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
7981 data << uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
7982 data << uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
7983 data << uint32(0x55d) << uint32(0x0); // 40 stone tower d
7984 data << uint32(0x3c6) << uint32(0x0); // 41 966 unk
7985 data << uint32(0x3c4) << uint32(0x0); // 42 964 unk
7986 data << uint32(0x3c2) << uint32(0x0); // 43 962 unk
7987 data << uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
7988 data << uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
7989 data << uint32(0x3b6) << uint32(0x0); // 46 950 unk
7990 data << uint32(0x55c) << uint32(0x0); // 47 icewing tower d
7991 data << uint32(0x55b) << uint32(0x0); // 48 dunn d
7992 data << uint32(0x55a) << uint32(0x0); // 49 duns d
7993 data << uint32(0x559) << uint32(0x0); // 50 1369 unk
7994 data << uint32(0x558) << uint32(0x0); // 51 iceblood d
7995 data << uint32(0x557) << uint32(0x0); // 52 towerp d
7996 data << uint32(0x556) << uint32(0x0); // 53 frostwolfe d
7997 data << uint32(0x555) << uint32(0x0); // 54 frostwolfw d
7998 data << uint32(0x554) << uint32(0x1); // 55 stoneh tower c
7999 data << uint32(0x553) << uint32(0x1); // 56 icewing tower c
8000 data << uint32(0x552) << uint32(0x1); // 57 dunn c
8001 data << uint32(0x551) << uint32(0x1); // 58 duns c
8002 data << uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
8003 data << uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
8004 data << uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
8005 data << uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
8006 data << uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
8007 data << uint32(0x545) << uint32(0x0); // 64 iceblood h_a
8008 data << uint32(0x543) << uint32(0x1); // 65 iceblod h_c
8009 data << uint32(0x542) << uint32(0x0); // 66 iceblood a_c
8010 data << uint32(0x540) << uint32(0x0); // 67 snowfall h_a
8011 data << uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
8012 data << uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
8013 data << uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
8014 data << uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
8015 data << uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
8016 data << uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
8017 data << uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
8018 data << uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
8019 data << uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
8020 data << uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
8021 data << uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
8022 data << uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
8023 data << uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
8024 data << uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
8026 break;
8027 case 3277: // WS
8028 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
8029 bg->FillInitialWorldStates(data);
8030 else
8032 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
8033 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
8034 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
8035 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
8036 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
8037 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
8038 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8039 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8041 break;
8042 case 3358: // AB
8043 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
8044 bg->FillInitialWorldStates(data);
8045 else
8047 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
8048 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
8049 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
8050 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
8051 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
8052 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
8053 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
8054 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
8055 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
8056 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
8057 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
8058 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
8059 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
8060 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
8061 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
8062 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
8063 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
8064 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
8065 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
8066 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
8067 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
8068 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
8069 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
8070 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
8071 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
8072 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
8073 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
8074 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
8075 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
8076 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
8077 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
8078 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
8080 break;
8081 case 3820: // EY
8082 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
8083 bg->FillInitialWorldStates(data);
8084 else
8086 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
8087 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
8088 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
8089 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
8090 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
8091 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
8092 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
8093 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
8094 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
8095 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
8096 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
8097 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
8098 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
8099 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
8100 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
8101 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
8102 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
8103 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
8104 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
8105 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
8106 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
8107 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
8108 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
8109 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
8110 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
8111 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
8112 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
8113 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
8114 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
8115 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
8116 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
8117 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
8118 // and some more ... unknown
8120 break;
8121 case 3483: // Hellfire Peninsula
8122 data << uint32(0x9ba) << uint32(0x1); // 10
8123 data << uint32(0x9b9) << uint32(0x1); // 11
8124 data << uint32(0x9b5) << uint32(0x0); // 12
8125 data << uint32(0x9b4) << uint32(0x1); // 13
8126 data << uint32(0x9b3) << uint32(0x0); // 14
8127 data << uint32(0x9b2) << uint32(0x0); // 15
8128 data << uint32(0x9b1) << uint32(0x1); // 16
8129 data << uint32(0x9b0) << uint32(0x0); // 17
8130 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
8131 data << uint32(0x9ac) << uint32(0x0); // 19
8132 data << uint32(0x9a8) << uint32(0x0); // 20
8133 data << uint32(0x9a7) << uint32(0x0); // 21
8134 data << uint32(0x9a6) << uint32(0x1); // 22
8135 break;
8136 case 3519: // Terokkar Forest
8137 data << uint32(0xa41) << uint32(0x0); // 10
8138 data << uint32(0xa40) << uint32(0x14); // 11
8139 data << uint32(0xa3f) << uint32(0x0); // 12
8140 data << uint32(0xa3e) << uint32(0x0); // 13
8141 data << uint32(0xa3d) << uint32(0x5); // 14
8142 data << uint32(0xa3c) << uint32(0x0); // 15
8143 data << uint32(0xa87) << uint32(0x0); // 16
8144 data << uint32(0xa86) << uint32(0x0); // 17
8145 data << uint32(0xa85) << uint32(0x0); // 18
8146 data << uint32(0xa84) << uint32(0x0); // 19
8147 data << uint32(0xa83) << uint32(0x0); // 20
8148 data << uint32(0xa82) << uint32(0x0); // 21
8149 data << uint32(0xa81) << uint32(0x0); // 22
8150 data << uint32(0xa80) << uint32(0x0); // 23
8151 data << uint32(0xa7e) << uint32(0x0); // 24
8152 data << uint32(0xa7d) << uint32(0x0); // 25
8153 data << uint32(0xa7c) << uint32(0x0); // 26
8154 data << uint32(0xa7b) << uint32(0x0); // 27
8155 data << uint32(0xa7a) << uint32(0x0); // 28
8156 data << uint32(0xa79) << uint32(0x0); // 29
8157 data << uint32(0x9d0) << uint32(0x5); // 30
8158 data << uint32(0x9ce) << uint32(0x0); // 31
8159 data << uint32(0x9cd) << uint32(0x0); // 32
8160 data << uint32(0x9cc) << uint32(0x0); // 33
8161 data << uint32(0xa88) << uint32(0x0); // 34
8162 data << uint32(0xad0) << uint32(0x0); // 35
8163 data << uint32(0xacf) << uint32(0x1); // 36
8164 break;
8165 case 3521: // Zangarmarsh
8166 data << uint32(0x9e1) << uint32(0x0); // 10
8167 data << uint32(0x9e0) << uint32(0x0); // 11
8168 data << uint32(0x9df) << uint32(0x0); // 12
8169 data << uint32(0xa5d) << uint32(0x1); // 13
8170 data << uint32(0xa5c) << uint32(0x0); // 14
8171 data << uint32(0xa5b) << uint32(0x1); // 15
8172 data << uint32(0xa5a) << uint32(0x0); // 16
8173 data << uint32(0xa59) << uint32(0x1); // 17
8174 data << uint32(0xa58) << uint32(0x0); // 18
8175 data << uint32(0xa57) << uint32(0x0); // 19
8176 data << uint32(0xa56) << uint32(0x0); // 20
8177 data << uint32(0xa55) << uint32(0x1); // 21
8178 data << uint32(0xa54) << uint32(0x0); // 22
8179 data << uint32(0x9e7) << uint32(0x0); // 23
8180 data << uint32(0x9e6) << uint32(0x0); // 24
8181 data << uint32(0x9e5) << uint32(0x0); // 25
8182 data << uint32(0xa00) << uint32(0x0); // 26
8183 data << uint32(0x9ff) << uint32(0x1); // 27
8184 data << uint32(0x9fe) << uint32(0x0); // 28
8185 data << uint32(0x9fd) << uint32(0x0); // 29
8186 data << uint32(0x9fc) << uint32(0x1); // 30
8187 data << uint32(0x9fb) << uint32(0x0); // 31
8188 data << uint32(0xa62) << uint32(0x0); // 32
8189 data << uint32(0xa61) << uint32(0x1); // 33
8190 data << uint32(0xa60) << uint32(0x1); // 34
8191 data << uint32(0xa5f) << uint32(0x0); // 35
8192 break;
8193 case 3698: // Nagrand Arena
8194 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
8195 bg->FillInitialWorldStates(data);
8196 else
8198 data << uint32(0xa0f) << uint32(0x0); // 7
8199 data << uint32(0xa10) << uint32(0x0); // 8
8200 data << uint32(0xa11) << uint32(0x0); // 9 show
8202 break;
8203 case 3702: // Blade's Edge Arena
8204 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8205 bg->FillInitialWorldStates(data);
8206 else
8208 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8209 data << uint32(0x9f1) << uint32(0x0); // 8 green
8210 data << uint32(0x9f3) << uint32(0x0); // 9 show
8212 break;
8213 case 3968: // Ruins of Lordaeron
8214 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8215 bg->FillInitialWorldStates(data);
8216 else
8218 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8219 data << uint32(0xbb9) << uint32(0x0); // 8 green
8220 data << uint32(0xbba) << uint32(0x0); // 9 show
8222 break;
8223 case 3703: // Shattrath City
8224 break;
8225 default:
8226 data << uint32(0x914) << uint32(0x0); // 7
8227 data << uint32(0x913) << uint32(0x0); // 8
8228 data << uint32(0x912) << uint32(0x0); // 9
8229 data << uint32(0x915) << uint32(0x0); // 10
8230 break;
8232 GetSession()->SendPacket(&data);
8235 uint32 Player::GetXPRestBonus(uint32 xp)
8237 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8239 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8240 rested_bonus = xp;
8242 SetRestBonus( GetRestBonus() - rested_bonus);
8244 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8245 return rested_bonus;
8248 void Player::SetBindPoint(uint64 guid)
8250 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8251 data << uint64(guid);
8252 GetSession()->SendPacket( &data );
8255 void Player::SendTalentWipeConfirm(uint64 guid)
8257 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8258 data << uint64(guid);
8259 data << uint32(resetTalentsCost());
8260 GetSession()->SendPacket( &data );
8263 void Player::SendPetSkillWipeConfirm()
8265 Pet* pet = GetPet();
8266 if(!pet)
8267 return;
8268 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8269 data << pet->GetGUID();
8270 data << uint32(pet->resetTalentsCost());
8271 GetSession()->SendPacket( &data );
8274 /*********************************************************/
8275 /*** STORAGE SYSTEM ***/
8276 /*********************************************************/
8278 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8280 assert(i < 3);
8281 if(i < 2 && item)
8283 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8284 return;
8285 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8286 if(charges == 0)
8287 return;
8288 if(charges > 1)
8289 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8290 else if(charges <= 1)
8292 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8293 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8298 void Player::SetSheath( SheathState sheathed )
8300 switch (sheathed)
8302 case SHEATH_STATE_UNARMED: // no prepared weapon
8303 SetVirtualItemSlot(0,NULL);
8304 SetVirtualItemSlot(1,NULL);
8305 SetVirtualItemSlot(2,NULL);
8306 break;
8307 case SHEATH_STATE_MELEE: // prepared melee weapon
8309 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true,true));
8310 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true,true));
8311 SetVirtualItemSlot(2,NULL);
8312 }; break;
8313 case SHEATH_STATE_RANGED: // prepared ranged weapon
8314 SetVirtualItemSlot(0,NULL);
8315 SetVirtualItemSlot(1,NULL);
8316 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true,true));
8317 break;
8318 default:
8319 SetVirtualItemSlot(0,NULL);
8320 SetVirtualItemSlot(1,NULL);
8321 SetVirtualItemSlot(2,NULL);
8322 break;
8324 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
8327 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8329 uint8 pClass = getClass();
8331 uint8 slots[4];
8332 slots[0] = NULL_SLOT;
8333 slots[1] = NULL_SLOT;
8334 slots[2] = NULL_SLOT;
8335 slots[3] = NULL_SLOT;
8336 switch( proto->InventoryType )
8338 case INVTYPE_HEAD:
8339 slots[0] = EQUIPMENT_SLOT_HEAD;
8340 break;
8341 case INVTYPE_NECK:
8342 slots[0] = EQUIPMENT_SLOT_NECK;
8343 break;
8344 case INVTYPE_SHOULDERS:
8345 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8346 break;
8347 case INVTYPE_BODY:
8348 slots[0] = EQUIPMENT_SLOT_BODY;
8349 break;
8350 case INVTYPE_CHEST:
8351 slots[0] = EQUIPMENT_SLOT_CHEST;
8352 break;
8353 case INVTYPE_ROBE:
8354 slots[0] = EQUIPMENT_SLOT_CHEST;
8355 break;
8356 case INVTYPE_WAIST:
8357 slots[0] = EQUIPMENT_SLOT_WAIST;
8358 break;
8359 case INVTYPE_LEGS:
8360 slots[0] = EQUIPMENT_SLOT_LEGS;
8361 break;
8362 case INVTYPE_FEET:
8363 slots[0] = EQUIPMENT_SLOT_FEET;
8364 break;
8365 case INVTYPE_WRISTS:
8366 slots[0] = EQUIPMENT_SLOT_WRISTS;
8367 break;
8368 case INVTYPE_HANDS:
8369 slots[0] = EQUIPMENT_SLOT_HANDS;
8370 break;
8371 case INVTYPE_FINGER:
8372 slots[0] = EQUIPMENT_SLOT_FINGER1;
8373 slots[1] = EQUIPMENT_SLOT_FINGER2;
8374 break;
8375 case INVTYPE_TRINKET:
8376 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8377 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8378 break;
8379 case INVTYPE_CLOAK:
8380 slots[0] = EQUIPMENT_SLOT_BACK;
8381 break;
8382 case INVTYPE_WEAPON:
8384 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8386 // suggest offhand slot only if know dual wielding
8387 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8388 if(CanDualWield())
8389 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8390 break;
8392 case INVTYPE_SHIELD:
8393 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8394 break;
8395 case INVTYPE_RANGED:
8396 slots[0] = EQUIPMENT_SLOT_RANGED;
8397 break;
8398 case INVTYPE_2HWEAPON:
8399 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8400 if (CanDualWield() && CanTitanGrip())
8401 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8402 break;
8403 case INVTYPE_TABARD:
8404 slots[0] = EQUIPMENT_SLOT_TABARD;
8405 break;
8406 case INVTYPE_WEAPONMAINHAND:
8407 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8408 break;
8409 case INVTYPE_WEAPONOFFHAND:
8410 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8411 break;
8412 case INVTYPE_HOLDABLE:
8413 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8414 break;
8415 case INVTYPE_THROWN:
8416 slots[0] = EQUIPMENT_SLOT_RANGED;
8417 break;
8418 case INVTYPE_RANGEDRIGHT:
8419 slots[0] = EQUIPMENT_SLOT_RANGED;
8420 break;
8421 case INVTYPE_BAG:
8422 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8423 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8424 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8425 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8426 break;
8427 case INVTYPE_RELIC:
8429 switch(proto->SubClass)
8431 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8432 if (pClass == CLASS_PALADIN)
8433 slots[0] = EQUIPMENT_SLOT_RANGED;
8434 break;
8435 case ITEM_SUBCLASS_ARMOR_IDOL:
8436 if (pClass == CLASS_DRUID)
8437 slots[0] = EQUIPMENT_SLOT_RANGED;
8438 break;
8439 case ITEM_SUBCLASS_ARMOR_TOTEM:
8440 if (pClass == CLASS_SHAMAN)
8441 slots[0] = EQUIPMENT_SLOT_RANGED;
8442 break;
8443 case ITEM_SUBCLASS_ARMOR_MISC:
8444 if (pClass == CLASS_WARLOCK)
8445 slots[0] = EQUIPMENT_SLOT_RANGED;
8446 break;
8447 case ITEM_SUBCLASS_ARMOR_SIGIL:
8448 if (pClass == CLASS_DEATH_KNIGHT)
8449 slots[0] = EQUIPMENT_SLOT_RANGED;
8450 break;
8452 break;
8454 default :
8455 return NULL_SLOT;
8458 if( slot != NULL_SLOT )
8460 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8462 for (int i = 0; i < 4; ++i)
8464 if ( slots[i] == slot )
8465 return slot;
8469 else
8471 // search free slot at first
8472 for (int i = 0; i < 4; ++i)
8474 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8476 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8477 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8478 return slots[i];
8482 // if not found free and can swap return first appropriate from used
8483 for (int i = 0; i < 4; ++i)
8485 if ( slots[i] != NULL_SLOT && swap )
8486 return slots[i];
8490 // no free position
8491 return NULL_SLOT;
8494 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8496 Item *pItem;
8497 uint32 tempcount = 0;
8499 uint8 res = EQUIP_ERR_OK;
8501 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8503 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8504 if( pItem && pItem->GetEntry() == item )
8506 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8507 if(ires==EQUIP_ERR_OK)
8509 tempcount += pItem->GetCount();
8510 if( tempcount >= count )
8511 return EQUIP_ERR_OK;
8513 else
8514 res = ires;
8517 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8519 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8520 if( pItem && pItem->GetEntry() == item )
8522 tempcount += pItem->GetCount();
8523 if( tempcount >= count )
8524 return EQUIP_ERR_OK;
8527 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8529 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8530 if( pItem && pItem->GetEntry() == item )
8532 tempcount += pItem->GetCount();
8533 if( tempcount >= count )
8534 return EQUIP_ERR_OK;
8537 Bag *pBag;
8538 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8540 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8541 if( pBag )
8543 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8545 pItem = GetItemByPos( i, j );
8546 if( pItem && pItem->GetEntry() == item )
8548 tempcount += pItem->GetCount();
8549 if( tempcount >= count )
8550 return EQUIP_ERR_OK;
8556 // not found req. item count and have unequippable items
8557 return res;
8560 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8562 uint32 count = 0;
8563 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8565 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8566 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8567 count += pItem->GetCount();
8569 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8571 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8572 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8573 count += pItem->GetCount();
8575 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8577 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8578 if( pBag )
8579 count += pBag->GetItemCount(item,skipItem);
8582 if(skipItem && skipItem->GetProto()->GemProperties)
8584 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8586 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8587 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8588 count += pItem->GetGemCountWithID(item);
8592 if(inBankAlso)
8594 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8596 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8597 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8598 count += pItem->GetCount();
8600 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8602 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8603 if( pBag )
8604 count += pBag->GetItemCount(item,skipItem);
8607 if(skipItem && skipItem->GetProto()->GemProperties)
8609 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8611 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8612 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8613 count += pItem->GetGemCountWithID(item);
8618 return count;
8621 uint32 Player::GetItemCountWithLimitCategory( uint32 limitCategory ) const
8623 uint32 count = 0;
8624 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8625 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8626 if (pItem->GetProto()->ItemLimitCategory == limitCategory)
8627 count += pItem->GetCount();
8629 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8630 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8631 if (pItem->GetProto()->ItemLimitCategory == limitCategory)
8632 count += pItem->GetCount();
8634 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8635 if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8636 count += pBag->GetItemCountWithLimitCategory(limitCategory);
8638 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8639 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8640 if (pItem->GetProto()->ItemLimitCategory == limitCategory)
8641 count += pItem->GetCount();
8643 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8644 if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8645 count += pBag->GetItemCountWithLimitCategory(limitCategory);
8647 return count;
8650 Item* Player::GetItemByEntry( uint32 item ) const
8652 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8653 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8654 if (pItem->GetEntry() == item)
8655 return pItem;
8657 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8658 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8659 if (pItem->GetEntry() == item)
8660 return pItem;
8662 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8663 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
8664 if (Item* itemPtr = pBag->GetItemByEntry(item))
8665 return itemPtr;
8667 return NULL;
8670 Item* Player::GetItemByLimitedCategory(uint32 limitedCategory) const
8672 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8673 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8674 if (pItem->GetProto()->ItemLimitCategory == limitedCategory)
8675 return pItem;
8677 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8678 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8679 if (pItem->GetProto()->ItemLimitCategory == limitedCategory)
8680 return pItem;
8682 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8683 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
8684 if (Item* itemPtr = pBag->GetItemByLimitedCategory(limitedCategory))
8685 return itemPtr;
8687 return NULL;
8690 Item* Player::GetItemByGuid(ObjectGuid guid) const
8692 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8693 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8694 if (pItem->GetObjectGuid() == guid)
8695 return pItem;
8697 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8698 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8699 if (pItem->GetObjectGuid() == guid)
8700 return pItem;
8702 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8703 if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8704 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8705 if (Item* pItem = pBag->GetItemByPos(j))
8706 if (pItem->GetObjectGuid() == guid)
8707 return pItem;
8709 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8710 if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8711 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8712 if (Item* pItem = pBag->GetItemByPos(j))
8713 if (pItem->GetObjectGuid() == guid)
8714 return pItem;
8716 return NULL;
8719 Item* Player::GetItemByPos( uint16 pos ) const
8721 uint8 bag = pos >> 8;
8722 uint8 slot = pos & 255;
8723 return GetItemByPos( bag, slot );
8726 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8728 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END )) )
8729 return m_items[slot];
8730 else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8731 || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END) )
8733 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8734 if ( pBag )
8735 return pBag->GetItemByPos(slot);
8737 return NULL;
8740 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool nonbroken, bool useable) const
8742 uint8 slot;
8743 switch (attackType)
8745 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8746 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8747 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8748 default: return NULL;
8751 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8752 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8753 return NULL;
8755 if (useable && !IsUseEquipedWeapon(attackType==BASE_ATTACK))
8756 return NULL;
8758 if (nonbroken && item->IsBroken())
8759 return NULL;
8761 return item;
8764 Item* Player::GetShield(bool useable) const
8766 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8767 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8768 return NULL;
8770 if(!useable)
8771 return item;
8773 if( item->IsBroken())
8774 return NULL;
8776 return item;
8779 uint32 Player::GetAttackBySlot( uint8 slot )
8781 switch(slot)
8783 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8784 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8785 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8786 default: return MAX_ATTACK;
8790 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8792 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8793 return true;
8794 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8795 return true;
8796 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8797 return true;
8798 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8799 return true;
8800 return false;
8803 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8805 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8806 return true;
8807 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8808 return true;
8809 return false;
8812 bool Player::IsBankPos( uint8 bag, uint8 slot )
8814 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8815 return true;
8816 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8817 return true;
8818 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8819 return true;
8820 return false;
8823 bool Player::IsBagPos( uint16 pos )
8825 uint8 bag = pos >> 8;
8826 uint8 slot = pos & 255;
8827 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8828 return true;
8829 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8830 return true;
8831 return false;
8834 bool Player::IsValidPos( uint8 bag, uint8 slot, bool explicit_pos ) const
8836 // post selected
8837 if(bag == NULL_BAG && !explicit_pos)
8838 return true;
8840 if (bag == INVENTORY_SLOT_BAG_0)
8842 // any post selected
8843 if (slot == NULL_SLOT && !explicit_pos)
8844 return true;
8846 // equipment
8847 if (slot < EQUIPMENT_SLOT_END)
8848 return true;
8850 // bag equip slots
8851 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8852 return true;
8854 // backpack slots
8855 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8856 return true;
8858 // keyring slots
8859 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8860 return true;
8862 // bank main slots
8863 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8864 return true;
8866 // bank bag slots
8867 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8868 return true;
8870 return false;
8873 // bag content slots
8874 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8876 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8877 if(!pBag)
8878 return false;
8880 // any post selected
8881 if (slot == NULL_SLOT && !explicit_pos)
8882 return true;
8884 return slot < pBag->GetBagSize();
8887 // bank bag content slots
8888 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8890 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8891 if(!pBag)
8892 return false;
8894 // any post selected
8895 if (slot == NULL_SLOT && !explicit_pos)
8896 return true;
8898 return slot < pBag->GetBagSize();
8901 // where this?
8902 return false;
8906 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8908 uint32 tempcount = 0;
8909 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8911 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8912 if( pItem && pItem->GetEntry() == item )
8914 tempcount += pItem->GetCount();
8915 if( tempcount >= count )
8916 return true;
8919 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8921 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8922 if( pItem && pItem->GetEntry() == item )
8924 tempcount += pItem->GetCount();
8925 if( tempcount >= count )
8926 return true;
8929 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8931 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8933 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8935 Item* pItem = GetItemByPos( i, j );
8936 if( pItem && pItem->GetEntry() == item )
8938 tempcount += pItem->GetCount();
8939 if( tempcount >= count )
8940 return true;
8946 if(inBankAlso)
8948 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8950 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8951 if( pItem && pItem->GetEntry() == item )
8953 tempcount += pItem->GetCount();
8954 if( tempcount >= count )
8955 return true;
8958 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8960 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8962 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8964 Item* pItem = GetItemByPos( i, j );
8965 if( pItem && pItem->GetEntry() == item )
8967 tempcount += pItem->GetCount();
8968 if( tempcount >= count )
8969 return true;
8976 return false;
8979 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8981 uint32 tempcount = 0;
8982 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8984 if(i==int(except_slot))
8985 continue;
8987 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8988 if( pItem && pItem->GetEntry() == item)
8990 tempcount += pItem->GetCount();
8991 if( tempcount >= count )
8992 return true;
8996 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item);
8997 if (pProto && pProto->GemProperties)
8999 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
9001 if(i==int(except_slot))
9002 continue;
9004 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9005 if( pItem && pItem->GetProto()->Socket[0].Color)
9007 tempcount += pItem->GetGemCountWithID(item);
9008 if( tempcount >= count )
9009 return true;
9014 return false;
9017 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
9019 uint32 tempcount = 0;
9020 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
9022 if(i==int(except_slot))
9023 continue;
9025 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9026 if (!pItem)
9027 continue;
9029 ItemPrototype const *pProto = pItem->GetProto();
9030 if (!pProto)
9031 continue;
9033 if (pProto->ItemLimitCategory == limitCategory)
9035 tempcount += pItem->GetCount();
9036 if( tempcount >= count )
9037 return true;
9040 if( pProto->Socket[0].Color)
9042 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
9043 if( tempcount >= count )
9044 return true;
9048 return false;
9051 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
9053 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
9054 if( !pProto )
9056 if(no_space_count)
9057 *no_space_count = count;
9058 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9061 // no maximum
9062 if(pProto->MaxCount > 0)
9064 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
9066 if (curcount + count > uint32(pProto->MaxCount))
9068 if(no_space_count)
9069 *no_space_count = count +curcount - pProto->MaxCount;
9070 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9074 // check unique-equipped limit
9075 if (pProto->ItemLimitCategory)
9077 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(pProto->ItemLimitCategory);
9078 if (!limitEntry)
9080 if(no_space_count)
9081 *no_space_count = count;
9082 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9085 if (limitEntry->mode == ITEM_LIMIT_CATEGORY_MODE_HAVE)
9087 uint32 curcount = GetItemCountWithLimitCategory(pProto->ItemLimitCategory);
9089 if (curcount + count > uint32(limitEntry->maxCount))
9091 if(no_space_count)
9092 *no_space_count = count + curcount - limitEntry->maxCount;
9093 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS;
9098 return EQUIP_ERR_OK;
9101 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
9103 Item *pItem;
9104 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9106 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9107 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
9108 return true;
9110 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9112 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9113 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
9114 return true;
9116 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9118 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9120 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9122 pItem = GetItemByPos( i, j );
9123 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
9124 return true;
9128 return false;
9131 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
9133 Item* pItem2 = GetItemByPos( bag, slot );
9135 // ignore move item (this slot will be empty at move)
9136 if (pItem2==pSrcItem)
9137 pItem2 = NULL;
9139 uint32 need_space;
9141 // empty specific slot - check item fit to slot
9142 if (!pItem2 || swap)
9144 if (bag == INVENTORY_SLOT_BAG_0)
9146 // keyring case
9147 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
9148 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9150 // currencytoken case
9151 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
9152 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9154 // prevent cheating
9155 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
9156 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9158 else
9160 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9161 if (!pBag)
9162 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9164 ItemPrototype const* pBagProto = pBag->GetProto();
9165 if (!pBagProto)
9166 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9168 if (slot >= pBagProto->ContainerSlots)
9169 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9171 if (!ItemCanGoIntoBag(pProto,pBagProto))
9172 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9175 // non empty stack with space
9176 need_space = pProto->GetMaxStackSize();
9178 // non empty slot, check item type
9179 else
9181 // can be merged at least partly
9182 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9183 if (res != EQUIP_ERR_OK)
9184 return res;
9186 // free stack space or infinity
9187 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9190 if (need_space > count)
9191 need_space = count;
9193 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
9194 if (!newPosition.isContainedIn(dest))
9196 dest.push_back(newPosition);
9197 count -= need_space;
9199 return EQUIP_ERR_OK;
9202 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
9204 // skip specific bag already processed in first called _CanStoreItem_InBag
9205 if (bag==skip_bag)
9206 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9208 // skip not existed bag or self targeted bag
9209 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9210 if (!pBag || pBag==pSrcItem)
9211 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9213 ItemPrototype const* pBagProto = pBag->GetProto();
9214 if (!pBagProto)
9215 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9217 // specialized bag mode or non-specilized
9218 if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
9219 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9221 if (!ItemCanGoIntoBag(pProto,pBagProto))
9222 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9224 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9226 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9227 if (j==skip_slot)
9228 continue;
9230 Item* pItem2 = GetItemByPos( bag, j );
9232 // ignore move item (this slot will be empty at move)
9233 if (pItem2 == pSrcItem)
9234 pItem2 = NULL;
9236 // if merge skip empty, if !merge skip non-empty
9237 if ((pItem2 != NULL) != merge)
9238 continue;
9240 uint32 need_space = pProto->GetMaxStackSize();
9242 if (pItem2)
9244 // can be merged at least partly
9245 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9246 if (res != EQUIP_ERR_OK)
9247 continue;
9249 // descrease at current stacksize
9250 need_space -= pItem2->GetCount();
9253 if (need_space > count)
9254 need_space = count;
9256 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9257 if (!newPosition.isContainedIn(dest))
9259 dest.push_back(newPosition);
9260 count -= need_space;
9262 if (count==0)
9263 return EQUIP_ERR_OK;
9266 return EQUIP_ERR_OK;
9269 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
9271 for(uint32 j = slot_begin; j < slot_end; ++j)
9273 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9274 if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
9275 continue;
9277 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
9279 // ignore move item (this slot will be empty at move)
9280 if (pItem2==pSrcItem)
9281 pItem2 = NULL;
9283 // if merge skip empty, if !merge skip non-empty
9284 if ((pItem2 != NULL) != merge)
9285 continue;
9287 uint32 need_space = pProto->GetMaxStackSize();
9289 if (pItem2)
9291 // can be merged at least partly
9292 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9293 if (res != EQUIP_ERR_OK)
9294 continue;
9296 // descrease at current stacksize
9297 need_space -= pItem2->GetCount();
9300 if (need_space > count)
9301 need_space = count;
9303 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9304 if (!newPosition.isContainedIn(dest))
9306 dest.push_back(newPosition);
9307 count -= need_space;
9309 if (count==0)
9310 return EQUIP_ERR_OK;
9313 return EQUIP_ERR_OK;
9316 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9318 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9320 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
9321 if (!pProto)
9323 if (no_space_count)
9324 *no_space_count = count;
9325 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9328 if (pItem)
9330 // item used
9331 if(pItem->m_lootGenerated)
9333 if (no_space_count)
9334 *no_space_count = count;
9335 return EQUIP_ERR_ALREADY_LOOTED;
9338 if (pItem->IsBindedNotWith(this))
9340 if (no_space_count)
9341 *no_space_count = count;
9342 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9346 // check count of items (skip for auto move for same player from bank)
9347 uint32 no_similar_count = 0; // can't store this amount similar items
9348 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9349 if (res!=EQUIP_ERR_OK)
9351 if (count==no_similar_count)
9353 if (no_space_count)
9354 *no_space_count = no_similar_count;
9355 return res;
9357 count -= no_similar_count;
9360 // in specific slot
9361 if (bag != NULL_BAG && slot != NULL_SLOT)
9363 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9364 if (res!=EQUIP_ERR_OK)
9366 if (no_space_count)
9367 *no_space_count = count + no_similar_count;
9368 return res;
9371 if (count==0)
9373 if (no_similar_count==0)
9374 return EQUIP_ERR_OK;
9376 if (no_space_count)
9377 *no_space_count = count + no_similar_count;
9378 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9382 // not specific slot or have space for partly store only in specific slot
9384 // in specific bag
9385 if (bag != NULL_BAG)
9387 // search stack in bag for merge to
9388 if (pProto->Stackable != 1)
9390 if (bag == INVENTORY_SLOT_BAG_0) // inventory
9392 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9393 if (res!=EQUIP_ERR_OK)
9395 if (no_space_count)
9396 *no_space_count = count + no_similar_count;
9397 return res;
9400 if (count==0)
9402 if (no_similar_count==0)
9403 return EQUIP_ERR_OK;
9405 if (no_space_count)
9406 *no_space_count = count + no_similar_count;
9407 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9410 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9411 if (res!=EQUIP_ERR_OK)
9413 if (no_space_count)
9414 *no_space_count = count + no_similar_count;
9415 return res;
9418 if (count==0)
9420 if (no_similar_count==0)
9421 return EQUIP_ERR_OK;
9423 if (no_space_count)
9424 *no_space_count = count + no_similar_count;
9425 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9428 else // equipped bag
9430 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9431 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9432 if (res!=EQUIP_ERR_OK)
9433 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9435 if (res!=EQUIP_ERR_OK)
9437 if (no_space_count)
9438 *no_space_count = count + no_similar_count;
9439 return res;
9442 if (count==0)
9444 if (no_similar_count==0)
9445 return EQUIP_ERR_OK;
9447 if (no_space_count)
9448 *no_space_count = count + no_similar_count;
9449 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9454 // search free slot in bag for place to
9455 if(bag == INVENTORY_SLOT_BAG_0) // inventory
9457 // search free slot - keyring case
9458 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9460 uint32 keyringSize = GetMaxKeyringSize();
9461 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9462 if (res!=EQUIP_ERR_OK)
9464 if (no_space_count)
9465 *no_space_count = count + no_similar_count;
9466 return res;
9469 if (count==0)
9471 if (no_similar_count==0)
9472 return EQUIP_ERR_OK;
9474 if (no_space_count)
9475 *no_space_count = count + no_similar_count;
9476 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9479 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9480 if (res!=EQUIP_ERR_OK)
9482 if (no_space_count)
9483 *no_space_count = count + no_similar_count;
9484 return res;
9487 if (count==0)
9489 if (no_similar_count==0)
9490 return EQUIP_ERR_OK;
9492 if (no_space_count)
9493 *no_space_count = count + no_similar_count;
9494 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9497 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9499 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9500 if (res!=EQUIP_ERR_OK)
9502 if (no_space_count)
9503 *no_space_count = count + no_similar_count;
9504 return res;
9507 if (count==0)
9509 if (no_similar_count==0)
9510 return EQUIP_ERR_OK;
9512 if (no_space_count)
9513 *no_space_count = count + no_similar_count;
9514 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9518 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9519 if (res!=EQUIP_ERR_OK)
9521 if (no_space_count)
9522 *no_space_count = count + no_similar_count;
9523 return res;
9526 if (count==0)
9528 if (no_similar_count==0)
9529 return EQUIP_ERR_OK;
9531 if (no_space_count)
9532 *no_space_count = count + no_similar_count;
9533 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9536 else // equipped bag
9538 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9539 if (res!=EQUIP_ERR_OK)
9540 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9542 if (res!=EQUIP_ERR_OK)
9544 if (no_space_count)
9545 *no_space_count = count + no_similar_count;
9546 return res;
9549 if (count==0)
9551 if (no_similar_count==0)
9552 return EQUIP_ERR_OK;
9554 if (no_space_count)
9555 *no_space_count = count + no_similar_count;
9556 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9561 // not specific bag or have space for partly store only in specific bag
9563 // search stack for merge to
9564 if (pProto->Stackable != 1)
9566 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9567 if (res!=EQUIP_ERR_OK)
9569 if (no_space_count)
9570 *no_space_count = count + no_similar_count;
9571 return res;
9574 if (count==0)
9576 if (no_similar_count==0)
9577 return EQUIP_ERR_OK;
9579 if (no_space_count)
9580 *no_space_count = count + no_similar_count;
9581 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9584 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9585 if (res!=EQUIP_ERR_OK)
9587 if (no_space_count)
9588 *no_space_count = count + no_similar_count;
9589 return res;
9592 if (count==0)
9594 if (no_similar_count==0)
9595 return EQUIP_ERR_OK;
9597 if (no_space_count)
9598 *no_space_count = count + no_similar_count;
9599 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9602 if (pProto->BagFamily)
9604 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9606 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9607 if (res!=EQUIP_ERR_OK)
9608 continue;
9610 if (count==0)
9612 if (no_similar_count==0)
9613 return EQUIP_ERR_OK;
9615 if (no_space_count)
9616 *no_space_count = count + no_similar_count;
9617 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9622 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9624 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9625 if (res!=EQUIP_ERR_OK)
9626 continue;
9628 if (count==0)
9630 if (no_similar_count==0)
9631 return EQUIP_ERR_OK;
9633 if (no_space_count)
9634 *no_space_count = count + no_similar_count;
9635 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9640 // search free slot - special bag case
9641 if (pProto->BagFamily)
9643 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9645 uint32 keyringSize = GetMaxKeyringSize();
9646 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9647 if (res!=EQUIP_ERR_OK)
9649 if (no_space_count)
9650 *no_space_count = count + no_similar_count;
9651 return res;
9654 if (count==0)
9656 if (no_similar_count==0)
9657 return EQUIP_ERR_OK;
9659 if (no_space_count)
9660 *no_space_count = count + no_similar_count;
9661 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9664 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9666 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9667 if (res!=EQUIP_ERR_OK)
9669 if (no_space_count)
9670 *no_space_count = count + no_similar_count;
9671 return res;
9674 if (count==0)
9676 if (no_similar_count==0)
9677 return EQUIP_ERR_OK;
9679 if (no_space_count)
9680 *no_space_count = count + no_similar_count;
9681 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9685 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9687 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9688 if (res!=EQUIP_ERR_OK)
9689 continue;
9691 if (count==0)
9693 if (no_similar_count==0)
9694 return EQUIP_ERR_OK;
9696 if (no_space_count)
9697 *no_space_count = count + no_similar_count;
9698 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9703 // search free slot
9704 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9705 if (res!=EQUIP_ERR_OK)
9707 if (no_space_count)
9708 *no_space_count = count + no_similar_count;
9709 return res;
9712 if (count==0)
9714 if (no_similar_count==0)
9715 return EQUIP_ERR_OK;
9717 if (no_space_count)
9718 *no_space_count = count + no_similar_count;
9719 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9722 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9724 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9725 if (res!=EQUIP_ERR_OK)
9726 continue;
9728 if (count==0)
9730 if (no_similar_count==0)
9731 return EQUIP_ERR_OK;
9733 if (no_space_count)
9734 *no_space_count = count + no_similar_count;
9735 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9739 if (no_space_count)
9740 *no_space_count = count + no_similar_count;
9742 return EQUIP_ERR_INVENTORY_FULL;
9745 //////////////////////////////////////////////////////////////////////////
9746 uint8 Player::CanStoreItems( Item **pItems,int count) const
9748 Item *pItem2;
9750 // fill space table
9751 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9752 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9753 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9754 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9756 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9757 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9758 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9759 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9761 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9763 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9765 if (pItem2 && !pItem2->IsInTrade())
9767 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9771 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9773 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9775 if (pItem2 && !pItem2->IsInTrade())
9777 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9781 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9783 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9785 if (pItem2 && !pItem2->IsInTrade())
9787 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9791 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9793 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9795 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9797 pItem2 = GetItemByPos( i, j );
9798 if (pItem2 && !pItem2->IsInTrade())
9800 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9806 // check free space for all items
9807 for (int k = 0; k < count; ++k)
9809 Item *pItem = pItems[k];
9811 // no item
9812 if (!pItem) continue;
9814 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9815 ItemPrototype const *pProto = pItem->GetProto();
9817 // strange item
9818 if( !pProto )
9819 return EQUIP_ERR_ITEM_NOT_FOUND;
9821 // item used
9822 if(pItem->m_lootGenerated)
9823 return EQUIP_ERR_ALREADY_LOOTED;
9825 // item it 'bind'
9826 if(pItem->IsBindedNotWith(this))
9827 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9829 Bag *pBag;
9830 ItemPrototype const *pBagProto;
9832 // item is 'one item only'
9833 uint8 res = CanTakeMoreSimilarItems(pItem);
9834 if(res != EQUIP_ERR_OK)
9835 return res;
9837 // search stack for merge to
9838 if( pProto->Stackable != 1 )
9840 bool b_found = false;
9842 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9844 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9845 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9847 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9848 b_found = true;
9849 break;
9852 if (b_found) continue;
9854 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9856 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9857 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9859 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9860 b_found = true;
9861 break;
9864 if (b_found) continue;
9866 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9868 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9869 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9871 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9872 b_found = true;
9873 break;
9876 if (b_found) continue;
9878 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9880 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9881 if( pBag )
9883 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9885 pItem2 = GetItemByPos( t, j );
9886 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9888 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9889 b_found = true;
9890 break;
9895 if (b_found) continue;
9898 // special bag case
9899 if( pProto->BagFamily )
9901 bool b_found = false;
9902 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9904 uint32 keyringSize = GetMaxKeyringSize();
9905 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9907 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9909 inv_keys[t-KEYRING_SLOT_START] = 1;
9910 b_found = true;
9911 break;
9916 if (b_found) continue;
9918 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9920 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9922 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9924 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9925 b_found = true;
9926 break;
9931 if (b_found) continue;
9933 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9935 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9936 if( pBag )
9938 pBagProto = pBag->GetProto();
9940 // not plain container check
9941 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9942 ItemCanGoIntoBag(pProto,pBagProto) )
9944 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9946 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9948 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9949 b_found = true;
9950 break;
9956 if (b_found) continue;
9959 // search free slot
9960 bool b_found = false;
9961 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9963 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9965 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9966 b_found = true;
9967 break;
9970 if (b_found) continue;
9972 // search free slot in bags
9973 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9975 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9976 if( pBag )
9978 pBagProto = pBag->GetProto();
9980 // special bag already checked
9981 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9982 continue;
9984 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9986 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9988 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9989 b_found = true;
9990 break;
9996 // no free slot found?
9997 if (!b_found)
9998 return EQUIP_ERR_INVENTORY_FULL;
10001 return EQUIP_ERR_OK;
10004 //////////////////////////////////////////////////////////////////////////
10005 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
10007 dest = 0;
10008 Item *pItem = Item::CreateItem( item, 1, this );
10009 if( pItem )
10011 uint8 result = CanEquipItem(slot, dest, pItem, swap );
10012 delete pItem;
10013 return result;
10016 return EQUIP_ERR_ITEM_NOT_FOUND;
10019 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
10021 dest = 0;
10022 if( pItem )
10024 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
10025 ItemPrototype const *pProto = pItem->GetProto();
10026 if( pProto )
10028 // item used
10029 if(pItem->m_lootGenerated)
10030 return EQUIP_ERR_ALREADY_LOOTED;
10032 if(pItem->IsBindedNotWith(this))
10033 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10035 // check count of items (skip for auto move for same player from bank)
10036 uint8 res = CanTakeMoreSimilarItems(pItem);
10037 if(res != EQUIP_ERR_OK)
10038 return res;
10040 // check this only in game
10041 if(not_loading)
10043 // May be here should be more stronger checks; STUNNED checked
10044 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
10045 if (hasUnitState(UNIT_STAT_STUNNED))
10046 return EQUIP_ERR_YOU_ARE_STUNNED;
10048 // do not allow equipping gear except weapons, offhands, projectiles, relics in
10049 // - combat
10050 // - in-progress arenas
10051 if( !pProto->CanChangeEquipStateInCombat() )
10053 if( isInCombat() )
10054 return EQUIP_ERR_NOT_IN_COMBAT;
10056 if(BattleGround* bg = GetBattleGround())
10057 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
10058 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
10061 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
10062 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
10064 if(IsNonMeleeSpellCasted(false))
10065 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
10068 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
10069 // 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)
10070 if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
10071 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10073 uint8 eslot = FindEquipSlot( pProto, slot, swap );
10074 if (eslot == NULL_SLOT)
10075 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10077 uint8 msg = CanUseItem(pItem , not_loading);
10078 if (msg != EQUIP_ERR_OK)
10079 return msg;
10080 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
10081 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
10083 // if swap ignore item (equipped also)
10084 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
10085 return res2;
10087 // check unique-equipped special item classes
10088 if (pProto->Class == ITEM_CLASS_QUIVER)
10090 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10092 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
10094 if (pBag != pItem)
10096 if (ItemPrototype const* pBagProto = pBag->GetProto())
10098 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
10099 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
10100 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
10101 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
10108 uint32 type = pProto->InventoryType;
10110 if (eslot == EQUIPMENT_SLOT_OFFHAND)
10112 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
10114 if (!CanDualWield())
10115 return EQUIP_ERR_CANT_DUAL_WIELD;
10117 else if (type == INVTYPE_2HWEAPON)
10119 if (!CanDualWield() || !CanTitanGrip())
10120 return EQUIP_ERR_CANT_DUAL_WIELD;
10123 if (IsTwoHandUsed())
10124 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
10127 // equip two-hand weapon case (with possible unequip 2 items)
10128 if (type == INVTYPE_2HWEAPON)
10130 if (eslot == EQUIPMENT_SLOT_OFFHAND)
10132 if (!CanTitanGrip())
10133 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10135 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
10136 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10138 if (!CanTitanGrip())
10140 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
10141 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
10142 ItemPosCountVec off_dest;
10143 if (offItem && (!not_loading ||
10144 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
10145 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
10146 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
10149 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
10150 return EQUIP_ERR_OK;
10154 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
10157 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
10159 // Applied only to equipped items and bank bags
10160 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
10161 return EQUIP_ERR_OK;
10163 Item* pItem = GetItemByPos(pos);
10165 // Applied only to existed equipped item
10166 if( !pItem )
10167 return EQUIP_ERR_OK;
10169 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
10171 ItemPrototype const *pProto = pItem->GetProto();
10172 if( !pProto )
10173 return EQUIP_ERR_ITEM_NOT_FOUND;
10175 // item used
10176 if(pItem->m_lootGenerated)
10177 return EQUIP_ERR_ALREADY_LOOTED;
10179 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10180 // - combat
10181 // - in-progress arenas
10182 if( !pProto->CanChangeEquipStateInCombat() )
10184 if( isInCombat() )
10185 return EQUIP_ERR_NOT_IN_COMBAT;
10187 if(BattleGround* bg = GetBattleGround())
10188 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
10189 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
10192 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
10193 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
10195 return EQUIP_ERR_OK;
10198 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
10200 if (!pItem)
10201 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10203 uint32 count = pItem->GetCount();
10205 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
10206 ItemPrototype const *pProto = pItem->GetProto();
10207 if (!pProto)
10208 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10210 // item used
10211 if(pItem->m_lootGenerated)
10212 return EQUIP_ERR_ALREADY_LOOTED;
10214 if (pItem->IsBindedNotWith(this))
10215 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10217 // check count of items (skip for auto move for same player from bank)
10218 uint8 res = CanTakeMoreSimilarItems(pItem);
10219 if (res != EQUIP_ERR_OK)
10220 return res;
10222 // in specific slot
10223 if (bag != NULL_BAG && slot != NULL_SLOT)
10225 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
10227 if (!pItem->IsBag())
10228 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
10230 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
10231 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
10233 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
10234 return cantuse;
10237 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
10238 if (res!=EQUIP_ERR_OK)
10239 return res;
10241 if (count==0)
10242 return EQUIP_ERR_OK;
10245 // not specific slot or have space for partly store only in specific slot
10247 // in specific bag
10248 if( bag != NULL_BAG )
10250 if( pProto->InventoryType == INVTYPE_BAG )
10252 Bag *pBag = (Bag*)pItem;
10253 if( pBag && !pBag->IsEmpty() )
10254 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
10257 // search stack in bag for merge to
10258 if( pProto->Stackable != 1 )
10260 if( bag == INVENTORY_SLOT_BAG_0 )
10262 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10263 if(res!=EQUIP_ERR_OK)
10264 return res;
10266 if(count==0)
10267 return EQUIP_ERR_OK;
10269 else
10271 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
10272 if(res!=EQUIP_ERR_OK)
10273 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
10275 if(res!=EQUIP_ERR_OK)
10276 return res;
10278 if(count==0)
10279 return EQUIP_ERR_OK;
10283 // search free slot in bag
10284 if( bag == INVENTORY_SLOT_BAG_0 )
10286 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10287 if(res!=EQUIP_ERR_OK)
10288 return res;
10290 if(count==0)
10291 return EQUIP_ERR_OK;
10293 else
10295 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
10296 if(res != EQUIP_ERR_OK)
10297 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
10299 if(res != EQUIP_ERR_OK)
10300 return res;
10302 if(count == 0)
10303 return EQUIP_ERR_OK;
10307 // not specific bag or have space for partly store only in specific bag
10309 // search stack for merge to
10310 if( pProto->Stackable != 1 )
10312 // in slots
10313 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10314 if(res != EQUIP_ERR_OK)
10315 return res;
10317 if(count == 0)
10318 return EQUIP_ERR_OK;
10320 // in special bags
10321 if( pProto->BagFamily )
10323 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10325 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10326 if(res!=EQUIP_ERR_OK)
10327 continue;
10329 if(count==0)
10330 return EQUIP_ERR_OK;
10334 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10336 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10337 if(res!=EQUIP_ERR_OK)
10338 continue;
10340 if(count==0)
10341 return EQUIP_ERR_OK;
10345 // search free place in special bag
10346 if( pProto->BagFamily )
10348 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10350 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10351 if(res!=EQUIP_ERR_OK)
10352 continue;
10354 if(count==0)
10355 return EQUIP_ERR_OK;
10359 // search free space
10360 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10361 if(res!=EQUIP_ERR_OK)
10362 return res;
10364 if(count==0)
10365 return EQUIP_ERR_OK;
10367 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10369 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10370 if(res!=EQUIP_ERR_OK)
10371 continue;
10373 if(count==0)
10374 return EQUIP_ERR_OK;
10376 return EQUIP_ERR_BANK_FULL;
10379 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10381 if (pItem)
10383 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10385 if (!isAlive() && not_loading)
10386 return EQUIP_ERR_YOU_ARE_DEAD;
10388 //if (isStunned())
10389 // return EQUIP_ERR_YOU_ARE_STUNNED;
10391 ItemPrototype const *pProto = pItem->GetProto();
10392 if (pProto)
10394 if (pItem->IsBindedNotWith(this))
10395 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10397 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
10398 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10400 if (uint32 item_use_skill = pItem->GetSkill())
10402 if (GetSkillValue(item_use_skill) == 0)
10404 // armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
10405 if (pProto->Class != ITEM_CLASS_ARMOR)
10406 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10408 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : NULL;
10409 if (!ssd)
10410 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10412 bool allowScaleSkill = false;
10413 for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i)
10415 SkillLineAbilityEntry const *skillInfo = sSkillLineAbilityStore.LookupEntry(i);
10416 if (!skillInfo)
10417 continue;
10419 if (skillInfo->skillId != item_use_skill)
10420 continue;
10422 // can't learn
10423 if (skillInfo->classmask && (skillInfo->classmask & getClassMask()) == 0)
10424 continue;
10426 if (skillInfo->racemask && (skillInfo->racemask & getRaceMask()) == 0)
10427 continue;
10429 allowScaleSkill = true;
10430 break;
10433 if (!allowScaleSkill)
10434 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10438 if (pProto->RequiredSkill != 0)
10440 if (GetSkillValue( pProto->RequiredSkill ) == 0)
10441 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10443 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
10444 return EQUIP_ERR_CANT_EQUIP_SKILL;
10447 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
10448 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10450 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
10451 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10453 if (getLevel() < pProto->RequiredLevel)
10454 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10456 return EQUIP_ERR_OK;
10459 return EQUIP_ERR_ITEM_NOT_FOUND;
10462 bool Player::CanUseItem( ItemPrototype const *pProto )
10464 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10466 if( pProto )
10468 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10469 return false;
10470 if( pProto->RequiredSkill != 0 )
10472 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10473 return false;
10474 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10475 return false;
10477 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10478 return false;
10479 if( getLevel() < pProto->RequiredLevel )
10480 return false;
10481 return true;
10483 return false;
10486 uint8 Player::CanUseAmmo( uint32 item ) const
10488 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10489 if( !isAlive() )
10490 return EQUIP_ERR_YOU_ARE_DEAD;
10491 //if( isStunned() )
10492 // return EQUIP_ERR_YOU_ARE_STUNNED;
10493 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
10494 if( pProto )
10496 if( pProto->InventoryType!= INVTYPE_AMMO )
10497 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10498 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10499 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10500 if( pProto->RequiredSkill != 0 )
10502 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10503 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10504 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10505 return EQUIP_ERR_CANT_EQUIP_SKILL;
10507 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10508 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10509 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10510 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10512 if( getLevel() < pProto->RequiredLevel )
10513 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10515 // Requires No Ammo
10516 if(GetDummyAura(46699))
10517 return EQUIP_ERR_BAG_FULL6;
10519 return EQUIP_ERR_OK;
10521 return EQUIP_ERR_ITEM_NOT_FOUND;
10524 void Player::SetAmmo( uint32 item )
10526 if(!item)
10527 return;
10529 // already set
10530 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10531 return;
10533 // check ammo
10534 if (item)
10536 uint8 msg = CanUseAmmo( item );
10537 if (msg != EQUIP_ERR_OK)
10539 SendEquipError(msg, NULL, NULL, item);
10540 return;
10544 SetUInt32Value(PLAYER_AMMO_ID, item);
10546 _ApplyAmmoBonuses();
10549 void Player::RemoveAmmo()
10551 SetUInt32Value(PLAYER_AMMO_ID, 0);
10553 m_ammoDPS = 0.0f;
10555 if (CanModifyStats())
10556 UpdateDamagePhysical(RANGED_ATTACK);
10559 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10560 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10562 uint32 count = 0;
10563 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10564 count += itr->count;
10566 Item *pItem = Item::CreateItem( item, count, this );
10567 if( pItem )
10569 ItemAddedQuestCheck( item, count );
10570 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, count);
10571 if(randomPropertyId)
10572 pItem->SetItemRandomProperties(randomPropertyId);
10573 pItem = StoreItem( dest, pItem, update );
10575 return pItem;
10578 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10580 if( !pItem )
10581 return NULL;
10583 Item* lastItem = pItem;
10584 uint32 entry = pItem->GetEntry();
10585 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10587 uint16 pos = itr->pos;
10588 uint32 count = itr->count;
10590 ++itr;
10592 if(itr == dest.end())
10594 lastItem = _StoreItem(pos,pItem,count,false,update);
10595 break;
10598 lastItem = _StoreItem(pos,pItem,count,true,update);
10600 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10601 return lastItem;
10604 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10605 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10607 if( !pItem )
10608 return NULL;
10610 uint8 bag = pos >> 8;
10611 uint8 slot = pos & 255;
10613 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10615 Item *pItem2 = GetItemByPos( bag, slot );
10617 if (!pItem2)
10619 if (clone)
10620 pItem = pItem->CloneItem(count, this);
10621 else
10622 pItem->SetCount(count);
10624 if (!pItem)
10625 return NULL;
10627 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10628 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10629 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10630 pItem->SetBinding( true );
10632 if (bag == INVENTORY_SLOT_BAG_0)
10634 m_items[slot] = pItem;
10635 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10636 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10637 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10639 pItem->SetSlot( slot );
10640 pItem->SetContainer( NULL );
10642 // need update known currency
10643 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10644 UpdateKnownCurrencies(pItem->GetEntry(), true);
10646 if (IsInWorld() && update)
10648 pItem->AddToWorld();
10649 pItem->SendCreateUpdateToPlayer( this );
10652 pItem->SetState(ITEM_CHANGED, this);
10654 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10656 pBag->StoreItem( slot, pItem, update );
10657 if( IsInWorld() && update )
10659 pItem->AddToWorld();
10660 pItem->SendCreateUpdateToPlayer( this );
10662 pItem->SetState(ITEM_CHANGED, this);
10663 pBag->SetState(ITEM_CHANGED, this);
10666 AddEnchantmentDurations(pItem);
10667 AddItemDurations(pItem);
10669 return pItem;
10671 else
10673 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10674 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10675 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10676 pItem2->SetBinding( true );
10678 pItem2->SetCount( pItem2->GetCount() + count );
10679 if (IsInWorld() && update)
10680 pItem2->SendCreateUpdateToPlayer( this );
10682 if (!clone)
10684 // delete item (it not in any slot currently)
10685 if (IsInWorld() && update)
10687 pItem->RemoveFromWorld();
10688 pItem->DestroyForPlayer( this );
10691 RemoveEnchantmentDurations(pItem);
10692 RemoveItemDurations(pItem);
10694 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10695 pItem->SetState(ITEM_REMOVED, this);
10698 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10699 AddEnchantmentDurations(pItem2);
10701 pItem2->SetState(ITEM_CHANGED, this);
10703 return pItem2;
10707 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10709 if (Item *pItem = Item::CreateItem( item, 1, this ))
10711 ItemAddedQuestCheck( item, 1 );
10712 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, 1);
10713 return EquipItem( pos, pItem, update );
10716 return NULL;
10719 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10721 AddEnchantmentDurations(pItem);
10722 AddItemDurations(pItem);
10724 uint8 bag = pos >> 8;
10725 uint8 slot = pos & 255;
10727 Item *pItem2 = GetItemByPos( bag, slot );
10729 if( !pItem2 )
10731 VisualizeItem( slot, pItem);
10733 if(isAlive())
10735 ItemPrototype const *pProto = pItem->GetProto();
10737 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10738 if(pProto && pProto->ItemSet)
10739 AddItemsSetItem(this, pItem);
10741 _ApplyItemMods(pItem, slot, true);
10743 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10745 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10747 if (getClass() == CLASS_ROGUE)
10748 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10750 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10752 if (!spellProto)
10753 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10754 else
10756 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10758 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10759 data << uint64(GetGUID());
10760 data << uint8(1);
10761 data << uint32(cooldownSpell);
10762 data << uint32(0);
10763 GetSession()->SendPacket(&data);
10768 if( IsInWorld() && update )
10770 pItem->AddToWorld();
10771 pItem->SendCreateUpdateToPlayer( this );
10774 ApplyEquipCooldown(pItem);
10776 if( slot == EQUIPMENT_SLOT_MAINHAND )
10778 UpdateExpertise(BASE_ATTACK);
10779 UpdateArmorPenetration();
10781 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10783 UpdateExpertise(OFF_ATTACK);
10784 UpdateArmorPenetration();
10787 else
10789 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10790 if( IsInWorld() && update )
10791 pItem2->SendCreateUpdateToPlayer( this );
10793 // delete item (it not in any slot currently)
10794 //pItem->DeleteFromDB();
10795 if( IsInWorld() && update )
10797 pItem->RemoveFromWorld();
10798 pItem->DestroyForPlayer( this );
10801 RemoveEnchantmentDurations(pItem);
10802 RemoveItemDurations(pItem);
10804 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10805 pItem->SetState(ITEM_REMOVED, this);
10806 pItem2->SetState(ITEM_CHANGED, this);
10808 ApplyEquipCooldown(pItem2);
10810 return pItem2;
10813 // only for full equip instead adding to stack
10814 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10815 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot+1);
10817 return pItem;
10820 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10822 if( pItem )
10824 AddEnchantmentDurations(pItem);
10825 AddItemDurations(pItem);
10827 uint8 slot = pos & 255;
10828 VisualizeItem( slot, pItem);
10830 if( IsInWorld() )
10832 pItem->AddToWorld();
10833 pItem->SendCreateUpdateToPlayer( this );
10836 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10837 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot+1);
10841 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10843 if(pItem)
10845 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10846 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10847 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10849 else
10851 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10852 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10856 void Player::VisualizeItem( uint8 slot, Item *pItem)
10858 if(!pItem)
10859 return;
10861 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10862 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10863 pItem->SetBinding( true );
10865 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10867 m_items[slot] = pItem;
10868 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10869 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10870 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10871 pItem->SetSlot( slot );
10872 pItem->SetContainer( NULL );
10874 if( slot < EQUIPMENT_SLOT_END )
10875 SetVisibleItemSlot(slot, pItem);
10877 pItem->SetState(ITEM_CHANGED, this);
10880 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10882 // note: removeitem does not actually change the item
10883 // it only takes the item out of storage temporarily
10884 // note2: if removeitem is to be used for delinking
10885 // the item must be removed from the player's updatequeue
10887 Item *pItem = GetItemByPos( bag, slot );
10888 if( pItem )
10890 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10892 RemoveEnchantmentDurations(pItem);
10893 RemoveItemDurations(pItem);
10895 if( bag == INVENTORY_SLOT_BAG_0 )
10897 if ( slot < INVENTORY_SLOT_BAG_END )
10899 ItemPrototype const *pProto = pItem->GetProto();
10900 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10902 if(pProto && pProto->ItemSet)
10903 RemoveItemsSetItem(this, pProto);
10905 _ApplyItemMods(pItem, slot, false);
10907 // remove item dependent auras and casts (only weapon and armor slots)
10908 if(slot < EQUIPMENT_SLOT_END)
10910 RemoveItemDependentAurasAndCasts(pItem);
10912 // remove held enchantments, update expertise
10913 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10915 if (pItem->GetItemSuffixFactor())
10917 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10918 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10920 else
10922 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10923 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10926 UpdateExpertise(BASE_ATTACK);
10927 UpdateArmorPenetration();
10929 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10931 UpdateExpertise(OFF_ATTACK);
10932 UpdateArmorPenetration();
10936 // need update known currency
10937 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10938 UpdateKnownCurrencies(pItem->GetEntry(), false);
10940 m_items[slot] = NULL;
10941 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10943 if ( slot < EQUIPMENT_SLOT_END )
10944 SetVisibleItemSlot(slot, NULL);
10946 else
10948 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10949 if( pBag )
10950 pBag->RemoveItem(slot, update);
10952 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10953 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10954 pItem->SetSlot( NULL_SLOT );
10955 if( IsInWorld() && update )
10956 pItem->SendCreateUpdateToPlayer( this );
10960 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10961 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10963 if(Item* it = GetItemByPos(bag,slot))
10965 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10966 RemoveItem(bag, slot, update);
10967 it->RemoveFromUpdateQueueOf(this);
10968 if(it->IsInWorld())
10970 it->RemoveFromWorld();
10971 it->DestroyForPlayer( this );
10976 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10977 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10979 // update quest counters
10980 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10981 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, pItem->GetEntry(), pItem->GetCount());
10983 // store item
10984 Item* pLastItem = StoreItem(dest, pItem, update);
10986 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10987 if(pLastItem == pItem)
10989 // update owner for last item (this can be original item with wrong owner
10990 if(pLastItem->GetOwnerGUID() != GetGUID())
10991 pLastItem->SetOwnerGUID(GetGUID());
10993 // if this original item then it need create record in inventory
10994 // in case trade we already have item in other player inventory
10995 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10999 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
11001 Item *pItem = GetItemByPos( bag, slot );
11002 if( pItem )
11004 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
11006 // start from destroy contained items (only equipped bag can have its)
11007 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
11009 for (int i = 0; i < MAX_BAG_SIZE; ++i)
11010 DestroyItem(slot, i, update);
11013 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
11014 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
11016 RemoveEnchantmentDurations(pItem);
11017 RemoveItemDurations(pItem);
11019 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
11021 if( bag == INVENTORY_SLOT_BAG_0 )
11023 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
11025 // equipment and equipped bags can have applied bonuses
11026 if ( slot < INVENTORY_SLOT_BAG_END )
11028 ItemPrototype const *pProto = pItem->GetProto();
11030 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
11031 if(pProto && pProto->ItemSet)
11032 RemoveItemsSetItem(this, pProto);
11034 _ApplyItemMods(pItem, slot, false);
11037 if ( slot < EQUIPMENT_SLOT_END )
11039 // remove item dependent auras and casts (only weapon and armor slots)
11040 RemoveItemDependentAurasAndCasts(pItem);
11042 // update expertise
11043 if( slot == EQUIPMENT_SLOT_MAINHAND )
11045 UpdateExpertise(BASE_ATTACK);
11046 UpdateArmorPenetration();
11048 else if( slot == EQUIPMENT_SLOT_OFFHAND )
11050 UpdateExpertise(OFF_ATTACK);
11051 UpdateArmorPenetration();
11054 // equipment visual show
11055 SetVisibleItemSlot(slot, NULL);
11057 // need update known currency
11058 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
11059 UpdateKnownCurrencies(pItem->GetEntry(), false);
11061 m_items[slot] = NULL;
11063 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
11064 pBag->RemoveItem(slot, update);
11066 if( IsInWorld() && update )
11068 pItem->RemoveFromWorld();
11069 pItem->DestroyForPlayer(this);
11072 //pItem->SetOwnerGUID(0);
11073 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
11074 pItem->SetSlot( NULL_SLOT );
11075 pItem->SetState(ITEM_REMOVED, this);
11079 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
11081 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
11082 uint32 remcount = 0;
11084 // in inventory
11085 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11087 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11089 if (pItem->GetEntry() == item)
11091 if (pItem->GetCount() + remcount <= count)
11093 // all items in inventory can unequipped
11094 remcount += pItem->GetCount();
11095 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11097 if (remcount >= count)
11098 return;
11100 else
11102 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11103 pItem->SetCount( pItem->GetCount() - count + remcount );
11104 if (IsInWorld() & update)
11105 pItem->SendCreateUpdateToPlayer( this );
11106 pItem->SetState(ITEM_CHANGED, this);
11107 return;
11113 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
11115 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11117 if (pItem->GetEntry() == item)
11119 if (pItem->GetCount() + remcount <= count)
11121 // all keys can be unequipped
11122 remcount += pItem->GetCount();
11123 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11125 if (remcount >= count)
11126 return;
11128 else
11130 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11131 pItem->SetCount( pItem->GetCount() - count + remcount );
11132 if (IsInWorld() & update)
11133 pItem->SendCreateUpdateToPlayer( this );
11134 pItem->SetState(ITEM_CHANGED, this);
11135 return;
11141 // in inventory bags
11142 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11144 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11146 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11148 if(Item* pItem = pBag->GetItemByPos(j))
11150 if (pItem->GetEntry() == item)
11152 // all items in bags can be unequipped
11153 if (pItem->GetCount() + remcount <= count)
11155 remcount += pItem->GetCount();
11156 DestroyItem( i, j, update );
11158 if (remcount >= count)
11159 return;
11161 else
11163 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11164 pItem->SetCount( pItem->GetCount() - count + remcount );
11165 if (IsInWorld() && update)
11166 pItem->SendCreateUpdateToPlayer( this );
11167 pItem->SetState(ITEM_CHANGED, this);
11168 return;
11176 // in equipment and bag list
11177 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11179 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11181 if (pItem && pItem->GetEntry() == item)
11183 if (pItem->GetCount() + remcount <= count)
11185 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
11187 remcount += pItem->GetCount();
11188 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11190 if (remcount >= count)
11191 return;
11194 else
11196 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11197 pItem->SetCount( pItem->GetCount() - count + remcount );
11198 if (IsInWorld() & update)
11199 pItem->SendCreateUpdateToPlayer( this );
11200 pItem->SetState(ITEM_CHANGED, this);
11201 return;
11208 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
11210 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
11212 // in inventory
11213 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11214 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11215 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11216 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11218 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
11219 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11220 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11221 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11223 // in inventory bags
11224 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11225 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11226 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11227 if (Item* pItem = pBag->GetItemByPos(j))
11228 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11229 DestroyItem(i, j, update);
11231 // in equipment and bag list
11232 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11233 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11234 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11235 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11238 void Player::DestroyConjuredItems( bool update )
11240 // used when entering arena
11241 // destroys all conjured items
11242 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
11244 // in inventory
11245 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11246 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11247 if (pItem->IsConjuredConsumable())
11248 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11250 // in inventory bags
11251 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11252 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11253 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11254 if (Item* pItem = pBag->GetItemByPos(j))
11255 if (pItem->IsConjuredConsumable())
11256 DestroyItem( i, j, update);
11258 // in equipment and bag list
11259 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11260 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11261 if (pItem->IsConjuredConsumable())
11262 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11265 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
11267 if(!pItem)
11268 return;
11270 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
11272 if( pItem->GetCount() <= count )
11274 count -= pItem->GetCount();
11276 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
11278 else
11280 ItemRemovedQuestCheck( pItem->GetEntry(), count);
11281 pItem->SetCount( pItem->GetCount() - count );
11282 count = 0;
11283 if( IsInWorld() & update )
11284 pItem->SendCreateUpdateToPlayer( this );
11285 pItem->SetState(ITEM_CHANGED, this);
11289 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
11291 uint8 srcbag = src >> 8;
11292 uint8 srcslot = src & 255;
11294 uint8 dstbag = dst >> 8;
11295 uint8 dstslot = dst & 255;
11297 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11298 if( !pSrcItem )
11300 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11301 return;
11304 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11306 //best error message found for attempting to split while looting
11307 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11308 return;
11311 // not let split all items (can be only at cheating)
11312 if(pSrcItem->GetCount() == count)
11314 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11315 return;
11318 // not let split more existed items (can be only at cheating)
11319 if(pSrcItem->GetCount() < count)
11321 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
11322 return;
11325 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11326 Item *pNewItem = pSrcItem->CloneItem( count, this );
11327 if( !pNewItem )
11329 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11330 return;
11333 if( IsInventoryPos( dst ) )
11335 // change item amount before check (for unique max count check)
11336 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11338 ItemPosCountVec dest;
11339 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11340 if( msg != EQUIP_ERR_OK )
11342 delete pNewItem;
11343 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11344 SendEquipError( msg, pSrcItem, NULL );
11345 return;
11348 if( IsInWorld() )
11349 pSrcItem->SendCreateUpdateToPlayer( this );
11350 pSrcItem->SetState(ITEM_CHANGED, this);
11351 StoreItem( dest, pNewItem, true);
11353 else if( IsBankPos ( dst ) )
11355 // change item amount before check (for unique max count check)
11356 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11358 ItemPosCountVec dest;
11359 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11360 if( msg != EQUIP_ERR_OK )
11362 delete pNewItem;
11363 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11364 SendEquipError( msg, pSrcItem, NULL );
11365 return;
11368 if( IsInWorld() )
11369 pSrcItem->SendCreateUpdateToPlayer( this );
11370 pSrcItem->SetState(ITEM_CHANGED, this);
11371 BankItem( dest, pNewItem, true);
11373 else if( IsEquipmentPos ( dst ) )
11375 // change item amount before check (for unique max count check), provide space for splitted items
11376 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11378 uint16 dest;
11379 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11380 if( msg != EQUIP_ERR_OK )
11382 delete pNewItem;
11383 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11384 SendEquipError( msg, pSrcItem, NULL );
11385 return;
11388 if( IsInWorld() )
11389 pSrcItem->SendCreateUpdateToPlayer( this );
11390 pSrcItem->SetState(ITEM_CHANGED, this);
11391 EquipItem( dest, pNewItem, true);
11392 AutoUnequipOffhandIfNeed();
11396 void Player::SwapItem( uint16 src, uint16 dst )
11398 uint8 srcbag = src >> 8;
11399 uint8 srcslot = src & 255;
11401 uint8 dstbag = dst >> 8;
11402 uint8 dstslot = dst & 255;
11404 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11405 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11407 if (!pSrcItem)
11408 return;
11410 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11412 if (!isAlive())
11414 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11415 return;
11418 // SRC checks
11420 // check unequip potability for equipped items and bank bags
11421 if (IsEquipmentPos(src) || IsBagPos(src))
11423 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11424 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty()));
11425 if (msg != EQUIP_ERR_OK)
11427 SendEquipError( msg, pSrcItem, pDstItem );
11428 return;
11432 // prevent put equipped/bank bag in self
11433 if (IsBagPos(src) && srcslot == dstbag)
11435 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11436 return;
11439 // prevent put equipped/bank bag in self
11440 if (IsBagPos(dst) && dstslot == srcbag)
11442 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pDstItem, pSrcItem );
11443 return;
11446 // DST checks
11448 if (pDstItem)
11450 // check unequip potability for equipped items and bank bags
11451 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11453 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11454 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty()));
11455 if(msg != EQUIP_ERR_OK)
11457 SendEquipError( msg, pSrcItem, pDstItem );
11458 return;
11463 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11464 // or swap empty bag with another empty or not empty bag (with items exchange)
11466 // Move case
11467 if( !pDstItem )
11469 if( IsInventoryPos( dst ) )
11471 ItemPosCountVec dest;
11472 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11473 if( msg != EQUIP_ERR_OK )
11475 SendEquipError( msg, pSrcItem, NULL );
11476 return;
11479 RemoveItem(srcbag, srcslot, true);
11480 StoreItem( dest, pSrcItem, true);
11482 else if( IsBankPos ( dst ) )
11484 ItemPosCountVec dest;
11485 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11486 if( msg != EQUIP_ERR_OK )
11488 SendEquipError( msg, pSrcItem, NULL );
11489 return;
11492 RemoveItem(srcbag, srcslot, true);
11493 BankItem( dest, pSrcItem, true);
11495 else if( IsEquipmentPos ( dst ) )
11497 uint16 dest;
11498 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11499 if( msg != EQUIP_ERR_OK )
11501 SendEquipError( msg, pSrcItem, NULL );
11502 return;
11505 RemoveItem(srcbag, srcslot, true);
11506 EquipItem(dest, pSrcItem, true);
11507 AutoUnequipOffhandIfNeed();
11510 return;
11513 // attempt merge to / fill target item
11514 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11516 uint8 msg;
11517 ItemPosCountVec sDest;
11518 uint16 eDest;
11519 if( IsInventoryPos( dst ) )
11520 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11521 else if( IsBankPos ( dst ) )
11522 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11523 else if( IsEquipmentPos ( dst ) )
11524 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11525 else
11526 return;
11528 // can be merge/fill
11529 if(msg == EQUIP_ERR_OK)
11531 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11533 RemoveItem(srcbag, srcslot, true);
11535 if( IsInventoryPos( dst ) )
11536 StoreItem( sDest, pSrcItem, true);
11537 else if( IsBankPos ( dst ) )
11538 BankItem( sDest, pSrcItem, true);
11539 else if( IsEquipmentPos ( dst ) )
11541 EquipItem( eDest, pSrcItem, true);
11542 AutoUnequipOffhandIfNeed();
11545 else
11547 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11548 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11549 pSrcItem->SetState(ITEM_CHANGED, this);
11550 pDstItem->SetState(ITEM_CHANGED, this);
11551 if( IsInWorld() )
11553 pSrcItem->SendCreateUpdateToPlayer( this );
11554 pDstItem->SendCreateUpdateToPlayer( this );
11557 return;
11561 // impossible merge/fill, do real swap
11562 uint8 msg;
11564 // check src->dest move possibility
11565 ItemPosCountVec sDest;
11566 uint16 eDest = 0;
11567 if( IsInventoryPos( dst ) )
11568 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11569 else if( IsBankPos( dst ) )
11570 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11571 else if( IsEquipmentPos( dst ) )
11573 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11574 if( msg == EQUIP_ERR_OK )
11575 msg = CanUnequipItem( eDest, true );
11578 if( msg != EQUIP_ERR_OK )
11580 SendEquipError( msg, pSrcItem, pDstItem );
11581 return;
11584 // check dest->src move possibility
11585 ItemPosCountVec sDest2;
11586 uint16 eDest2 = 0;
11587 if( IsInventoryPos( src ) )
11588 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11589 else if( IsBankPos( src ) )
11590 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11591 else if( IsEquipmentPos( src ) )
11593 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11594 if( msg == EQUIP_ERR_OK )
11595 msg = CanUnequipItem( eDest2, true);
11598 if( msg != EQUIP_ERR_OK )
11600 SendEquipError( msg, pDstItem, pSrcItem );
11601 return;
11604 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11605 if(pSrcItem->IsBag() && pDstItem->IsBag())
11607 Bag* emptyBag = NULL;
11608 Bag* fullBag = NULL;
11609 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11611 emptyBag = (Bag*)pSrcItem;
11612 fullBag = (Bag*)pDstItem;
11614 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11616 emptyBag = (Bag*)pDstItem;
11617 fullBag = (Bag*)pSrcItem;
11620 // bag swap (with items exchange) case
11621 if(emptyBag && fullBag)
11623 ItemPrototype const* emotyProto = emptyBag->GetProto();
11625 uint32 count = 0;
11627 for(uint32 i=0; i < fullBag->GetBagSize(); ++i)
11629 Item *bagItem = fullBag->GetItemByPos(i);
11630 if (!bagItem)
11631 continue;
11633 ItemPrototype const* bagItemProto = bagItem->GetProto();
11634 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11636 // one from items not go to empty target bag
11637 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11638 return;
11641 ++count;
11645 if (count > emptyBag->GetBagSize())
11647 // too small targeted bag
11648 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11649 return;
11652 // Items swap
11653 count = 0; // will pos in new bag
11654 for(uint32 i = 0; i< fullBag->GetBagSize(); ++i)
11656 Item *bagItem = fullBag->GetItemByPos(i);
11657 if (!bagItem)
11658 continue;
11660 fullBag->RemoveItem(i, true);
11661 emptyBag->StoreItem(count, bagItem, true);
11662 bagItem->SetState(ITEM_CHANGED, this);
11664 ++count;
11669 // now do moves, remove...
11670 RemoveItem(dstbag, dstslot, false);
11671 RemoveItem(srcbag, srcslot, false);
11673 // add to dest
11674 if (IsInventoryPos(dst))
11675 StoreItem(sDest, pSrcItem, true);
11676 else if (IsBankPos(dst))
11677 BankItem(sDest, pSrcItem, true);
11678 else if (IsEquipmentPos(dst))
11679 EquipItem(eDest, pSrcItem, true);
11681 // add to src
11682 if (IsInventoryPos(src))
11683 StoreItem(sDest2, pDstItem, true);
11684 else if (IsBankPos(src))
11685 BankItem(sDest2, pDstItem, true);
11686 else if (IsEquipmentPos(src))
11687 EquipItem(eDest2, pDstItem, true);
11689 AutoUnequipOffhandIfNeed();
11692 void Player::AddItemToBuyBackSlot( Item *pItem )
11694 if (pItem)
11696 uint32 slot = m_currentBuybackSlot;
11697 // if current back slot non-empty search oldest or free
11698 if (m_items[slot])
11700 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11701 uint32 oldest_slot = BUYBACK_SLOT_START;
11703 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11705 // found empty
11706 if (!m_items[i])
11708 slot = i;
11709 break;
11712 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11714 if (oldest_time > i_time)
11716 oldest_time = i_time;
11717 oldest_slot = i;
11721 // find oldest
11722 slot = oldest_slot;
11725 RemoveItemFromBuyBackSlot( slot, true );
11726 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11728 m_items[slot] = pItem;
11729 time_t base = time(NULL);
11730 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11731 uint32 eslot = slot - BUYBACK_SLOT_START;
11733 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11734 if (ItemPrototype const *pProto = pItem->GetProto())
11735 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11736 else
11737 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11738 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11740 // move to next (for non filled list is move most optimized choice)
11741 if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11742 ++m_currentBuybackSlot;
11746 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11748 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11749 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11750 return m_items[slot];
11751 return NULL;
11754 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11756 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11757 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11759 Item *pItem = m_items[slot];
11760 if (pItem)
11762 pItem->RemoveFromWorld();
11763 if(del) pItem->SetState(ITEM_REMOVED, this);
11766 m_items[slot] = NULL;
11768 uint32 eslot = slot - BUYBACK_SLOT_START;
11769 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11770 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11771 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11773 // if current backslot is filled set to now free slot
11774 if (m_items[m_currentBuybackSlot])
11775 m_currentBuybackSlot = slot;
11779 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2, uint32 itemid /*= 0*/ )
11781 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11782 WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, 1+8+8+1);
11783 data << uint8(msg);
11785 if (msg != EQUIP_ERR_OK)
11787 data << uint64(pItem ? pItem->GetGUID() : 0);
11788 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11789 data << uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2
11791 switch(msg)
11793 case EQUIP_ERR_CANT_EQUIP_LEVEL_I:
11794 case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW:
11796 ItemPrototype const* proto = pItem ? pItem->GetProto() : sObjectMgr.GetItemPrototype(itemid);
11797 data << uint32(proto ? proto->RequiredLevel : 0);
11798 break;
11800 case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM: // no idea about this one...
11802 data << uint64(0);
11803 data << uint32(0);
11804 data << uint64(0);
11805 break;
11807 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS:
11808 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS:
11809 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS:
11811 ItemPrototype const* proto = pItem ? pItem->GetProto() : sObjectMgr.GetItemPrototype(itemid);
11812 data << uint32(proto ? proto->ItemLimitCategory : 0);
11813 break;
11815 default:
11816 break;
11819 GetSession()->SendPacket(&data);
11822 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11824 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11825 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11826 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11827 data << uint32(item);
11828 if (param > 0)
11829 data << uint32(param);
11830 data << uint8(msg);
11831 GetSession()->SendPacket(&data);
11834 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11836 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11837 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11838 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11839 data << uint64(guid);
11840 if (param > 0)
11841 data << uint32(param);
11842 data << uint8(msg);
11843 GetSession()->SendPacket(&data);
11846 void Player::ClearTrade()
11848 tradeGold = 0;
11849 acceptTrade = false;
11850 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11851 tradeItems[i] = NULL_SLOT;
11854 void Player::TradeCancel(bool sendback)
11856 if (pTrader)
11858 // send yellow "Trade canceled" message to both traders
11859 WorldSession* ws;
11860 ws = GetSession();
11861 if (sendback)
11862 ws->SendCancelTrade();
11863 ws = pTrader->GetSession();
11864 if (!ws->PlayerLogout())
11865 ws->SendCancelTrade();
11867 // cleanup
11868 ClearTrade();
11869 pTrader->ClearTrade();
11870 // prevent loss of reference
11871 pTrader->pTrader = NULL;
11872 pTrader = NULL;
11876 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11878 if (m_itemDuration.empty())
11879 return;
11881 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11883 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11885 Item* item = *itr;
11886 ++itr; // current element can be erased in UpdateDuration
11888 if ((realtimeonly && item->GetProto()->Duration < 0) || !realtimeonly)
11889 item->UpdateDuration(this,time);
11893 void Player::UpdateEnchantTime(uint32 time)
11895 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11897 assert(itr->item);
11898 next = itr;
11899 if (!itr->item->GetEnchantmentId(itr->slot))
11901 next = m_enchantDuration.erase(itr);
11903 else if (itr->leftduration <= time)
11905 ApplyEnchantment(itr->item, itr->slot, false, false);
11906 itr->item->ClearEnchantment(itr->slot);
11907 next = m_enchantDuration.erase(itr);
11909 else if (itr->leftduration > time)
11911 itr->leftduration -= time;
11912 ++next;
11917 void Player::AddEnchantmentDurations(Item *item)
11919 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11921 if (!item->GetEnchantmentId(EnchantmentSlot(x)))
11922 continue;
11924 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11925 if (duration > 0)
11926 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11930 void Player::RemoveEnchantmentDurations(Item *item)
11932 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11934 if (itr->item == item)
11936 // save duration in item
11937 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11938 itr = m_enchantDuration.erase(itr);
11940 else
11941 ++itr;
11945 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11947 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11948 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11950 next = itr;
11951 if (itr->slot == slot)
11953 if (itr->item && itr->item->GetEnchantmentId(slot))
11955 // remove from stats
11956 ApplyEnchantment(itr->item, slot, false, false);
11957 // remove visual
11958 itr->item->ClearEnchantment(slot);
11960 // remove from update list
11961 next = m_enchantDuration.erase(itr);
11963 else
11964 ++next;
11967 // remove enchants from inventory items
11968 // NOTE: no need to remove these from stats, since these aren't equipped
11969 // in inventory
11970 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11971 if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
11972 if (pItem->GetEnchantmentId(slot))
11973 pItem->ClearEnchantment(slot);
11975 // in inventory bags
11976 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11977 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11978 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11979 if (Item* pItem = pBag->GetItemByPos(j))
11980 if (pItem->GetEnchantmentId(slot))
11981 pItem->ClearEnchantment(slot);
11984 // duration == 0 will remove item enchant
11985 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11987 if (!item)
11988 return;
11990 if (slot >= MAX_ENCHANTMENT_SLOT)
11991 return;
11993 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11995 if (itr->item == item && itr->slot == slot)
11997 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11998 m_enchantDuration.erase(itr);
11999 break;
12002 if (item && duration > 0 )
12004 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
12005 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
12009 void Player::ApplyEnchantment(Item *item,bool apply)
12011 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
12012 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
12015 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
12017 if (!item)
12018 return;
12020 if (!item->IsEquipped())
12021 return;
12023 if (slot >= MAX_ENCHANTMENT_SLOT)
12024 return;
12026 uint32 enchant_id = item->GetEnchantmentId(slot);
12027 if (!enchant_id)
12028 return;
12030 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
12031 if (!pEnchant)
12032 return;
12034 if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
12035 return;
12037 if (!item->IsBroken())
12039 for (int s = 0; s < 3; ++s)
12041 uint32 enchant_display_type = pEnchant->type[s];
12042 uint32 enchant_amount = pEnchant->amount[s];
12043 uint32 enchant_spell_id = pEnchant->spellid[s];
12045 switch(enchant_display_type)
12047 case ITEM_ENCHANTMENT_TYPE_NONE:
12048 break;
12049 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
12050 // processed in Player::CastItemCombatSpell
12051 break;
12052 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
12053 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12054 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
12055 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
12056 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
12057 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
12058 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12059 break;
12060 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
12061 if (enchant_spell_id)
12063 if (apply)
12065 int32 basepoints = 0;
12066 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
12067 if (item->GetItemRandomPropertyId())
12069 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
12070 if (item_rand)
12072 // Search enchant_amount
12073 for (int k = 0; k < 3; ++k)
12075 if(item_rand->enchant_id[k] == enchant_id)
12077 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
12078 break;
12083 // Cast custom spell vs all equal basepoints getted from enchant_amount
12084 if (basepoints)
12085 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
12086 else
12087 CastSpell(this, enchant_spell_id, true, item);
12089 else
12090 RemoveAurasDueToItemSpell(item, enchant_spell_id);
12092 break;
12093 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
12094 if (!enchant_amount)
12096 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
12097 if(item_rand)
12099 for (int k = 0; k < 3; ++k)
12101 if(item_rand->enchant_id[k] == enchant_id)
12103 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
12104 break;
12110 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
12111 break;
12112 case ITEM_ENCHANTMENT_TYPE_STAT:
12114 if (!enchant_amount)
12116 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
12117 if(item_rand_suffix)
12119 for (int k = 0; k < 3; ++k)
12121 if(item_rand_suffix->enchant_id[k] == enchant_id)
12123 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
12124 break;
12130 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
12131 switch (enchant_spell_id)
12133 case ITEM_MOD_MANA:
12134 sLog.outDebug("+ %u MANA",enchant_amount);
12135 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
12136 break;
12137 case ITEM_MOD_HEALTH:
12138 sLog.outDebug("+ %u HEALTH",enchant_amount);
12139 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
12140 break;
12141 case ITEM_MOD_AGILITY:
12142 sLog.outDebug("+ %u AGILITY",enchant_amount);
12143 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
12144 ApplyStatBuffMod(STAT_AGILITY, float(enchant_amount), apply);
12145 break;
12146 case ITEM_MOD_STRENGTH:
12147 sLog.outDebug("+ %u STRENGTH",enchant_amount);
12148 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
12149 ApplyStatBuffMod(STAT_STRENGTH, float(enchant_amount), apply);
12150 break;
12151 case ITEM_MOD_INTELLECT:
12152 sLog.outDebug("+ %u INTELLECT",enchant_amount);
12153 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
12154 ApplyStatBuffMod(STAT_INTELLECT, float(enchant_amount), apply);
12155 break;
12156 case ITEM_MOD_SPIRIT:
12157 sLog.outDebug("+ %u SPIRIT",enchant_amount);
12158 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
12159 ApplyStatBuffMod(STAT_SPIRIT, float(enchant_amount), apply);
12160 break;
12161 case ITEM_MOD_STAMINA:
12162 sLog.outDebug("+ %u STAMINA",enchant_amount);
12163 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
12164 ApplyStatBuffMod(STAT_STAMINA, float(enchant_amount), apply);
12165 break;
12166 case ITEM_MOD_DEFENSE_SKILL_RATING:
12167 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
12168 sLog.outDebug("+ %u DEFENCE", enchant_amount);
12169 break;
12170 case ITEM_MOD_DODGE_RATING:
12171 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
12172 sLog.outDebug("+ %u DODGE", enchant_amount);
12173 break;
12174 case ITEM_MOD_PARRY_RATING:
12175 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
12176 sLog.outDebug("+ %u PARRY", enchant_amount);
12177 break;
12178 case ITEM_MOD_BLOCK_RATING:
12179 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
12180 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
12181 break;
12182 case ITEM_MOD_HIT_MELEE_RATING:
12183 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12184 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
12185 break;
12186 case ITEM_MOD_HIT_RANGED_RATING:
12187 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12188 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
12189 break;
12190 case ITEM_MOD_HIT_SPELL_RATING:
12191 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12192 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
12193 break;
12194 case ITEM_MOD_CRIT_MELEE_RATING:
12195 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12196 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
12197 break;
12198 case ITEM_MOD_CRIT_RANGED_RATING:
12199 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12200 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
12201 break;
12202 case ITEM_MOD_CRIT_SPELL_RATING:
12203 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12204 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
12205 break;
12206 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12207 // in Enchantments
12208 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12209 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12210 // break;
12211 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12212 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12213 // break;
12214 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12215 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12216 // break;
12217 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12218 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12219 // break;
12220 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12221 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12222 // break;
12223 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12224 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12225 // break;
12226 // case ITEM_MOD_HASTE_MELEE_RATING:
12227 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12228 // break;
12229 // case ITEM_MOD_HASTE_RANGED_RATING:
12230 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12231 // break;
12232 case ITEM_MOD_HASTE_SPELL_RATING:
12233 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12234 break;
12235 case ITEM_MOD_HIT_RATING:
12236 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12237 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12238 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12239 sLog.outDebug("+ %u HIT", enchant_amount);
12240 break;
12241 case ITEM_MOD_CRIT_RATING:
12242 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12243 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12244 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12245 sLog.outDebug("+ %u CRITICAL", enchant_amount);
12246 break;
12247 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12248 // case ITEM_MOD_HIT_TAKEN_RATING:
12249 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12250 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12251 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12252 // break;
12253 // case ITEM_MOD_CRIT_TAKEN_RATING:
12254 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12255 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12256 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12257 // break;
12258 case ITEM_MOD_RESILIENCE_RATING:
12259 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12260 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12261 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12262 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
12263 break;
12264 case ITEM_MOD_HASTE_RATING:
12265 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12266 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12267 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12268 sLog.outDebug("+ %u HASTE", enchant_amount);
12269 break;
12270 case ITEM_MOD_EXPERTISE_RATING:
12271 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
12272 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
12273 break;
12274 case ITEM_MOD_ATTACK_POWER:
12275 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
12276 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12277 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
12278 break;
12279 case ITEM_MOD_RANGED_ATTACK_POWER:
12280 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12281 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
12282 break;
12283 case ITEM_MOD_MANA_REGENERATION:
12284 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
12285 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
12286 break;
12287 case ITEM_MOD_ARMOR_PENETRATION_RATING:
12288 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
12289 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
12290 break;
12291 case ITEM_MOD_SPELL_POWER:
12292 ((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
12293 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
12294 break;
12295 case ITEM_MOD_FERAL_ATTACK_POWER:
12296 case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
12297 case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
12298 default:
12299 break;
12301 break;
12303 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
12305 if(getClass() == CLASS_SHAMAN)
12307 float addValue = 0.0f;
12308 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12310 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12311 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
12313 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
12315 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12316 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
12319 break;
12321 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
12322 // processed in Player::CastItemUseSpell
12323 break;
12324 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
12325 // nothing do..
12326 break;
12327 default:
12328 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
12329 break;
12330 } /*switch(enchant_display_type)*/
12331 } /*for*/
12334 // visualize enchantment at player and equipped items
12335 if(slot == PERM_ENCHANTMENT_SLOT)
12336 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
12338 if(slot == TEMP_ENCHANTMENT_SLOT)
12339 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
12342 if(apply_dur)
12344 if(apply)
12346 // set duration
12347 uint32 duration = item->GetEnchantmentDuration(slot);
12348 if(duration > 0)
12349 AddEnchantmentDuration(item, slot, duration);
12351 else
12353 // duration == 0 will remove EnchantDuration
12354 AddEnchantmentDuration(item, slot, 0);
12359 void Player::SendEnchantmentDurations()
12361 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
12363 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
12367 void Player::SendItemDurations()
12369 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
12371 (*itr)->SendTimeUpdate(this);
12375 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12377 if(!item) // prevent crash
12378 return;
12380 // last check 2.0.10
12381 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12382 data << uint64(GetGUID()); // player GUID
12383 data << uint32(received); // 0=looted, 1=from npc
12384 data << uint32(created); // 0=received, 1=created
12385 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12386 data << uint8(item->GetBagSlot()); // bagslot
12387 // item slot, but when added to stack: 0xFFFFFFFF
12388 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
12389 data << uint32(item->GetEntry()); // item id
12390 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12391 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12392 data << uint32(count); // count of items
12393 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
12395 if (broadcast && GetGroup())
12396 GetGroup()->BroadcastPacket(&data, true);
12397 else
12398 GetSession()->SendPacket(&data);
12401 /*********************************************************/
12402 /*** GOSSIP SYSTEM ***/
12403 /*********************************************************/
12405 void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId)
12407 PlayerMenu* pMenu = PlayerTalkClass;
12408 pMenu->ClearMenus();
12410 pMenu->GetGossipMenu().SetMenuId(menuId);
12412 GossipMenuItemsMapBounds pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(menuId);
12414 // if default menuId and no menu options exist for this, use options from default options
12415 if (pMenuItemBounds.first == pMenuItemBounds.second && menuId == GetDefaultGossipMenuForSource(pSource))
12416 pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(0);
12418 for(GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr)
12420 bool bCanTalk = true;
12422 if (itr->second.cond_1 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1))
12423 continue;
12425 if (itr->second.cond_2 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12426 continue;
12428 if (itr->second.cond_3 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_3))
12429 continue;
12431 if (pSource->GetTypeId() == TYPEID_UNIT)
12433 Creature *pCreature = (Creature*)pSource;
12435 uint32 npcflags = pCreature->GetUInt32Value(UNIT_NPC_FLAGS);
12437 if (!(itr->second.npc_option_npcflag & npcflags))
12438 continue;
12440 switch(itr->second.option_id)
12442 case GOSSIP_OPTION_QUESTGIVER:
12443 PrepareQuestMenu(pSource->GetGUID());
12444 bCanTalk = false;
12445 break;
12446 case GOSSIP_OPTION_ARMORER:
12447 bCanTalk = false; // added in special mode
12448 break;
12449 case GOSSIP_OPTION_SPIRITHEALER:
12450 if (!isDead())
12451 bCanTalk = false;
12452 break;
12453 case GOSSIP_OPTION_VENDOR:
12455 VendorItemData const* vItems = pCreature->GetVendorItems();
12456 if (!vItems || vItems->Empty())
12458 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature->GetGUIDLow(), pCreature->GetEntry());
12459 bCanTalk = false;
12461 break;
12463 case GOSSIP_OPTION_TRAINER:
12464 if (!pCreature->isCanTrainingOf(this, false))
12465 bCanTalk = false;
12466 break;
12467 case GOSSIP_OPTION_UNLEARNTALENTS:
12468 if (!pCreature->isCanTrainingAndResetTalentsOf(this))
12469 bCanTalk = false;
12470 break;
12471 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12472 if (!GetPet() || GetPet()->getPetType() != HUNTER_PET || GetPet()->m_spells.size() <= 1 || pCreature->GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || pCreature->GetCreatureInfo()->trainer_class != CLASS_HUNTER)
12473 bCanTalk = false;
12474 break;
12475 case GOSSIP_OPTION_TAXIVENDOR:
12476 if (GetSession()->SendLearnNewTaxiNode(pCreature))
12477 return;
12478 break;
12479 case GOSSIP_OPTION_BATTLEFIELD:
12480 if (!pCreature->isCanInteractWithBattleMaster(this, false))
12481 bCanTalk = false;
12482 break;
12483 case GOSSIP_OPTION_STABLEPET:
12484 if (getClass() != CLASS_HUNTER)
12485 bCanTalk = false;
12486 break;
12487 case GOSSIP_OPTION_GOSSIP:
12488 case GOSSIP_OPTION_SPIRITGUIDE:
12489 case GOSSIP_OPTION_INNKEEPER:
12490 case GOSSIP_OPTION_BANKER:
12491 case GOSSIP_OPTION_PETITIONER:
12492 case GOSSIP_OPTION_TABARDDESIGNER:
12493 case GOSSIP_OPTION_AUCTIONEER:
12494 break; // no checks
12495 default:
12496 sLog.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature->GetEntry(), itr->second.option_id, itr->second.menu_id);
12497 bCanTalk = false;
12498 break;
12501 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12503 GameObject *pGo = (GameObject*)pSource;
12505 switch(itr->second.option_id)
12507 case GOSSIP_OPTION_QUESTGIVER:
12508 if (pGo->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
12509 PrepareQuestMenu(pSource->GetGUID());
12510 bCanTalk = false;
12511 break;
12512 case GOSSIP_OPTION_GOSSIP:
12513 if (pGo->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && pGo->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
12514 bCanTalk = false;
12515 break;
12516 default:
12517 bCanTalk = false;
12518 break;
12522 if (bCanTalk)
12524 std::string strOptionText = itr->second.option_text;
12525 std::string strBoxText = itr->second.box_text;
12527 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12529 if (loc_idx >= 0)
12531 uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.id);
12533 if (GossipMenuItemsLocale const *no = sObjectMgr.GetGossipMenuItemsLocale(idxEntry))
12535 if (no->OptionText.size() > (size_t)loc_idx && !no->OptionText[loc_idx].empty())
12536 strOptionText = no->OptionText[loc_idx];
12538 if (no->BoxText.size() > (size_t)loc_idx && !no->BoxText[loc_idx].empty())
12539 strBoxText = no->BoxText[loc_idx];
12543 pMenu->GetGossipMenu().AddMenuItem(itr->second.option_icon, strOptionText, 0, itr->second.option_id, strBoxText, itr->second.box_money, itr->second.box_coded);
12544 pMenu->GetGossipMenu().AddGossipMenuItemData(itr->second.action_menu_id, itr->second.action_poi_id, itr->second.action_script_id);
12548 // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
12549 /*if (pMenu->Empty())
12551 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
12553 // output error message if need
12554 pCreature->isCanTrainingOf(this, true);
12557 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
12559 // output error message if need
12560 pCreature->isCanInteractWithBattleMaster(this, true);
12565 void Player::SendPreparedGossip(WorldObject *pSource)
12567 if (!pSource)
12568 return;
12570 if (pSource->GetTypeId() == TYPEID_UNIT)
12572 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
12573 if (!((Creature*)pSource)->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
12575 SendPreparedQuest(pSource->GetGUID());
12576 return;
12579 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12581 // probably need to find a better way here
12582 if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
12584 SendPreparedQuest(pSource->GetGUID());
12585 return;
12589 // in case non empty gossip menu (that not included quests list size) show it
12590 // (quest entries from quest menu will be included in list)
12592 uint32 textId = GetGossipTextId(pSource);
12594 if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
12595 textId = GetGossipTextId(menuId);
12597 PlayerTalkClass->SendGossipMenu(textId, pSource->GetGUID());
12600 void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 menuId)
12602 GossipMenu& gossipmenu = PlayerTalkClass->GetGossipMenu();
12604 if (gossipListId >= gossipmenu.MenuItemCount())
12605 return;
12607 // if not same, then something funky is going on
12608 if (menuId != gossipmenu.GetMenuId())
12609 return;
12611 uint32 gossipOptionId = gossipmenu.GetItem(gossipListId).m_gOptionId;
12612 uint64 guid = pSource->GetGUID();
12614 if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12616 if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
12618 sLog.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource->GetEntry());
12619 return;
12623 GossipMenuItemData pMenuData = gossipmenu.GetItemData(gossipListId);
12625 switch(gossipOptionId)
12627 case GOSSIP_OPTION_GOSSIP:
12629 if (pMenuData.m_gAction_poi)
12630 PlayerTalkClass->SendPointOfInterest(pMenuData.m_gAction_poi);
12632 if (pMenuData.m_gAction_menu)
12634 PrepareGossipMenu(pSource, pMenuData.m_gAction_menu);
12635 SendPreparedGossip(pSource);
12638 if (pMenuData.m_gAction_script)
12640 if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12641 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, this, pSource);
12642 else if (pSource->GetTypeId() == TYPEID_UNIT)
12643 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, pSource, this);
12646 break;
12648 case GOSSIP_OPTION_SPIRITHEALER:
12649 if (isDead())
12650 ((Creature*)pSource)->CastSpell(((Creature*)pSource),17251,true,NULL,NULL,GetGUID());
12651 break;
12652 case GOSSIP_OPTION_QUESTGIVER:
12653 PrepareQuestMenu(guid);
12654 SendPreparedQuest(guid);
12655 break;
12656 case GOSSIP_OPTION_VENDOR:
12657 case GOSSIP_OPTION_ARMORER:
12658 GetSession()->SendListInventory(guid);
12659 break;
12660 case GOSSIP_OPTION_STABLEPET:
12661 GetSession()->SendStablePet(guid);
12662 break;
12663 case GOSSIP_OPTION_TRAINER:
12664 GetSession()->SendTrainerList(guid);
12665 break;
12666 case GOSSIP_OPTION_UNLEARNTALENTS:
12667 PlayerTalkClass->CloseGossip();
12668 SendTalentWipeConfirm(guid);
12669 break;
12670 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12671 PlayerTalkClass->CloseGossip();
12672 SendPetSkillWipeConfirm();
12673 break;
12674 case GOSSIP_OPTION_TAXIVENDOR:
12675 GetSession()->SendTaxiMenu(((Creature*)pSource));
12676 break;
12677 case GOSSIP_OPTION_INNKEEPER:
12678 PlayerTalkClass->CloseGossip();
12679 SetBindPoint(guid);
12680 break;
12681 case GOSSIP_OPTION_BANKER:
12682 GetSession()->SendShowBank(guid);
12683 break;
12684 case GOSSIP_OPTION_PETITIONER:
12685 PlayerTalkClass->CloseGossip();
12686 GetSession()->SendPetitionShowList(guid);
12687 break;
12688 case GOSSIP_OPTION_TABARDDESIGNER:
12689 PlayerTalkClass->CloseGossip();
12690 GetSession()->SendTabardVendorActivate(guid);
12691 break;
12692 case GOSSIP_OPTION_AUCTIONEER:
12693 GetSession()->SendAuctionHello(guid, ((Creature*)pSource));
12694 break;
12695 case GOSSIP_OPTION_SPIRITGUIDE:
12696 PrepareGossipMenu(pSource);
12697 SendPreparedGossip(pSource);
12698 break;
12699 case GOSSIP_OPTION_BATTLEFIELD:
12701 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(pSource->GetEntry());
12703 if (bgTypeId == BATTLEGROUND_TYPE_NONE)
12705 sLog.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
12706 return;
12709 GetSession()->SendBattlegGroundList(guid, bgTypeId);
12710 break;
12715 uint32 Player::GetGossipTextId(WorldObject *pSource)
12717 if (!pSource || pSource->GetTypeId() != TYPEID_UNIT || !((Creature*)pSource)->GetDBTableGUIDLow())
12718 return DEFAULT_GOSSIP_MESSAGE;
12720 if (uint32 pos = sObjectMgr.GetNpcGossip(((Creature*)pSource)->GetDBTableGUIDLow()))
12721 return pos;
12723 return DEFAULT_GOSSIP_MESSAGE;
12726 uint32 Player::GetGossipTextId(uint32 menuId)
12728 uint32 textId = DEFAULT_GOSSIP_MESSAGE;
12730 if (!menuId)
12731 return textId;
12733 GossipMenusMapBounds pMenuBounds = sObjectMgr.GetGossipMenusMapBounds(menuId);
12735 for(GossipMenusMap::const_iterator itr = pMenuBounds.first; itr != pMenuBounds.second; ++itr)
12737 if (sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1) && sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12738 textId = itr->second.text_id;
12741 return textId;
12744 uint32 Player::GetDefaultGossipMenuForSource(WorldObject *pSource)
12746 if (pSource->GetTypeId() == TYPEID_UNIT)
12747 return ((Creature*)pSource)->GetCreatureInfo()->GossipMenuId;
12748 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12749 return((GameObject*)pSource)->GetGOInfo()->GetGossipMenuId();
12751 return 0;
12754 /*********************************************************/
12755 /*** QUEST SYSTEM ***/
12756 /*********************************************************/
12758 void Player::PrepareQuestMenu( uint64 guid )
12760 Object *pObject;
12761 QuestRelations* pObjectQR;
12762 QuestRelations* pObjectQIR;
12764 // pets also can have quests
12765 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12767 pObject = (Object*)pCreature;
12768 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
12769 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
12771 else
12773 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12774 //only for quests which cast teleport spells on player
12775 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
12776 ASSERT(_map);
12777 GameObject *pGameObject = _map->GetGameObject(guid);
12778 if( pGameObject )
12780 pObject = (Object*)pGameObject;
12781 pObjectQR = &sObjectMgr.mGOQuestRelations;
12782 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
12784 else
12785 return;
12788 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12789 qm.ClearMenu();
12791 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12793 uint32 quest_id = i->second;
12794 QuestStatus status = GetQuestStatus( quest_id );
12795 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12796 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12797 else if ( status == QUEST_STATUS_INCOMPLETE )
12798 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12799 else if (status == QUEST_STATUS_AVAILABLE )
12800 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12803 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12805 uint32 quest_id = i->second;
12806 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12807 if(!pQuest) continue;
12809 QuestStatus status = GetQuestStatus( quest_id );
12811 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12812 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12813 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12814 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12818 void Player::SendPreparedQuest(uint64 guid)
12820 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12822 if (questMenu.Empty())
12823 return;
12825 QuestMenuItem const& qmi0 = questMenu.GetItem(0);
12827 uint32 status = qmi0.m_qIcon;
12829 // single element case
12830 if (questMenu.MenuItemCount() == 1)
12832 // Auto open -- maybe also should verify there is no greeting
12833 uint32 quest_id = qmi0.m_qId;
12834 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12836 if (pQuest)
12838 if (status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus(quest_id))
12839 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12840 else if (status == DIALOG_STATUS_UNK2)
12841 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12842 // Send completable on repeatable and autoCompletable quest if player don't have quest
12843 // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
12844 else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDaily())
12845 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true);
12846 else
12847 PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true);
12850 // multiply entries
12851 else
12853 QEmote qe;
12854 qe._Delay = 0;
12855 qe._Emote = 0;
12856 std::string title = "";
12858 // need pet case for some quests
12859 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12861 uint32 textid = GetGossipTextId(pCreature);
12863 GossipText const* gossiptext = sObjectMgr.GetGossipText(textid);
12864 if (!gossiptext)
12866 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12867 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12868 title = "";
12870 else
12872 qe = gossiptext->Options[0].Emotes[0];
12874 if(!gossiptext->Options[0].Text_0.empty())
12876 title = gossiptext->Options[0].Text_0;
12878 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12879 if (loc_idx >= 0)
12881 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12882 if (nl)
12884 if ((int32)nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12885 title = nl->Text_0[0][loc_idx];
12889 else
12891 title = gossiptext->Options[0].Text_1;
12893 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12894 if (loc_idx >= 0)
12896 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12897 if (nl)
12899 if ((int32)nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12900 title = nl->Text_1[0][loc_idx];
12906 PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
12910 bool Player::IsActiveQuest( uint32 quest_id ) const
12912 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12914 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12917 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12919 Object *pObject;
12920 QuestRelations* pObjectQR;
12921 QuestRelations* pObjectQIR;
12923 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12925 pObject = (Object*)pCreature;
12926 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
12927 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
12929 else
12931 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12932 //only for quests which cast teleport spells on player
12933 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
12934 ASSERT(_map);
12935 GameObject *pGameObject = _map->GetGameObject(guid);
12936 if( pGameObject )
12938 pObject = (Object*)pGameObject;
12939 pObjectQR = &sObjectMgr.mGOQuestRelations;
12940 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
12942 else
12943 return NULL;
12946 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12947 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12949 if (itr->second == nextQuestID)
12950 return sObjectMgr.GetQuestTemplate(nextQuestID);
12953 return NULL;
12956 bool Player::CanSeeStartQuest( Quest const *pQuest )
12958 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12959 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12960 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12961 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12963 return getLevel() + sWorld.getConfig(CONFIG_UINT32_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12966 return false;
12969 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12971 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12972 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12973 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12974 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12975 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12976 && SatisfyQuestDay( pQuest, msg );
12979 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12981 if( !SatisfyQuestLog( msg ) )
12982 return false;
12984 uint32 srcitem = pQuest->GetSrcItemId();
12985 if( srcitem > 0 )
12987 uint32 count = pQuest->GetSrcItemCount();
12988 ItemPosCountVec dest;
12989 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12991 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12992 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12993 return true;
12994 else if( msg2 != EQUIP_ERR_OK )
12996 SendEquipError(msg2, NULL, NULL, srcitem);
12997 return false;
13000 return true;
13003 bool Player::CanCompleteQuest( uint32 quest_id )
13005 if( quest_id )
13007 QuestStatusData& q_status = mQuestStatus[quest_id];
13008 if( q_status.m_status == QUEST_STATUS_COMPLETE )
13009 return false; // not allow re-complete quest
13011 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13013 if(!qInfo)
13014 return false;
13016 // auto complete quest
13017 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
13018 return true;
13020 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13023 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13025 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13027 if( qInfo->ReqItemCount[i] != 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
13028 return false;
13032 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
13034 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13036 if( qInfo->ReqCreatureOrGOId[i] == 0 )
13037 continue;
13039 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
13040 return false;
13044 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
13045 return false;
13047 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
13048 return false;
13050 if ( qInfo->GetRewOrReqMoney() < 0 )
13052 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
13053 return false;
13056 uint32 repFacId = qInfo->GetRepObjectiveFaction();
13057 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
13058 return false;
13060 return true;
13063 return false;
13066 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
13068 // Solve problem that player don't have the quest and try complete it.
13069 // if repeatable she must be able to complete event if player don't have it.
13070 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
13071 if( !CanTakeQuest(pQuest, false) )
13072 return false;
13074 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
13075 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13076 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i], pQuest->ReqItemCount[i]) )
13077 return false;
13079 if( !CanRewardQuest(pQuest, false) )
13080 return false;
13082 return true;
13085 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
13087 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
13088 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
13089 return false;
13091 // daily quest can't be rewarded (25 daily quest already completed)
13092 if(!SatisfyQuestDay(pQuest,true))
13093 return false;
13095 // rewarded and not repeatable quest (only cheating case, then ignore without message)
13096 if(GetQuestRewardStatus(pQuest->GetQuestId()))
13097 return false;
13099 // prevent receive reward with quest items in bank
13100 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13102 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13104 if( pQuest->ReqItemCount[i] != 0 &&
13105 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
13107 if(msg)
13108 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL, pQuest->ReqItemId[i]);
13109 return false;
13114 // prevent receive reward with low money and GetRewOrReqMoney() < 0
13115 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
13116 return false;
13118 return true;
13121 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
13123 // prevent receive reward with quest items in bank or for not completed quest
13124 if(!CanRewardQuest(pQuest,msg))
13125 return false;
13127 if ( pQuest->GetRewChoiceItemsCount() > 0 )
13129 if( pQuest->RewChoiceItemId[reward] )
13131 ItemPosCountVec dest;
13132 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
13133 if( res != EQUIP_ERR_OK )
13135 SendEquipError( res, NULL, NULL, pQuest->RewChoiceItemId[reward] );
13136 return false;
13141 if ( pQuest->GetRewItemsCount() > 0 )
13143 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
13145 if( pQuest->RewItemId[i] )
13147 ItemPosCountVec dest;
13148 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
13149 if( res != EQUIP_ERR_OK )
13151 SendEquipError( res, NULL, NULL );
13152 return false;
13158 return true;
13161 void Player::SendPetTameFailure(PetTameFailureReason reason)
13163 WorldPacket data(SMSG_PET_TAME_FAILURE, 1);
13164 data << uint8(reason);
13165 GetSession()->SendPacket(&data);
13168 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
13170 uint16 log_slot = FindQuestSlot( 0 );
13171 assert(log_slot < MAX_QUEST_LOG_SIZE);
13173 uint32 quest_id = pQuest->GetQuestId();
13175 // if not exist then created with set uState==NEW and rewarded=false
13176 QuestStatusData& questStatusData = mQuestStatus[quest_id];
13178 // check for repeatable quests status reset
13179 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
13180 questStatusData.m_explored = false;
13182 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13184 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13185 questStatusData.m_itemcount[i] = 0;
13188 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
13190 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13191 questStatusData.m_creatureOrGOcount[i] = 0;
13194 GiveQuestSourceItem( pQuest );
13195 AdjustQuestReqItemCount( pQuest, questStatusData );
13197 if( pQuest->GetRepObjectiveFaction() )
13198 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
13199 GetReputationMgr().SetVisible(factionEntry);
13201 uint32 qtime = 0;
13202 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13204 uint32 limittime = pQuest->GetLimitTime();
13206 // shared timed quest
13207 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
13208 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
13210 AddTimedQuest( quest_id );
13211 questStatusData.m_timer = limittime * IN_MILISECONDS;
13212 qtime = static_cast<uint32>(time(NULL)) + limittime;
13214 else
13215 questStatusData.m_timer = 0;
13217 SetQuestSlot(log_slot, quest_id, qtime);
13219 if (questStatusData.uState != QUEST_NEW)
13220 questStatusData.uState = QUEST_CHANGED;
13222 //starting initial quest script
13223 if(questGiver && pQuest->GetQuestStartScript()!=0)
13224 GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
13226 // Some spells applied at quest activation
13227 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,true);
13228 if(saBounds.first != saBounds.second)
13230 uint32 zone, area;
13231 GetZoneAndAreaId(zone,area);
13233 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13234 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13235 if (!HasAura(itr->second->spellId, EFFECT_INDEX_0) )
13236 CastSpell(this,itr->second->spellId,true);
13239 UpdateForQuestWorldObjects();
13242 void Player::CompleteQuest( uint32 quest_id )
13244 if( quest_id )
13246 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
13248 uint16 log_slot = FindQuestSlot( quest_id );
13249 if( log_slot < MAX_QUEST_LOG_SIZE)
13250 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13252 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
13254 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
13255 RewardQuest(qInfo,0,this,false);
13256 else
13257 SendQuestComplete( quest_id );
13262 void Player::IncompleteQuest( uint32 quest_id )
13264 if( quest_id )
13266 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
13268 uint16 log_slot = FindQuestSlot( quest_id );
13269 if( log_slot < MAX_QUEST_LOG_SIZE)
13270 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13274 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
13276 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
13277 //should work fine, cause far teleport will be executed in Player::Update()
13278 SetCanDelayTeleport(true);
13280 uint32 quest_id = pQuest->GetQuestId();
13282 for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i )
13284 if (pQuest->ReqItemId[i])
13285 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
13288 RemoveTimedQuest(quest_id);
13290 if (BattleGround* bg = GetBattleGround())
13291 if (bg->GetTypeID() == BATTLEGROUND_AV)
13292 ((BattleGroundAV*)bg)->HandleQuestComplete(pQuest->GetQuestId(), this);
13294 if (pQuest->GetRewChoiceItemsCount() > 0)
13296 if (uint32 itemId = pQuest->RewChoiceItemId[reward])
13298 ItemPosCountVec dest;
13299 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK)
13301 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13302 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
13307 if (pQuest->GetRewItemsCount() > 0)
13309 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
13311 if (uint32 itemId = pQuest->RewItemId[i])
13313 ItemPosCountVec dest;
13314 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i] ) == EQUIP_ERR_OK)
13316 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13317 SendNewItem(item, pQuest->RewItemCount[i], true, false);
13323 RewardReputation( pQuest );
13325 uint16 log_slot = FindQuestSlot( quest_id );
13326 if (log_slot < MAX_QUEST_LOG_SIZE)
13327 SetQuestSlot(log_slot,0);
13329 QuestStatusData& q_status = mQuestStatus[quest_id];
13331 // Not give XP in case already completed once repeatable quest
13332 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_QUEST));
13334 if (getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
13335 GiveXP( XP , NULL );
13336 else
13338 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY));
13339 ModifyMoney( money );
13340 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
13343 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
13344 if (pQuest->GetRewOrReqMoney())
13346 ModifyMoney( pQuest->GetRewOrReqMoney() );
13348 if (pQuest->GetRewOrReqMoney() > 0)
13349 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
13352 // honor reward
13353 if (pQuest->GetRewHonorAddition())
13354 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorAddition()));
13356 // title reward
13357 if (pQuest->GetCharTitleId())
13359 if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
13360 SetTitle(titleEntry);
13363 if (pQuest->GetBonusTalents())
13365 m_questRewardTalentCount+=pQuest->GetBonusTalents();
13366 InitTalentForLevel();
13369 // Send reward mail
13370 if (uint32 mail_template_id = pQuest->GetRewMailTemplateId())
13371 MailDraft(mail_template_id).SendMailTo(this, questGiver, MAIL_CHECK_MASK_NONE, pQuest->GetRewMailDelaySecs());
13373 if (pQuest->IsDaily())
13375 SetDailyQuestStatus(quest_id);
13376 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
13379 if (!pQuest->IsRepeatable())
13380 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
13381 else
13382 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
13384 q_status.m_rewarded = true;
13385 if (q_status.uState != QUEST_NEW)
13386 q_status.uState = QUEST_CHANGED;
13388 if (announce)
13389 SendQuestReward( pQuest, XP, questGiver );
13391 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
13392 if (pQuest->GetRewSpellCast() > 0)
13393 CastSpell( this, pQuest->GetRewSpellCast(), true);
13394 else if ( pQuest->GetRewSpell() > 0)
13395 CastSpell( this, pQuest->GetRewSpell(), true);
13397 if (pQuest->GetZoneOrSort() > 0)
13398 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
13399 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
13400 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
13402 uint32 zone = 0;
13403 uint32 area = 0;
13405 // remove auras from spells with quest reward state limitations
13406 SpellAreaForQuestMapBounds saEndBounds = sSpellMgr.GetSpellAreaForQuestEndMapBounds(quest_id);
13407 if(saEndBounds.first != saEndBounds.second)
13409 GetZoneAndAreaId(zone,area);
13411 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
13412 if(!itr->second->IsFitToRequirements(this,zone,area))
13413 RemoveAurasDueToSpell(itr->second->spellId);
13416 // Some spells applied at quest reward
13417 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,false);
13418 if(saBounds.first != saBounds.second)
13420 if(!zone || !area)
13421 GetZoneAndAreaId(zone,area);
13423 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13424 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13425 if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
13426 CastSpell(this,itr->second->spellId,true);
13429 //lets remove flag for delayed teleports
13430 SetCanDelayTeleport(false);
13433 void Player::FailQuest(uint32 questId)
13435 if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(questId))
13437 SetQuestStatus(questId, QUEST_STATUS_FAILED);
13439 uint16 log_slot = FindQuestSlot(questId);
13441 if (log_slot < MAX_QUEST_LOG_SIZE)
13443 SetQuestSlotTimer(log_slot, 1);
13444 SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
13447 if (pQuest->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13449 QuestStatusData& q_status = mQuestStatus[questId];
13451 RemoveTimedQuest(questId);
13452 q_status.m_timer = 0;
13454 SendQuestTimerFailed(questId);
13456 else
13457 SendQuestFailed(questId);
13461 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
13463 int32 zoneOrSort = qInfo->GetZoneOrSort();
13464 int32 skillOrClass = qInfo->GetSkillOrClass();
13466 // skip zone zoneOrSort and 0 case skillOrClass
13467 if( zoneOrSort >= 0 && skillOrClass == 0 )
13468 return true;
13470 int32 questSort = -zoneOrSort;
13471 uint8 reqSortClass = ClassByQuestSort(questSort);
13473 // check class sort cases in zoneOrSort
13474 if( reqSortClass != 0 && getClass() != reqSortClass)
13476 if( msg )
13477 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13478 return false;
13481 // check class
13482 if( skillOrClass < 0 )
13484 uint8 reqClass = -int32(skillOrClass);
13485 if(getClass() != reqClass)
13487 if( msg )
13488 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13489 return false;
13492 // check skill
13493 else if( skillOrClass > 0 )
13495 uint32 reqSkill = skillOrClass;
13496 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
13498 if( msg )
13499 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13500 return false;
13504 return true;
13507 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
13509 if( getLevel() < qInfo->GetMinLevel() )
13511 if( msg )
13512 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13513 return false;
13515 return true;
13518 bool Player::SatisfyQuestLog( bool msg )
13520 // exist free slot
13521 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
13522 return true;
13524 if( msg )
13526 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
13527 GetSession()->SendPacket( &data );
13528 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
13530 return false;
13533 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
13535 // No previous quest (might be first quest in a series)
13536 if( qInfo->prevQuests.empty())
13537 return true;
13539 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
13541 uint32 prevId = abs(*iter);
13543 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13544 Quest const* qPrevInfo = sObjectMgr.GetQuestTemplate(prevId);
13546 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
13548 // If any of the positive previous quests completed, return true
13549 if( *iter > 0 && i_prevstatus->second.m_rewarded )
13551 // skip one-from-all exclusive group
13552 if(qPrevInfo->GetExclusiveGroup() >= 0)
13553 return true;
13555 // each-from-all exclusive group ( < 0)
13556 // can be start if only all quests in prev quest exclusive group completed and rewarded
13557 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13558 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13560 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13562 for(; iter2 != end; ++iter2)
13564 uint32 exclude_Id = iter2->second;
13566 // skip checked quest id, only state of other quests in group is interesting
13567 if(exclude_Id == prevId)
13568 continue;
13570 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13572 // alternative quest from group also must be completed and rewarded(reported)
13573 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
13575 if( msg )
13576 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13577 return false;
13580 return true;
13582 // If any of the negative previous quests active, return true
13583 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13584 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
13586 // skip one-from-all exclusive group
13587 if(qPrevInfo->GetExclusiveGroup() >= 0)
13588 return true;
13590 // each-from-all exclusive group ( < 0)
13591 // can be start if only all quests in prev quest exclusive group active
13592 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13593 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13595 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13597 for(; iter2 != end; ++iter2)
13599 uint32 exclude_Id = iter2->second;
13601 // skip checked quest id, only state of other quests in group is interesting
13602 if(exclude_Id == prevId)
13603 continue;
13605 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13607 // alternative quest from group also must be active
13608 if( i_exstatus == mQuestStatus.end() ||
13609 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
13610 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
13612 if( msg )
13613 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13614 return false;
13617 return true;
13622 // Has only positive prev. quests in non-rewarded state
13623 // and negative prev. quests in non-active state
13624 if( msg )
13625 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13627 return false;
13630 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
13632 uint32 reqraces = qInfo->GetRequiredRaces();
13633 if ( reqraces == 0 )
13634 return true;
13635 if( (reqraces & getRaceMask()) == 0 )
13637 if( msg )
13638 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13639 return false;
13641 return true;
13644 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13646 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13647 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13649 if( msg )
13650 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13651 return false;
13654 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13655 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13657 if( msg )
13658 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13659 return false;
13662 return true;
13665 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13667 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13668 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13670 if( msg )
13671 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13672 return false;
13674 return true;
13677 bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
13679 if (!m_timedquests.empty() && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13681 if (msg)
13682 SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
13684 return false;
13686 return true;
13689 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13691 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13692 if(qInfo->GetExclusiveGroup() <= 0)
13693 return true;
13695 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = sObjectMgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13696 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13698 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13700 for(; iter != end; ++iter)
13702 uint32 exclude_Id = iter->second;
13704 // skip checked quest id, only state of other quests in group is interesting
13705 if(exclude_Id == qInfo->GetQuestId())
13706 continue;
13708 // not allow have daily quest if daily quest from exclusive group already recently completed
13709 Quest const* Nquest = sObjectMgr.GetQuestTemplate(exclude_Id);
13710 if( !SatisfyQuestDay(Nquest, false) )
13712 if( msg )
13713 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13714 return false;
13717 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13719 // alternative quest already started or completed
13720 if( i_exstatus != mQuestStatus.end()
13721 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13723 if( msg )
13724 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13725 return false;
13728 return true;
13731 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13733 if(!qInfo->GetNextQuestInChain())
13734 return true;
13736 // next quest in chain already started or completed
13737 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13738 if( itr != mQuestStatus.end()
13739 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13741 if( msg )
13742 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13743 return false;
13746 // check for all quests further up the chain
13747 // only necessary if there are quest chains with more than one quest that can be skipped
13748 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13749 return true;
13752 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13754 // No previous quest in chain
13755 if( qInfo->prevChainQuests.empty())
13756 return true;
13758 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13760 uint32 prevId = *iter;
13762 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13764 if( i_prevstatus != mQuestStatus.end() )
13766 // If any of the previous quests in chain active, return false
13767 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13768 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13770 if( msg )
13771 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13772 return false;
13776 // check for all quests further down the chain
13777 // only necessary if there are quest chains with more than one quest that can be skipped
13778 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13779 // return false;
13782 // No previous quest in chain active
13783 return true;
13786 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13788 if(!qInfo->IsDaily())
13789 return true;
13791 bool have_slot = false;
13792 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13794 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13795 if(qInfo->GetQuestId()==id)
13796 return false;
13798 if(!id)
13799 have_slot = true;
13802 if(!have_slot)
13804 if( msg )
13805 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13806 return false;
13809 return true;
13812 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13814 uint32 srcitem = pQuest->GetSrcItemId();
13815 if( srcitem > 0 )
13817 uint32 count = pQuest->GetSrcItemCount();
13818 if( count <= 0 )
13819 count = 1;
13821 ItemPosCountVec dest;
13822 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13823 if( msg == EQUIP_ERR_OK )
13825 Item * item = StoreNewItem(dest, srcitem, true);
13826 SendNewItem(item, count, true, false);
13827 return true;
13829 // player already have max amount required item, just report success
13830 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13831 return true;
13832 else
13833 SendEquipError( msg, NULL, NULL, srcitem );
13834 return false;
13837 return true;
13840 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13842 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13843 if( qInfo )
13845 uint32 srcitem = qInfo->GetSrcItemId();
13846 if( srcitem > 0 )
13848 uint32 count = qInfo->GetSrcItemCount();
13849 if( count <= 0 )
13850 count = 1;
13852 // exist one case when destroy source quest item not possible:
13853 // non un-equippable item (equipped non-empty bag, for example)
13854 uint8 res = CanUnequipItems(srcitem,count);
13855 if(res != EQUIP_ERR_OK)
13857 if(msg)
13858 SendEquipError( res, NULL, NULL, srcitem );
13859 return false;
13862 DestroyItemCount(srcitem, count, true, true);
13865 return true;
13868 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13870 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13871 if( qInfo )
13873 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13874 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13875 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13876 && !qInfo->IsRepeatable() )
13877 return itr->second.m_rewarded;
13879 return false;
13881 return false;
13884 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13886 if( quest_id )
13888 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13889 if( itr != mQuestStatus.end() )
13890 return itr->second.m_status;
13892 return QUEST_STATUS_NONE;
13895 bool Player::CanShareQuest(uint32 quest_id) const
13897 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13898 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13900 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13901 if( itr != mQuestStatus.end() )
13902 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13904 return false;
13907 void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
13909 if (sObjectMgr.GetQuestTemplate(quest_id))
13911 QuestStatusData& q_status = mQuestStatus[quest_id];
13913 q_status.m_status = status;
13915 if (q_status.uState != QUEST_NEW)
13916 q_status.uState = QUEST_CHANGED;
13919 UpdateForQuestWorldObjects();
13922 // not used in MaNGOS, but used in scripting code
13923 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13925 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13926 if( !qInfo )
13927 return 0;
13929 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13930 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13931 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13933 return 0;
13936 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13938 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13940 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13942 uint32 reqitemcount = pQuest->ReqItemCount[i];
13943 if( reqitemcount != 0 )
13945 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i], true);
13947 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13948 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13954 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13956 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13957 if ( GetQuestSlotQuestId(i) == quest_id )
13958 return i;
13960 return MAX_QUEST_LOG_SIZE;
13963 void Player::AreaExploredOrEventHappens( uint32 questId )
13965 if( questId )
13967 uint16 log_slot = FindQuestSlot( questId );
13968 if( log_slot < MAX_QUEST_LOG_SIZE)
13970 QuestStatusData& q_status = mQuestStatus[questId];
13972 if(!q_status.m_explored)
13974 q_status.m_explored = true;
13975 if (q_status.uState != QUEST_NEW)
13976 q_status.uState = QUEST_CHANGED;
13979 if( CanCompleteQuest( questId ) )
13980 CompleteQuest( questId );
13984 //not used in mangosd, function for external script library
13985 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13987 if( Group *pGroup = GetGroup() )
13989 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13991 Player *pGroupGuy = itr->getSource();
13993 // for any leave or dead (with not released body) group member at appropriate distance
13994 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13995 pGroupGuy->AreaExploredOrEventHappens(questId);
13998 else
13999 AreaExploredOrEventHappens(questId);
14002 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
14004 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14006 uint32 questid = GetQuestSlotQuestId(i);
14007 if ( questid == 0 )
14008 continue;
14010 QuestStatusData& q_status = mQuestStatus[questid];
14012 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
14013 continue;
14015 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14016 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
14017 continue;
14019 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
14021 uint32 reqitem = qInfo->ReqItemId[j];
14022 if ( reqitem == entry )
14024 uint32 reqitemcount = qInfo->ReqItemCount[j];
14025 uint32 curitemcount = q_status.m_itemcount[j];
14026 if ( curitemcount < reqitemcount )
14028 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
14029 q_status.m_itemcount[j] += additemcount;
14030 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14032 SendQuestUpdateAddItem( qInfo, j, additemcount );
14034 if ( CanCompleteQuest( questid ) )
14035 CompleteQuest( questid );
14036 return;
14040 UpdateForQuestWorldObjects();
14043 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
14045 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14047 uint32 questid = GetQuestSlotQuestId(i);
14048 if(!questid)
14049 continue;
14050 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14051 if ( !qInfo )
14052 continue;
14053 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
14054 continue;
14056 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
14058 uint32 reqitem = qInfo->ReqItemId[j];
14059 if ( reqitem == entry )
14061 QuestStatusData& q_status = mQuestStatus[questid];
14063 uint32 reqitemcount = qInfo->ReqItemCount[j];
14064 uint32 curitemcount;
14065 if( q_status.m_status != QUEST_STATUS_COMPLETE )
14066 curitemcount = q_status.m_itemcount[j];
14067 else
14068 curitemcount = GetItemCount(entry, true);
14069 if ( curitemcount < reqitemcount + count )
14071 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
14072 q_status.m_itemcount[j] = curitemcount - remitemcount;
14073 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14075 IncompleteQuest( questid );
14077 return;
14081 UpdateForQuestWorldObjects();
14084 void Player::KilledMonster( CreatureInfo const* cInfo, uint64 guid )
14086 if(cInfo->Entry)
14087 KilledMonsterCredit(cInfo->Entry,guid);
14089 for(int i = 0; i < MAX_KILL_CREDIT; ++i)
14090 if(cInfo->KillCredit[i])
14091 KilledMonsterCredit(cInfo->KillCredit[i],guid);
14094 void Player::KilledMonsterCredit( uint32 entry, uint64 guid )
14096 uint32 addkillcount = 1;
14097 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
14098 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14100 uint32 questid = GetQuestSlotQuestId(i);
14101 if(!questid)
14102 continue;
14104 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14105 if( !qInfo )
14106 continue;
14107 // just if !ingroup || !noraidgroup || raidgroup
14108 QuestStatusData& q_status = mQuestStatus[questid];
14109 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
14111 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
14113 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14115 // skip GO activate objective or none
14116 if(qInfo->ReqCreatureOrGOId[j] <=0)
14117 continue;
14119 // skip Cast at creature objective
14120 if(qInfo->ReqSpell[j] !=0 )
14121 continue;
14123 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
14125 if ( reqkill == entry )
14127 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
14128 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
14129 if ( curkillcount < reqkillcount )
14131 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
14132 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14134 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
14136 if ( CanCompleteQuest( questid ) )
14137 CompleteQuest( questid );
14139 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14140 continue;
14148 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
14150 bool isCreature = IS_CREATURE_GUID(guid);
14152 uint32 addCastCount = 1;
14153 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
14155 uint32 questid = GetQuestSlotQuestId(i);
14156 if(!questid)
14157 continue;
14159 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14160 if ( !qInfo )
14161 continue;
14163 QuestStatusData& q_status = mQuestStatus[questid];
14165 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14167 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
14169 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14171 // skip kill creature objective (0) or wrong spell casts
14172 if(qInfo->ReqSpell[j] != spell_id )
14173 continue;
14175 uint32 reqTarget = 0;
14177 if(isCreature)
14179 // creature activate objectives
14180 if(qInfo->ReqCreatureOrGOId[j] > 0)
14181 // checked at quest_template loading
14182 reqTarget = qInfo->ReqCreatureOrGOId[j];
14184 else
14186 // GO activate objective
14187 if(qInfo->ReqCreatureOrGOId[j] < 0)
14188 // checked at quest_template loading
14189 reqTarget = - qInfo->ReqCreatureOrGOId[j];
14192 // other not this creature/GO related objectives
14193 if( reqTarget != entry )
14194 continue;
14196 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
14197 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
14198 if ( curCastCount < reqCastCount )
14200 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
14201 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14203 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
14206 if ( CanCompleteQuest( questid ) )
14207 CompleteQuest( questid );
14209 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14210 break;
14217 void Player::TalkedToCreature( uint32 entry, uint64 guid )
14219 uint32 addTalkCount = 1;
14220 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14222 uint32 questid = GetQuestSlotQuestId(i);
14223 if(!questid)
14224 continue;
14226 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14227 if ( !qInfo )
14228 continue;
14230 QuestStatusData& q_status = mQuestStatus[questid];
14232 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14234 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
14236 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14238 // skip spell casts and Gameobject objectives
14239 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
14240 continue;
14242 uint32 reqTarget = 0;
14244 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
14245 // checked at quest_template loading
14246 reqTarget = qInfo->ReqCreatureOrGOId[j];
14247 else
14248 continue;
14250 if ( reqTarget == entry )
14252 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
14253 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
14254 if ( curTalkCount < reqTalkCount )
14256 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
14257 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14259 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
14261 if ( CanCompleteQuest( questid ) )
14262 CompleteQuest( questid );
14264 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14265 continue;
14273 void Player::MoneyChanged( uint32 count )
14275 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14277 uint32 questid = GetQuestSlotQuestId(i);
14278 if (!questid)
14279 continue;
14281 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14282 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
14284 QuestStatusData& q_status = mQuestStatus[questid];
14286 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14288 if(int32(count) >= -qInfo->GetRewOrReqMoney())
14290 if ( CanCompleteQuest( questid ) )
14291 CompleteQuest( questid );
14294 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14296 if(int32(count) < -qInfo->GetRewOrReqMoney())
14297 IncompleteQuest( questid );
14303 void Player::ReputationChanged(FactionEntry const* factionEntry )
14305 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14307 if(uint32 questid = GetQuestSlotQuestId(i))
14309 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid))
14311 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
14313 QuestStatusData& q_status = mQuestStatus[questid];
14314 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14316 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
14317 if ( CanCompleteQuest( questid ) )
14318 CompleteQuest( questid );
14320 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14322 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
14323 IncompleteQuest( questid );
14331 bool Player::HasQuestForItem( uint32 itemid ) const
14333 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14335 uint32 questid = GetQuestSlotQuestId(i);
14336 if ( questid == 0 )
14337 continue;
14339 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
14340 if(qs_itr == mQuestStatus.end())
14341 continue;
14343 QuestStatusData const& q_status = qs_itr->second;
14345 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
14347 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
14348 if(!qinfo)
14349 continue;
14351 // hide quest if player is in raid-group and quest is no raid quest
14352 if (GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID
14353 && !InBattleGround())
14354 continue;
14356 // There should be no mixed ReqItem/ReqSource drop
14357 // This part for ReqItem drop
14358 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
14360 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
14361 return true;
14363 // This part - for ReqSource
14364 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
14366 // examined item is a source item
14367 if (qinfo->ReqSourceId[j] == itemid)
14369 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(itemid);
14371 // 'unique' item
14372 if (pProto->MaxCount && (int32)GetItemCount(itemid,true) < pProto->MaxCount)
14373 return true;
14375 // allows custom amount drop when not 0
14376 if (qinfo->ReqSourceCount[j])
14378 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
14379 return true;
14380 } else if ((int32)GetItemCount(itemid,true) < pProto->Stackable)
14381 return true;
14386 return false;
14389 void Player::SendQuestComplete( uint32 quest_id )
14391 if( quest_id )
14393 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
14394 data << uint32(quest_id);
14395 GetSession()->SendPacket( &data );
14396 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
14400 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
14402 uint32 questid = pQuest->GetQuestId();
14403 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
14404 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
14405 data << uint32(questid);
14407 if ( getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
14409 data << uint32(XP);
14410 data << uint32(pQuest->GetRewOrReqMoney());
14412 else
14414 data << uint32(0);
14415 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY)));
14418 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorAddition()));
14419 data << uint32(pQuest->GetBonusTalents()); // bonus talents
14420 data << uint32(0);
14421 GetSession()->SendPacket( &data );
14423 if (pQuest->GetQuestCompleteScript() != 0)
14424 GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
14427 void Player::SendQuestFailed( uint32 quest_id )
14429 if( quest_id )
14431 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
14432 data << uint32(quest_id);
14433 data << uint32(0); // failed reason (4 for inventory is full)
14434 GetSession()->SendPacket( &data );
14435 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
14439 void Player::SendQuestTimerFailed( uint32 quest_id )
14441 if( quest_id )
14443 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
14444 data << uint32(quest_id);
14445 GetSession()->SendPacket( &data );
14446 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
14450 void Player::SendCanTakeQuestResponse( uint32 msg )
14452 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
14453 data << uint32(msg);
14454 GetSession()->SendPacket( &data );
14455 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
14458 void Player::SendQuestConfirmAccept(const Quest* pQuest, Player* pReceiver)
14460 if (pReceiver)
14462 std::string strTitle = pQuest->GetTitle();
14464 int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
14466 if (loc_idx >= 0)
14468 if (const QuestLocale* pLocale = sObjectMgr.GetQuestLocale(pQuest->GetQuestId()))
14470 if ((int32)pLocale->Title.size() > loc_idx && !pLocale->Title[loc_idx].empty())
14471 strTitle = pLocale->Title[loc_idx];
14475 WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8));
14476 data << uint32(pQuest->GetQuestId());
14477 data << strTitle;
14478 data << uint64(GetGUID());
14479 pReceiver->GetSession()->SendPacket(&data);
14481 sLog.outDebug("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
14485 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
14487 if( pPlayer )
14489 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
14490 data << uint64(pPlayer->GetGUID());
14491 data << uint8(msg); // valid values: 0-8
14492 GetSession()->SendPacket( &data );
14493 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
14497 void Player::SendQuestUpdateAddItem( Quest const* /*pQuest*/, uint32 /*item_idx*/, uint32 /*count*/ )
14499 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
14500 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
14501 //data << pQuest->ReqItemId[item_idx];
14502 //data << count;
14503 GetSession()->SendPacket( &data );
14506 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
14508 assert(old_count + add_count < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
14510 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
14511 if (entry < 0)
14512 // client expected gameobject template id in form (id|0x80000000)
14513 entry = (-entry) | 0x80000000;
14515 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
14516 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
14517 data << uint32(pQuest->GetQuestId());
14518 data << uint32(entry);
14519 data << uint32(old_count + add_count);
14520 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
14521 data << uint64(guid);
14522 GetSession()->SendPacket(&data);
14524 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
14525 if( log_slot < MAX_QUEST_LOG_SIZE)
14526 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
14529 /*********************************************************/
14530 /*** LOAD SYSTEM ***/
14531 /*********************************************************/
14533 void Player::_LoadDeclinedNames(QueryResult* result)
14535 if(!result)
14536 return;
14538 if(m_declinedname)
14539 delete m_declinedname;
14541 m_declinedname = new DeclinedName;
14542 Field *fields = result->Fetch();
14543 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
14544 m_declinedname->name[i] = fields[i].GetCppString();
14546 delete result;
14549 void Player::_LoadArenaTeamInfo(QueryResult *result)
14551 // arenateamid, played_week, played_season, personal_rating
14552 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
14553 if (!result)
14554 return;
14558 Field *fields = result->Fetch();
14560 uint32 arenateamid = fields[0].GetUInt32();
14561 uint32 played_week = fields[1].GetUInt32();
14562 uint32 played_season = fields[2].GetUInt32();
14563 uint32 wons_season = fields[3].GetUInt32();
14564 uint32 personal_rating = fields[4].GetUInt32();
14566 ArenaTeam* aTeam = sObjectMgr.GetArenaTeamById(arenateamid);
14567 if(!aTeam)
14569 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid);
14570 continue;
14572 uint8 arenaSlot = aTeam->GetSlot();
14574 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_ID, arenateamid);
14575 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_TYPE, aTeam->GetType());
14576 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_MEMBER, (aTeam->GetCaptain() == GetGUID()) ? 0 : 1);
14577 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_WEEK, played_week);
14578 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_SEASON, played_season);
14579 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_WINS_SEASON, wons_season);
14580 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_PERSONAL_RATING, personal_rating);
14582 } while (result->NextRow());
14583 delete result;
14586 void Player::_LoadEquipmentSets(QueryResult *result)
14588 // 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));
14589 if (!result)
14590 return;
14592 uint32 count = 0;
14595 Field *fields = result->Fetch();
14597 EquipmentSet eqSet;
14599 eqSet.Guid = fields[0].GetUInt64();
14600 uint32 index = fields[1].GetUInt32();
14601 eqSet.Name = fields[2].GetCppString();
14602 eqSet.IconName = fields[3].GetCppString();
14603 eqSet.state = EQUIPMENT_SET_UNCHANGED;
14605 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
14606 eqSet.Items[i] = fields[4+i].GetUInt32();
14608 m_EquipmentSets[index] = eqSet;
14610 ++count;
14612 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
14613 break;
14614 } while (result->NextRow());
14615 delete result;
14618 void Player::_LoadBGData(QueryResult* result)
14620 if (!result)
14621 return;
14623 // Expecting only one row
14624 Field *fields = result->Fetch();
14625 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
14626 m_bgData.bgInstanceID = fields[0].GetUInt32();
14627 m_bgData.bgTeam = fields[1].GetUInt32();
14628 m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
14629 fields[2].GetFloat(), // X
14630 fields[3].GetFloat(), // Y
14631 fields[4].GetFloat(), // Z
14632 fields[5].GetFloat()); // Orientation
14633 m_bgData.taxiPath[0] = fields[7].GetUInt32();
14634 m_bgData.taxiPath[1] = fields[8].GetUInt32();
14635 m_bgData.mountSpell = fields[9].GetUInt32();
14637 delete result;
14640 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
14642 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
14643 if(!result)
14644 return false;
14646 Field *fields = result->Fetch();
14648 x = fields[0].GetFloat();
14649 y = fields[1].GetFloat();
14650 z = fields[2].GetFloat();
14651 o = fields[3].GetFloat();
14652 mapid = fields[4].GetUInt32();
14653 in_flight = !fields[5].GetCppString().empty();
14655 delete result;
14656 return true;
14659 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
14661 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
14662 if( !result )
14663 return false;
14665 Field *fields = result->Fetch();
14667 data = StrSplit(fields[0].GetCppString(), " ");
14669 delete result;
14671 return true;
14674 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
14676 if(index >= data.size())
14677 return 0;
14679 return (uint32)atoi(data[index].c_str());
14682 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
14684 float result;
14685 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
14686 memcpy(&result, &temp, sizeof(result));
14688 return result;
14691 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14693 Tokens data;
14694 if(!LoadValuesArrayFromDB(data,guid))
14695 return 0;
14697 return GetUInt32ValueFromArray(data,index);
14700 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14702 float result;
14703 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14704 memcpy(&result, &temp, sizeof(result));
14706 return result;
14709 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14711 // 0 1 2 3 4 5 6 7 8 9 10 11 12
14712 //SELECT guid, account, data, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags,"
14713 // 13 14 15 16 17 18 19 20 21 22 23 24 25
14714 //"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost,"
14715 // 26 27 28 29 30 31 32 33 34 35 36 37 38 39
14716 //"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,"
14717 // 40 41 42 43 44 45 46 47 48 49 50
14718 //"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk,"
14719 // 51 52 53 54 55 56 57 58 59 60
14720 //"health, power1, power2, power3, power4, power5, power6, power7, specCount, activeSpec FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid));
14721 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14723 if(!result)
14725 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14726 return false;
14729 Field *fields = result->Fetch();
14731 uint32 dbAccountId = fields[1].GetUInt32();
14733 // check if the character's account in the db and the logged in account match.
14734 // player should be able to load/delete character only with correct account!
14735 if( dbAccountId != GetSession()->GetAccountId() )
14737 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14738 delete result;
14739 return false;
14742 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14744 m_name = fields[3].GetCppString();
14746 // check name limitations
14747 if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
14748 (GetSession()->GetSecurity() == SEC_PLAYER && sObjectMgr.IsReservedName(m_name)))
14750 delete result;
14751 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14752 return false;
14755 if(!LoadValues( fields[2].GetString()))
14757 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
14758 delete result;
14759 return false;
14762 // overwrite possible wrong/corrupted guid
14763 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14765 // overwrite some data fields
14766 uint32 bytes0 = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0xFF000000;
14767 bytes0 |= fields[4].GetUInt8(); // race
14768 bytes0 |= fields[5].GetUInt8() << 8; // class
14769 bytes0 |= fields[6].GetUInt8() << 16; // gender
14770 SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
14772 SetUInt32Value(UNIT_FIELD_LEVEL, fields[7].GetUInt8());
14773 SetUInt32Value(PLAYER_XP, fields[8].GetUInt32());
14775 uint32 money = fields[9].GetUInt32();
14776 if(money > MAX_MONEY_AMOUNT)
14777 money = MAX_MONEY_AMOUNT;
14778 SetMoney(money);
14780 SetUInt32Value(PLAYER_BYTES, fields[10].GetUInt32());
14781 SetUInt32Value(PLAYER_BYTES_2, fields[11].GetUInt32());
14782 SetUInt32Value(PLAYER_BYTES_3, (fields[50].GetUInt16() & 0xFFFE) | fields[6].GetUInt8());
14783 SetUInt32Value(PLAYER_FLAGS, fields[12].GetUInt32());
14784 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[49].GetInt32());
14786 SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES, fields[48].GetUInt64());
14789 InitDisplayIds();
14791 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14792 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14794 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
14795 SetVisibleItemSlot(slot, NULL);
14797 if (m_items[slot])
14799 delete m_items[slot];
14800 m_items[slot] = NULL;
14804 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14805 outDebugValues();
14807 //Need to call it to initialize m_team (m_team can be calculated from race)
14808 //Other way is to saves m_team into characters table.
14809 setFactionForRace(getRace());
14810 SetCharm(NULL);
14812 // load home bind and check in same time class/race pair, it used later for restore broken positions
14813 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14815 delete result;
14816 return false;
14819 InitPrimaryProfessions(); // to max set before any spell loaded
14821 // init saved position, and fix it later if problematic
14822 uint32 transGUID = fields[31].GetUInt32();
14823 Relocate(fields[13].GetFloat(),fields[14].GetFloat(),fields[15].GetFloat(),fields[17].GetFloat());
14824 SetLocationMapId(fields[16].GetUInt32());
14826 uint32 difficulty = fields[39].GetUInt32();
14827 if(difficulty >= MAX_DUNGEON_DIFFICULTY)
14828 difficulty = DUNGEON_DIFFICULTY_NORMAL;
14829 SetDungeonDifficulty(Difficulty(difficulty)); // may be changed in _LoadGroup
14831 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14833 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14835 uint32 arena_currency = fields[40].GetUInt32();
14836 if (arena_currency > sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS))
14837 arena_currency = sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS);
14839 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14841 // check arena teams integrity
14842 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14844 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14845 if(!arena_team_id)
14846 continue;
14848 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(arena_team_id))
14849 if(at->HaveMember(GetGUID()))
14850 continue;
14852 // arena team not exist or not member, cleanup fields
14853 for(int j = 0; j < ARENA_TEAM_END; ++j)
14854 SetArenaTeamInfoField(arena_slot, ArenaTeamInfoType(j), 0);
14857 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, fields[41].GetUInt32());
14858 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, fields[42].GetUInt32());
14859 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, fields[43].GetUInt32());
14860 SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, fields[44].GetUInt32());
14861 SetUInt16Value(PLAYER_FIELD_KILLS, 0, fields[45].GetUInt16());
14862 SetUInt16Value(PLAYER_FIELD_KILLS, 1, fields[46].GetUInt16());
14864 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14866 if(!IsPositionValid())
14868 sLog.outError("Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
14869 RelocateToHomebind();
14871 transGUID = 0;
14873 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
14876 _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
14878 if(m_bgData.bgInstanceID) //saved in BattleGround
14880 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
14882 bool player_at_bg = currentBg && currentBg->IsPlayerInBattleGround(GetGUID());
14884 if(player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE)
14886 BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14887 AddBattleGroundQueueId(bgQueueTypeId);
14889 m_bgData.bgTypeID = currentBg->GetTypeID();
14891 //join player to battleground group
14892 currentBg->EventPlayerLoggedIn(this, GetGUID());
14893 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData.bgTeam);
14895 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14897 else
14899 // leave bg
14900 if (player_at_bg)
14901 currentBg->RemovePlayerAtLeave(GetGUID(), false, true);
14903 // move to bg enter point
14904 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14905 SetLocationMapId(_loc.mapid);
14906 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14908 // We are not in BG anymore
14909 m_bgData.bgInstanceID = 0;
14912 else
14914 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14915 // if server restart after player save in BG or area
14916 // player can have current coordinates in to BG/Arena map, fix this
14917 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14919 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14920 SetLocationMapId(_loc.mapid);
14921 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14925 if (transGUID != 0)
14927 m_movementInfo.SetTransportData(transGUID, fields[27].GetFloat(), fields[28].GetFloat(), fields[29].GetFloat(), fields[30].GetFloat(), 0, -1);
14929 if( !MaNGOS::IsValidMapCoord(
14930 GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
14931 GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o) ||
14932 // transport size limited
14933 m_movementInfo.GetTransportPos()->x > 50 || m_movementInfo.GetTransportPos()->y > 50 || m_movementInfo.GetTransportPos()->z > 50 )
14935 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14936 guid, GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
14937 GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o);
14939 RelocateToHomebind();
14941 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
14943 transGUID = 0;
14947 if (transGUID != 0)
14949 for (MapManager::TransportSet::const_iterator iter = sMapMgr.m_Transports.begin(); iter != sMapMgr.m_Transports.end(); ++iter)
14951 if( (*iter)->GetGUIDLow() == transGUID)
14953 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14954 // client without expansion support
14955 if(GetSession()->Expansion() < transMapEntry->Expansion())
14957 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14958 break;
14961 m_transport = *iter;
14962 m_transport->AddPassenger(this);
14963 SetLocationMapId(m_transport->GetMapId());
14964 break;
14968 if(!m_transport)
14970 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14971 guid,transGUID);
14973 RelocateToHomebind();
14975 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
14977 transGUID = 0;
14980 else // not transport case
14982 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14983 // client without expansion support
14984 if(GetSession()->Expansion() < mapEntry->Expansion())
14986 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14987 RelocateToHomebind();
14991 // NOW player must have valid map
14992 // load the player's map here if it's not already loaded
14993 SetMap(sMapMgr.CreateMap(GetMapId(), this));
14995 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14996 if(GetInstanceId() && !sInstanceSaveMgr.GetInstanceSave(GetInstanceId()))
14998 AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(GetMapId());
14999 if(at)
15000 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
15001 else
15002 sLog.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
15005 SaveRecallPosition();
15007 time_t now = time(NULL);
15008 time_t logoutTime = time_t(fields[23].GetUInt64());
15010 // since last logout (in seconds)
15011 uint32 time_diff = uint32(now - logoutTime);
15013 // set value, including drunk invisibility detection
15014 // calculate sobering. after 15 minutes logged out, the player will be sober again
15015 float soberFactor;
15016 if(time_diff > 15*MINUTE)
15017 soberFactor = 0;
15018 else
15019 soberFactor = 1-time_diff/(15.0f*MINUTE);
15020 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
15021 SetDrunkValue(newDrunkenValue);
15023 m_rest_bonus = fields[22].GetFloat();
15024 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
15025 float bubble0 = 0.031f;
15026 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
15027 float bubble1 = 0.125f;
15029 if(time_diff > 0)
15031 float bubble = fields[24].GetUInt32() > 0
15032 ? bubble1*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
15033 : bubble0*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_WILDERNESS);
15035 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
15038 m_cinematic = fields[19].GetUInt32();
15039 m_Played_time[PLAYED_TIME_TOTAL]= fields[20].GetUInt32();
15040 m_Played_time[PLAYED_TIME_LEVEL]= fields[21].GetUInt32();
15042 m_resetTalentsCost = fields[25].GetUInt32();
15043 m_resetTalentsTime = time_t(fields[26].GetUInt64());
15045 // reserve some flags
15046 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
15048 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
15049 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
15051 m_taxi.LoadTaxiMask( fields[18].GetString() ); // must be before InitTaxiNodesForLevel
15053 uint32 extraflags = fields[32].GetUInt32();
15055 m_stableSlots = fields[33].GetUInt32();
15056 if(m_stableSlots > MAX_PET_STABLES)
15058 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
15059 m_stableSlots = MAX_PET_STABLES;
15062 m_atLoginFlags = fields[34].GetUInt32();
15064 // Honor system
15065 // Update Honor kills data
15066 m_lastHonorUpdateTime = logoutTime;
15067 UpdateHonorFields();
15069 m_deathExpireTime = (time_t)fields[37].GetUInt64();
15070 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
15071 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
15073 std::string taxi_nodes = fields[38].GetCppString();
15075 // clear channel spell data (if saved at channel spell casting)
15076 SetChannelObjectGUID(0);
15077 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
15079 // clear charm/summon related fields
15080 SetCharm(NULL);
15081 SetPet(NULL);
15082 SetTargetGUID(0);
15083 SetChannelObjectGUID(0);
15084 SetCharmerGUID(0);
15085 SetOwnerGUID(0);
15086 SetCreatorGUID(0);
15088 // reset some aura modifiers before aura apply
15089 SetFarSightGUID(0);
15090 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
15091 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
15093 // cleanup aura list explicitly before skill load wher some spells can be applied
15094 RemoveAllAuras();
15096 // make sure the unit is considered out of combat for proper loading
15097 ClearInCombat();
15099 // make sure the unit is considered not in duel for proper loading
15100 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
15101 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
15103 // reset stats before loading any modifiers
15104 InitStatsForLevel();
15105 InitGlyphsForLevel();
15106 InitTaxiNodesForLevel();
15107 InitRunes();
15109 // load skills after InitStatsForLevel because it triggering aura apply also
15110 _LoadSkills(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS));
15112 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
15114 // Mail
15115 _LoadMail();
15116 UpdateNextMailTimeAndUnreads();
15118 m_specsCount = fields[59].GetUInt8();
15119 m_activeSpec = fields[60].GetUInt8();
15121 _LoadGlyphs(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGLYPHS));
15123 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
15124 ApplyGlyphs(true);
15126 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
15127 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
15128 m_deathState = DEAD;
15130 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
15132 // after spell load, learn rewarded spell if need also
15133 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
15134 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
15136 // after spell and quest load
15137 InitTalentForLevel();
15138 learnDefaultSpells();
15140 // must be before inventory (some items required reputation check)
15141 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
15143 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
15145 // update items with duration and realtime
15146 UpdateItemDuration(time_diff, true);
15148 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
15150 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
15152 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
15153 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
15154 uint32 curTitle = fields[47].GetUInt32();
15155 if (curTitle && !HasTitle(curTitle))
15156 curTitle = 0;
15158 SetUInt32Value(PLAYER_CHOSEN_TITLE, curTitle);
15160 // Not finish taxi flight path
15161 if(m_bgData.HasTaxiPath())
15163 m_taxi.ClearTaxiDestinations();
15164 for (int i = 0; i < 2; ++i)
15165 m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
15167 else if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
15169 // problems with taxi path loading
15170 TaxiNodesEntry const* nodeEntry = NULL;
15171 if(uint32 node_id = m_taxi.GetTaxiSource())
15172 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
15174 if(!nodeEntry) // don't know taxi start node, to homebind
15176 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
15177 RelocateToHomebind();
15179 else // have start node, to it
15181 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
15182 SetLocationMapId(nodeEntry->map_id);
15183 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
15186 //we can be relocated from taxi and still have an outdated Map pointer!
15187 //so we need to get a new Map pointer!
15188 SetMap(sMapMgr.CreateMap(GetMapId(), this));
15189 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
15191 m_taxi.ClearTaxiDestinations();
15194 if(uint32 node_id = m_taxi.GetTaxiSource())
15196 // save source node as recall coord to prevent recall and fall from sky
15197 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
15198 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
15199 m_recallMap = nodeEntry->map_id;
15200 m_recallX = nodeEntry->x;
15201 m_recallY = nodeEntry->y;
15202 m_recallZ = nodeEntry->z;
15204 // flight will started later
15207 // has to be called after last Relocate() in Player::LoadFromDB
15208 SetFallInformation(0, GetPositionZ());
15210 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
15212 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
15213 // Do now before stats re-calculation cleanup for ghost state unexpected auras
15214 if(!isAlive())
15215 RemoveAllAurasOnDeath();
15217 //apply all stat bonuses from items and auras
15218 SetCanModifyStats(true);
15219 UpdateAllStats();
15221 // restore remembered power/health values (but not more max values)
15222 uint32 savedhealth = fields[51].GetUInt32();
15223 SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth);
15224 for(uint32 i = 0; i < MAX_POWERS; ++i)
15226 uint32 savedpower = fields[52+i].GetUInt32();
15227 SetPower(Powers(i),savedpower > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedpower);
15230 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
15231 outDebugValues();
15233 // all fields read
15234 delete result;
15236 // GM state
15237 if(GetSession()->GetSecurity() > SEC_PLAYER)
15239 switch(sWorld.getConfig(CONFIG_UINT32_GM_LOGIN_STATE))
15241 default:
15242 case 0: break; // disable
15243 case 1: SetGameMaster(true); break; // enable
15244 case 2: // save state
15245 if(extraflags & PLAYER_EXTRA_GM_ON)
15246 SetGameMaster(true);
15247 break;
15250 switch(sWorld.getConfig(CONFIG_UINT32_GM_VISIBLE_STATE))
15252 default:
15253 case 0: SetGMVisible(false); break; // invisible
15254 case 1: break; // visible
15255 case 2: // save state
15256 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
15257 SetGMVisible(false);
15258 break;
15261 switch(sWorld.getConfig(CONFIG_UINT32_GM_ACCEPT_TICKETS))
15263 default:
15264 case 0: break; // disable
15265 case 1: SetAcceptTicket(true); break; // enable
15266 case 2: // save state
15267 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
15268 SetAcceptTicket(true);
15269 break;
15272 switch(sWorld.getConfig(CONFIG_UINT32_GM_CHAT))
15274 default:
15275 case 0: break; // disable
15276 case 1: SetGMChat(true); break; // enable
15277 case 2: // save state
15278 if(extraflags & PLAYER_EXTRA_GM_CHAT)
15279 SetGMChat(true);
15280 break;
15283 switch(sWorld.getConfig(CONFIG_UINT32_GM_WISPERING_TO))
15285 default:
15286 case 0: break; // disable
15287 case 1: SetAcceptWhispers(true); break; // enable
15288 case 2: // save state
15289 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
15290 SetAcceptWhispers(true);
15291 break;
15295 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
15297 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
15298 m_achievementMgr.CheckAllAchievementCriteria();
15300 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
15302 return true;
15305 bool Player::isAllowedToLoot(Creature* creature)
15307 if(Player* recipient = creature->GetLootRecipient())
15309 if (recipient == this)
15310 return true;
15311 if( Group* otherGroup = recipient->GetGroup())
15313 Group* thisGroup = GetGroup();
15314 if(!thisGroup)
15315 return false;
15316 return thisGroup == otherGroup;
15318 return false;
15320 else
15321 // prevent other players from looting if the recipient got disconnected
15322 return !creature->hasLootRecipient();
15325 void Player::_LoadActions(QueryResult *result)
15327 for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
15328 m_actionButtons[i].clear();
15330 //QueryResult *result = CharacterDatabase.PQuery("SELECT spec, button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
15332 if(result)
15336 Field *fields = result->Fetch();
15338 uint8 spec = fields[0].GetUInt8();
15339 uint8 button = fields[1].GetUInt8();
15340 uint32 action = fields[2].GetUInt32();
15341 uint8 type = fields[3].GetUInt8();
15343 if(ActionButton* ab = addActionButton(spec, button, action, type))
15344 ab->uState = ACTIONBUTTON_UNCHANGED;
15345 else
15347 sLog.outError( " ...at loading, and will deleted in DB also");
15349 // Will deleted in DB at next save (it can create data until save but marked as deleted)
15350 m_actionButtons[spec][button].uState = ACTIONBUTTON_DELETED;
15353 while( result->NextRow() );
15355 delete result;
15359 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
15361 //RemoveAllAuras(); -- some spells casted before aura load, for example in LoadSkills, aura list explcitly cleaned early
15363 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15365 if(result)
15369 Field *fields = result->Fetch();
15370 uint64 caster_guid = fields[0].GetUInt64();
15371 uint32 spellid = fields[1].GetUInt32();
15372 SpellEffectIndex effindex = SpellEffectIndex(fields[2].GetUInt32());
15373 uint32 stackcount = fields[3].GetUInt32();
15374 int32 damage = fields[4].GetInt32();
15375 int32 maxduration = fields[5].GetInt32();
15376 int32 remaintime = fields[6].GetInt32();
15377 int32 remaincharges = fields[7].GetInt32();
15379 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
15380 if (!spellproto)
15382 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
15383 continue;
15386 if (effindex >= MAX_EFFECT_INDEX)
15388 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
15389 continue;
15392 // negative effects should continue counting down after logout
15393 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
15395 if (remaintime/IN_MILISECONDS <= int32(timediff))
15396 continue;
15398 remaintime -= timediff*IN_MILISECONDS;
15401 // prevent wrong values of remaincharges
15402 if (spellproto->procCharges)
15404 if (remaincharges <= 0 || remaincharges > (int32)spellproto->procCharges)
15405 remaincharges = spellproto->procCharges;
15407 else
15408 remaincharges = 0;
15411 for(uint32 i = 0; i < stackcount; ++i)
15413 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
15414 if (!damage)
15415 damage = aura->GetModifier()->m_amount;
15417 // reset stolen single target auras
15418 if (caster_guid != GetGUID() && aura->IsSingleTarget())
15419 aura->SetIsSingleTarget(false);
15421 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
15422 AddAura(aura);
15423 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
15426 while( result->NextRow() );
15428 delete result;
15431 if(getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
15432 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
15435 void Player::_LoadGlyphs(QueryResult *result)
15437 if(!result)
15438 return;
15440 // 0 1 2
15441 // "SELECT spec, slot, glyph FROM character_glyphs WHERE guid='%u'"
15445 Field *fields = result->Fetch();
15446 uint8 spec = fields[0].GetUInt8();
15447 uint8 slot = fields[1].GetUInt8();
15448 uint32 glyph = fields[2].GetUInt32();
15450 GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph);
15451 if(!gp)
15453 sLog.outError("Player %s has not existing glyph entry %u on index %u, spec %u", m_name.c_str(), glyph, slot, spec);
15454 continue;
15457 GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(slot));
15458 if (!gs)
15460 sLog.outError("Player %s has not existing glyph slot entry %u on index %u, spec %u", m_name.c_str(), GetGlyphSlot(slot), slot, spec);
15461 continue;
15464 if(gp->TypeFlags != gs->TypeFlags)
15466 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
15467 continue;
15470 m_glyphs[spec][slot].id = glyph;
15472 } while( result->NextRow() );
15474 delete result;
15479 void Player::LoadCorpse()
15481 if( isAlive() )
15483 sObjectAccessor.ConvertCorpseForPlayer(GetGUID());
15485 else
15487 if(Corpse *corpse = GetCorpse())
15489 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
15491 else
15493 //Prevent Dead Player login without corpse
15494 ResurrectPlayer(0.5f);
15499 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
15501 //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());
15502 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
15503 //NOTE: the "order by `bag`" is important because it makes sure
15504 //the bagMap is filled before items in the bags are loaded
15505 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
15506 //expected to be equipped before offhand items (TODO: fixme)
15508 uint32 zone = GetZoneId();
15510 if (result)
15512 std::list<Item*> problematicItems;
15514 // prevent items from being added to the queue when stored
15515 m_itemUpdateQueueBlocked = true;
15518 Field *fields = result->Fetch();
15519 uint32 bag_guid = fields[1].GetUInt32();
15520 uint8 slot = fields[2].GetUInt8();
15521 uint32 item_guid = fields[3].GetUInt32();
15522 uint32 item_id = fields[4].GetUInt32();
15524 ItemPrototype const * proto = ObjectMgr::GetItemPrototype(item_id);
15526 if(!proto)
15528 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15529 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
15530 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
15531 continue;
15534 Item *item = NewItemOrBag(proto);
15536 if(!item->LoadFromDB(item_guid, GetGUID(), result))
15538 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
15539 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15540 item->FSetState(ITEM_REMOVED);
15541 item->SaveToDB(); // it also deletes item object !
15542 continue;
15545 // not allow have in alive state item limited to another map/zone
15546 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
15548 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15549 item->FSetState(ITEM_REMOVED);
15550 item->SaveToDB(); // it also deletes item object !
15551 continue;
15554 // "Conjured items disappear if you are logged out for more than 15 minutes"
15555 if (timediff > 15*MINUTE && item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED))
15557 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15558 item->FSetState(ITEM_REMOVED);
15559 item->SaveToDB(); // it also deletes item object !
15560 continue;
15563 bool success = true;
15565 // the item/bag is not in a bag
15566 if (!bag_guid)
15568 item->SetContainer( NULL );
15569 item->SetSlot(slot);
15571 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
15573 ItemPosCountVec dest;
15574 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
15575 item = StoreItem(dest, item, true);
15576 else
15577 success = false;
15579 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
15581 uint16 dest;
15582 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
15583 QuickEquipItem(dest, item);
15584 else
15585 success = false;
15587 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
15589 ItemPosCountVec dest;
15590 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
15591 item = BankItem(dest, item, true);
15592 else
15593 success = false;
15596 if(success)
15598 // store bags that may contain items in them
15599 if(item->IsBag() && IsBagPos(item->GetPos()))
15600 bagMap[item_guid] = (Bag*)item;
15603 // the item/bag in a bag
15604 else
15606 item->SetSlot(NULL_SLOT);
15607 // the item is in a bag, find the bag
15608 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
15609 if(itr != bagMap.end() && slot < itr->second->GetBagSize())
15611 ItemPosCountVec dest;
15612 if( CanStoreItem( itr->second->GetSlot(), slot, dest, item, false ) == EQUIP_ERR_OK )
15613 item = StoreItem(dest, item, true);
15614 else
15615 success = false;
15617 else
15618 success = false;
15621 // item's state may have changed after stored
15622 if (success)
15624 item->SetState(ITEM_UNCHANGED, this);
15626 // recharged mana gem
15627 if (timediff > 15*MINUTE && proto->ItemLimitCategory ==ITEM_LIMIT_CATEGORY_MANA_GEM)
15628 item->RestoreCharges();
15630 else
15632 sLog.outError("Player::_LoadInventory: Player %s has item (GUID: %u Entry: %u) can't be loaded to inventory (Bag GUID: %u Slot: %u) by some reason, will send by mail.", GetName(),item_guid, item_id, bag_guid, slot);
15633 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15634 problematicItems.push_back(item);
15636 } while (result->NextRow());
15638 delete result;
15639 m_itemUpdateQueueBlocked = false;
15641 // send by mail problematic items
15642 while(!problematicItems.empty())
15644 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
15646 // fill mail
15647 MailDraft draft(subject);
15649 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
15651 Item* item = problematicItems.front();
15652 problematicItems.pop_front();
15654 draft.AddItem(item);
15657 draft.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
15660 //if(isAlive())
15661 _ApplyAllItemMods();
15664 // load mailed item which should receive current player
15665 void Player::_LoadMailedItems(Mail *mail)
15667 // data needs to be at first place for Item::LoadFromDB
15668 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);
15669 if(!result)
15670 return;
15674 Field *fields = result->Fetch();
15675 uint32 item_guid_low = fields[1].GetUInt32();
15676 uint32 item_template = fields[2].GetUInt32();
15678 mail->AddItem(item_guid_low, item_template);
15680 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(item_template);
15682 if(!proto)
15684 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);
15685 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15686 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
15687 continue;
15690 Item *item = NewItemOrBag(proto);
15692 if(!item->LoadFromDB(item_guid_low, 0, result))
15694 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
15695 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15696 item->FSetState(ITEM_REMOVED);
15697 item->SaveToDB(); // it also deletes item object !
15698 continue;
15701 AddMItem(item);
15702 } while (result->NextRow());
15704 delete result;
15707 void Player::_LoadMail()
15709 m_mail.clear();
15710 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15711 QueryResult *result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,subject,itemTextId,has_items,expire_time,deliver_time,money,cod,checked,stationery,mailTemplateId FROM mail WHERE receiver = '%u' ORDER BY id DESC",GetGUIDLow());
15712 if(result)
15716 Field *fields = result->Fetch();
15717 Mail *m = new Mail;
15718 m->messageID = fields[0].GetUInt32();
15719 m->messageType = fields[1].GetUInt8();
15720 m->sender = fields[2].GetUInt32();
15721 m->receiver = fields[3].GetUInt32();
15722 m->subject = fields[4].GetCppString();
15723 m->itemTextId = fields[5].GetUInt32();
15724 bool has_items = fields[6].GetBool();
15725 m->expire_time = (time_t)fields[7].GetUInt64();
15726 m->deliver_time = (time_t)fields[8].GetUInt64();
15727 m->money = fields[9].GetUInt32();
15728 m->COD = fields[10].GetUInt32();
15729 m->checked = fields[11].GetUInt32();
15730 m->stationery = fields[12].GetUInt8();
15731 m->mailTemplateId = fields[13].GetInt16();
15733 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15735 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15736 m->mailTemplateId = 0;
15739 m->state = MAIL_STATE_UNCHANGED;
15741 if (has_items)
15742 _LoadMailedItems(m);
15744 m_mail.push_back(m);
15745 } while( result->NextRow() );
15746 delete result;
15750 void Player::LoadPet()
15752 //fixme: the pet should still be loaded if the player is not in world
15753 // just not added to the map
15754 if(IsInWorld())
15756 Pet *pet = new Pet;
15757 if(!pet->LoadPetFromDB(this,0,0,true))
15758 delete pet;
15762 void Player::_LoadQuestStatus(QueryResult *result)
15764 mQuestStatus.clear();
15766 uint32 slot = 0;
15768 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15769 //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());
15771 if(result)
15775 Field *fields = result->Fetch();
15777 uint32 quest_id = fields[0].GetUInt32();
15778 // used to be new, no delete?
15779 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15780 if( pQuest )
15782 // find or create
15783 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15785 uint32 qstatus = fields[1].GetUInt32();
15786 if(qstatus < MAX_QUEST_STATUS)
15787 questStatusData.m_status = QuestStatus(qstatus);
15788 else
15790 questStatusData.m_status = QUEST_STATUS_NONE;
15791 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15794 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15795 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15797 time_t quest_time = time_t(fields[4].GetUInt64());
15799 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15801 AddTimedQuest( quest_id );
15803 if (quest_time <= sWorld.GetGameTime())
15804 questStatusData.m_timer = 1;
15805 else
15806 questStatusData.m_timer = uint32(quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
15808 else
15809 quest_time = 0;
15811 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15812 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15813 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15814 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15815 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15816 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15817 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15818 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15820 questStatusData.uState = QUEST_UNCHANGED;
15822 // add to quest log
15823 if (slot < MAX_QUEST_LOG_SIZE &&
15824 ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
15825 questStatusData.m_status == QUEST_STATUS_COMPLETE ||
15826 questStatusData.m_status == QUEST_STATUS_FAILED) &&
15827 (!questStatusData.m_rewarded || pQuest->IsRepeatable())))
15829 SetQuestSlot(slot, quest_id, uint32(quest_time));
15831 if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
15832 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
15834 if (questStatusData.m_status == QUEST_STATUS_FAILED)
15835 SetQuestSlotState(slot, QUEST_STATE_FAIL);
15837 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15838 if(questStatusData.m_creatureOrGOcount[idx])
15839 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
15841 ++slot;
15844 if(questStatusData.m_rewarded)
15846 // learn rewarded spell if unknown
15847 learnQuestRewardedSpells(pQuest);
15849 // set rewarded title if any
15850 if(pQuest->GetCharTitleId())
15852 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15853 SetTitle(titleEntry);
15856 if(pQuest->GetBonusTalents())
15857 m_questRewardTalentCount += pQuest->GetBonusTalents();
15860 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15863 while( result->NextRow() );
15865 delete result;
15868 // clear quest log tail
15869 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15870 SetQuestSlot(i, 0);
15873 void Player::_LoadDailyQuestStatus(QueryResult *result)
15875 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15876 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15878 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15880 if(result)
15882 uint32 quest_daily_idx = 0;
15886 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15888 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15889 break;
15892 Field *fields = result->Fetch();
15894 uint32 quest_id = fields[0].GetUInt32();
15896 // save _any_ from daily quest times (it must be after last reset anyway)
15897 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15899 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15900 if( !pQuest )
15901 continue;
15903 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15904 ++quest_daily_idx;
15906 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15908 while( result->NextRow() );
15910 delete result;
15913 m_DailyQuestChanged = false;
15916 void Player::_LoadSpells(QueryResult *result)
15918 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15920 if(result)
15924 Field *fields = result->Fetch();
15926 addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool());
15928 while( result->NextRow() );
15930 delete result;
15934 void Player::_LoadGroup(QueryResult *result)
15936 //QueryResult *result = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15937 if (result)
15939 uint32 groupId = (*result)[0].GetUInt32();
15940 delete result;
15942 if (Group* group = sObjectMgr.GetGroupById(groupId))
15944 uint8 subgroup = group->GetMemberGroup(GetGUID());
15945 SetGroup(group, subgroup);
15946 if (getLevel() >= LEVELREQUIREMENT_HEROIC)
15948 // the group leader may change the instance difficulty while the player is offline
15949 SetDungeonDifficulty(group->GetDungeonDifficulty());
15950 SetRaidDifficulty(group->GetRaidDifficulty());
15956 void Player::_LoadBoundInstances(QueryResult *result)
15958 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15959 m_boundInstances[i].clear();
15961 Group *group = GetGroup();
15963 //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));
15964 if(result)
15968 Field *fields = result->Fetch();
15969 bool perm = fields[1].GetBool();
15970 uint32 mapId = fields[2].GetUInt32();
15971 uint32 instanceId = fields[0].GetUInt32();
15972 uint8 difficulty = fields[3].GetUInt8();
15974 time_t resetTime = (time_t)fields[4].GetUInt64();
15975 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15976 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15977 // and in that case it is not used
15979 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15980 if(!mapEntry || !mapEntry->IsDungeon())
15982 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15983 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15984 continue;
15987 if(difficulty >= MAX_DIFFICULTY)
15989 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15990 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15991 continue;
15994 MapDifficulty const* mapDiff = GetMapDifficultyData(mapId,Difficulty(difficulty));
15995 if(!mapDiff)
15997 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15998 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15999 continue;
16002 if(!perm && group)
16004 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);
16005 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
16006 continue;
16009 // since non permanent binds are always solo bind, they can always be reset
16010 InstanceSave *save = sInstanceSaveMgr.AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, !perm, true);
16011 if(save) BindToInstance(save, perm, true);
16012 } while(result->NextRow());
16013 delete result;
16017 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
16019 // some instances only have one difficulty
16020 MapDifficulty const* mapDiff = GetMapDifficultyData(mapid,difficulty);
16021 if(!mapDiff)
16022 return NULL;
16024 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
16025 if(itr != m_boundInstances[difficulty].end())
16026 return &itr->second;
16027 else
16028 return NULL;
16031 void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
16033 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
16034 UnbindInstance(itr, difficulty, unload);
16037 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
16039 if(itr != m_boundInstances[difficulty].end())
16041 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
16042 itr->second.save->RemovePlayer(this); // save can become invalid
16043 m_boundInstances[difficulty].erase(itr++);
16047 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
16049 if(save)
16051 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
16052 if(bind.save)
16054 // update the save when the group kills a boss
16055 if(permanent != bind.perm || save != bind.save)
16056 if(!load) CharacterDatabase.PExecute("UPDATE character_instance SET instance = '%u', permanent = '%u' WHERE guid = '%u' AND instance = '%u'", save->GetInstanceId(), permanent, GetGUIDLow(), bind.save->GetInstanceId());
16058 else
16059 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
16061 if(bind.save != save)
16063 if(bind.save) bind.save->RemovePlayer(this);
16064 save->AddPlayer(this);
16067 if(permanent) save->SetCanReset(false);
16069 bind.save = save;
16070 bind.perm = permanent;
16071 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());
16072 return &bind;
16074 else
16075 return NULL;
16078 void Player::SendRaidInfo()
16080 uint32 counter = 0;
16082 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
16084 size_t p_counter = data.wpos();
16085 data << uint32(counter); // placeholder
16087 time_t now = time(NULL);
16089 for(int i = 0; i < MAX_DIFFICULTY; ++i)
16091 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
16093 if(itr->second.perm)
16095 InstanceSave *save = itr->second.save;
16096 data << uint32(save->GetMapId()); // map id
16097 data << uint32(save->GetDifficulty()); // difficulty
16098 data << uint64(save->GetInstanceId()); // instance id
16099 data << uint8(1); // expired = 0
16100 data << uint8(0); // extended = 1
16101 data << uint32(save->GetResetTime() - now); // reset time
16102 ++counter;
16106 data.put<uint32>(p_counter, counter);
16107 GetSession()->SendPacket(&data);
16111 - called on every successful teleportation to a map
16113 void Player::SendSavedInstances()
16115 bool hasBeenSaved = false;
16116 WorldPacket data;
16118 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16120 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
16122 if(itr->second.perm) // only permanent binds are sent
16124 hasBeenSaved = true;
16125 break;
16130 //Send opcode 811. true or false means, whether you have current raid/heroic instances
16131 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
16132 data << uint32(hasBeenSaved);
16133 GetSession()->SendPacket(&data);
16135 if(!hasBeenSaved)
16136 return;
16138 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16140 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
16142 if(itr->second.perm)
16144 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
16145 data << uint32(itr->second.save->GetMapId());
16146 GetSession()->SendPacket(&data);
16152 /// convert the player's binds to the group
16153 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
16155 bool has_binds = false;
16156 bool has_solo = false;
16158 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
16159 assert(player_guid);
16161 // copy all binds to the group, when changing leader it's assumed the character
16162 // will not have any solo binds
16164 if(player)
16166 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16168 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
16170 has_binds = true;
16171 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
16172 // permanent binds are not removed
16173 if(!itr->second.perm)
16175 // increments itr in call
16176 player->UnbindInstance(itr, Difficulty(i), true);
16177 has_solo = true;
16179 else
16180 ++itr;
16185 // if the player's not online we don't know what binds it has
16186 if(!player || !group || has_binds)
16187 CharacterDatabase.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid));
16189 // the following should not get executed when changing leaders
16190 if(!player || has_solo)
16191 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
16194 bool Player::_LoadHomeBind(QueryResult *result)
16196 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
16197 if(!info)
16199 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
16200 return false;
16203 bool ok = false;
16204 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
16205 if (result)
16207 Field *fields = result->Fetch();
16208 m_homebindMapId = fields[0].GetUInt32();
16209 m_homebindAreaId = fields[1].GetUInt16();
16210 m_homebindX = fields[2].GetFloat();
16211 m_homebindY = fields[3].GetFloat();
16212 m_homebindZ = fields[4].GetFloat();
16213 delete result;
16215 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
16217 // accept saved data only for valid position (and non instanceable), and accessable
16218 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
16219 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
16221 ok = true;
16223 else
16224 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
16227 if(!ok)
16229 m_homebindMapId = info->mapId;
16230 m_homebindAreaId = info->areaId;
16231 m_homebindX = info->positionX;
16232 m_homebindY = info->positionY;
16233 m_homebindZ = info->positionZ;
16235 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_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ);
16238 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
16239 m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ);
16241 return true;
16244 /*********************************************************/
16245 /*** SAVE SYSTEM ***/
16246 /*********************************************************/
16248 void Player::SaveToDB()
16250 // we should assure this: assert((m_nextSave != sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE)));
16251 // delay auto save at any saves (manual, in code, or autosave)
16252 m_nextSave = sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE);
16254 //lets allow only players in world to be saved
16255 if(IsBeingTeleportedFar())
16257 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
16258 return;
16261 // first save/honor gain after midnight will also update the player's honor fields
16262 UpdateHonorFields();
16264 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
16265 outDebugValues();
16267 CharacterDatabase.BeginTransaction();
16269 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
16271 std::string sql_name = m_name;
16272 CharacterDatabase.escape_string(sql_name);
16274 std::ostringstream ss;
16275 ss << "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
16276 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
16277 "taximask, online, cinematic, "
16278 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
16279 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
16280 "death_expire_time, taxi_path, arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, "
16281 "todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, health, power1, power2, power3, "
16282 "power4, power5, power6, power7, specCount, activeSpec) VALUES ("
16283 << GetGUIDLow() << ", "
16284 << GetSession()->GetAccountId() << ", '"
16285 << sql_name << "', "
16286 << (uint32)getRace() << ", "
16287 << (uint32)getClass() << ", "
16288 << (uint32)getGender() << ", "
16289 << getLevel() << ", "
16290 << GetUInt32Value(PLAYER_XP) << ", "
16291 << GetMoney() << ", "
16292 << GetUInt32Value(PLAYER_BYTES) << ", "
16293 << GetUInt32Value(PLAYER_BYTES_2) << ", "
16294 << GetUInt32Value(PLAYER_FLAGS) << ", ";
16296 if(!IsBeingTeleported())
16298 ss << GetMapId() << ", "
16299 << (uint32)GetDungeonDifficulty() << ", "
16300 << finiteAlways(GetPositionX()) << ", "
16301 << finiteAlways(GetPositionY()) << ", "
16302 << finiteAlways(GetPositionZ()) << ", "
16303 << finiteAlways(GetOrientation()) << ", '";
16305 else
16307 ss << GetTeleportDest().mapid << ", "
16308 << (uint32)GetDungeonDifficulty() << ", "
16309 << finiteAlways(GetTeleportDest().coord_x) << ", "
16310 << finiteAlways(GetTeleportDest().coord_y) << ", "
16311 << finiteAlways(GetTeleportDest().coord_z) << ", "
16312 << finiteAlways(GetTeleportDest().orientation) << ", '";
16315 uint16 i;
16316 for( i = 0; i < m_valuesCount; ++i )
16318 ss << GetUInt32Value(i) << " ";
16321 ss << "', ";
16323 ss << m_taxi << ", "; // string with TaxiMaskSize numbers
16325 ss << (IsInWorld() ? 1 : 0) << ", ";
16327 ss << m_cinematic << ", ";
16329 ss << m_Played_time[PLAYED_TIME_TOTAL] << ", ";
16330 ss << m_Played_time[PLAYED_TIME_LEVEL] << ", ";
16332 ss << finiteAlways(m_rest_bonus) << ", ";
16333 ss << (uint64)time(NULL) << ", ";
16334 ss << (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0) << ", ";
16335 //save, far from tavern/city
16336 //save, but in tavern/city
16337 ss << m_resetTalentsCost << ", ";
16338 ss << (uint64)m_resetTalentsTime << ", ";
16340 ss << finiteAlways(m_movementInfo.GetTransportPos()->x) << ", ";
16341 ss << finiteAlways(m_movementInfo.GetTransportPos()->y) << ", ";
16342 ss << finiteAlways(m_movementInfo.GetTransportPos()->z) << ", ";
16343 ss << finiteAlways(m_movementInfo.GetTransportPos()->o) << ", ";
16344 if (m_transport)
16345 ss << m_transport->GetGUIDLow();
16346 else
16347 ss << "0";
16348 ss << ", ";
16350 ss << m_ExtraFlags << ", ";
16352 ss << uint32(m_stableSlots) << ", "; // to prevent save uint8 as char
16354 ss << uint32(m_atLoginFlags) << ", ";
16356 ss << GetZoneId() << ", ";
16358 ss << (uint64)m_deathExpireTime << ", '";
16360 ss << m_taxi.SaveTaxiDestinationsToString() << "', ";
16362 ss << GetArenaPoints() << ", ";
16364 ss << GetHonorPoints() << ", ";
16366 ss << GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION) << ", ";
16368 ss << GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION) << ", ";
16370 ss << GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS) << ", ";
16372 ss << GetUInt16Value(PLAYER_FIELD_KILLS, 0) << ", ";
16374 ss << GetUInt16Value(PLAYER_FIELD_KILLS, 1) << ", ";
16376 ss << GetUInt32Value(PLAYER_CHOSEN_TITLE) << ", ";
16378 ss << GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES) << ", ";
16380 // FIXME: at this moment send to DB as unsigned, including unit32(-1)
16381 ss << GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX) << ", ";
16383 ss << (uint16)(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE) << ", ";
16385 ss << GetHealth();
16387 for(uint32 i = 0; i < MAX_POWERS; ++i)
16388 ss << "," << GetPower(Powers(i));
16390 ss << ", ";
16391 ss << uint32(m_specsCount) << ", ";
16392 ss << uint32(m_activeSpec);
16394 ss << ")";
16396 CharacterDatabase.Execute( ss.str().c_str() );
16398 if(m_mailsUpdated) //save mails only when needed
16399 _SaveMail();
16401 _SaveBGData();
16402 _SaveInventory();
16403 _SaveQuestStatus();
16404 _SaveDailyQuestStatus();
16405 _SaveSpells();
16406 _SaveSpellCooldowns();
16407 _SaveActions();
16408 _SaveAuras();
16409 _SaveSkills();
16410 m_achievementMgr.SaveToDB();
16411 m_reputationMgr.SaveToDB();
16412 _SaveEquipmentSets();
16413 GetSession()->SaveTutorialsData(); // changed only while character in game
16414 _SaveGlyphs();
16416 CharacterDatabase.CommitTransaction();
16418 // save pet (hunter pet level and experience and all type pets health/mana).
16419 if(Pet* pet = GetPet())
16420 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
16423 // fast save function for item/money cheating preventing - save only inventory and money state
16424 void Player::SaveInventoryAndGoldToDB()
16426 _SaveInventory();
16427 SaveGoldToDB();
16430 void Player::SaveGoldToDB()
16432 CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
16435 void Player::_SaveActions()
16437 for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
16439 for(ActionButtonList::iterator itr = m_actionButtons[i].begin(); itr != m_actionButtons[i].end(); )
16441 switch (itr->second.uState)
16443 case ACTIONBUTTON_NEW:
16444 CharacterDatabase.PExecute("INSERT INTO character_action (guid,spec, button,action,type) VALUES ('%u', '%u', '%u', '%u', '%u')",
16445 GetGUIDLow(), i, (uint32)itr->first, (uint32)itr->second.GetAction(), (uint32)itr->second.GetType() );
16446 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16447 ++itr;
16448 break;
16449 case ACTIONBUTTON_CHANGED:
16450 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' AND spec = '%u'",
16451 (uint32)itr->second.GetAction(), (uint32)itr->second.GetType(), GetGUIDLow(), (uint32)itr->first, i );
16452 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16453 ++itr;
16454 break;
16455 case ACTIONBUTTON_DELETED:
16456 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' AND button = '%u' AND spec = '%u'", GetGUIDLow(), (uint32)itr->first, i);
16457 m_actionButtons[i].erase(itr++);
16458 break;
16459 default:
16460 ++itr;
16461 break;
16467 void Player::_SaveAuras()
16469 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
16471 AuraMap const& auras = GetAuras();
16473 if (auras.empty())
16474 return;
16476 spellEffectPair lastEffectPair = auras.begin()->first;
16477 uint32 stackCounter = 1;
16479 /* copied following sql-code partly from achievementmgr */
16480 bool first_round = true;
16481 std::ostringstream ss;
16482 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
16484 if(itr == auras.end() || lastEffectPair != itr->first)
16486 AuraMap::const_iterator itr2 = itr;
16487 // save previous spellEffectPair to db
16488 itr2--;
16490 //skip all auras from spells that are passive
16491 //do not save single target auras (unless they were cast by the player)
16492 if (!itr2->second->IsPassive() && (itr2->second->GetCasterGUID() == GetGUID() || !itr2->second->IsSingleTarget()))
16494 if (first_round)
16496 ss << "INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges)VALUES ";
16497 first_round = false;
16499 // next new/changed record prefix
16500 else
16501 ss << ", ";
16503 ss << "("<< GetGUIDLow() << "," << itr2->second->GetCasterGUID() << ","
16504 << (uint32)itr2->second->GetId() << "," << (uint32)itr2->second->GetEffIndex() << ","
16505 << stackCounter << "," << itr2->second->GetModifier()->m_amount << ","
16506 <<int(itr2->second->GetAuraMaxDuration()) << "," << int(itr2->second->GetAuraDuration()) << ","
16507 << int(itr2->second->GetAuraCharges()) << ")";
16510 if(itr == auras.end())
16511 break;
16514 if (lastEffectPair == itr->first)
16515 stackCounter++;
16516 else
16518 lastEffectPair = itr->first;
16519 stackCounter = 1;
16523 // if something changed execute
16524 if (!first_round)
16525 CharacterDatabase.Execute( ss.str().c_str() );
16528 void Player::_SaveGlyphs()
16531 for (uint8 spec = 0; spec < m_specsCount; ++spec)
16533 for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
16535 switch(m_glyphs[spec][slot].uState)
16537 case GLYPH_NEW:
16538 CharacterDatabase.PExecute("INSERT INTO character_glyphs (guid, spec, slot, glyph) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), spec, slot, m_glyphs[spec][slot].GetId());
16539 break;
16540 case GLYPH_CHANGED:
16541 CharacterDatabase.PExecute("UPDATE character_glyphs SET glyph = '%u' WHERE guid='%u' AND spec = '%u' AND slot = '%u'", m_glyphs[spec][slot].GetId(), GetGUIDLow(), spec, slot);
16542 break;
16543 case GLYPH_DELETED:
16544 CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid='%u' AND spec = '%u' AND slot = '%u'",GetGUIDLow(), spec, slot);
16545 break;
16546 case GLYPH_UNCHANGED:
16547 break;
16549 m_glyphs[spec][slot].uState = GLYPH_UNCHANGED;
16554 void Player::_SaveInventory()
16556 // force items in buyback slots to new state
16557 // and remove those that aren't already
16558 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
16560 Item *item = m_items[i];
16561 if (!item || item->GetState() == ITEM_NEW) continue;
16562 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16563 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
16564 m_items[i]->FSetState(ITEM_NEW);
16567 // update enchantment durations
16568 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
16570 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
16573 // if no changes
16574 if (m_itemUpdateQueue.empty()) return;
16576 // do not save if the update queue is corrupt
16577 bool error = false;
16578 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16580 Item *item = m_itemUpdateQueue[i];
16581 if(!item || item->GetState() == ITEM_REMOVED) continue;
16582 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
16584 if (test == NULL)
16586 sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the player doesn't have an item at that position!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow());
16587 error = true;
16589 else if (test != item)
16591 sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the item with guid %d is there instead!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), test->GetGUIDLow());
16592 error = true;
16596 if (error)
16598 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
16599 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
16600 return;
16603 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16605 Item *item = m_itemUpdateQueue[i];
16606 if(!item) continue;
16608 Bag *container = item->GetContainer();
16609 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
16611 switch(item->GetState())
16613 case ITEM_NEW:
16614 CharacterDatabase.PExecute("INSERT INTO character_inventory (guid,bag,slot,item,item_template) VALUES ('%u', '%u', '%u', '%u', '%u')", GetGUIDLow(), bag_guid, item->GetSlot(), item->GetGUIDLow(), item->GetEntry());
16615 break;
16616 case ITEM_CHANGED:
16617 CharacterDatabase.PExecute("UPDATE character_inventory SET guid='%u', bag='%u', slot='%u', item_template='%u' WHERE item='%u'", GetGUIDLow(), bag_guid, item->GetSlot(), item->GetEntry(), item->GetGUIDLow());
16618 break;
16619 case ITEM_REMOVED:
16620 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16621 break;
16622 case ITEM_UNCHANGED:
16623 break;
16626 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
16628 m_itemUpdateQueue.clear();
16631 void Player::_SaveMail()
16633 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
16635 Mail *m = (*itr);
16636 if (m->state == MAIL_STATE_CHANGED)
16638 CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" UI64FMTD "', deliver_time = '" UI64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
16639 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
16640 if(m->removedItems.size())
16642 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
16643 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
16644 m->removedItems.clear();
16646 m->state = MAIL_STATE_UNCHANGED;
16648 else if (m->state == MAIL_STATE_DELETED)
16650 if (m->HasItems())
16651 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
16652 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
16653 if (m->itemTextId)
16654 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
16655 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
16656 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
16660 //deallocate deleted mails...
16661 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
16663 if ((*itr)->state == MAIL_STATE_DELETED)
16665 Mail* m = *itr;
16666 m_mail.erase(itr);
16667 delete m;
16668 itr = m_mail.begin();
16670 else
16671 ++itr;
16674 m_mailsUpdated = false;
16677 void Player::_SaveQuestStatus()
16679 // we don't need transactions here.
16680 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
16682 switch (i->second.uState)
16684 case QUEST_NEW :
16685 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
16686 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
16687 GetGUIDLow(), i->first, i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILISECONDS+ sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3]);
16688 break;
16689 case QUEST_CHANGED :
16690 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" UI64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
16691 i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILISECONDS + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3], GetGUIDLow(), i->first );
16692 break;
16693 case QUEST_UNCHANGED:
16694 break;
16696 i->second.uState = QUEST_UNCHANGED;
16700 void Player::_SaveDailyQuestStatus()
16702 if(!m_DailyQuestChanged)
16703 return;
16705 m_DailyQuestChanged = false;
16707 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
16709 // we don't need transactions here.
16710 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
16711 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
16712 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
16713 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
16714 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
16718 void Player::_SaveSkills()
16720 // we don't need transactions here.
16721 for( SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); )
16723 if(itr->second.uState == SKILL_UNCHANGED)
16725 ++itr;
16726 continue;
16729 if(itr->second.uState == SKILL_DELETED)
16731 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), itr->first );
16732 mSkillStatus.erase(itr++);
16733 continue;
16736 uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos));
16737 uint16 value = SKILL_VALUE(valueData);
16738 uint16 max = SKILL_MAX(valueData);
16740 switch (itr->second.uState)
16742 case SKILL_NEW:
16743 CharacterDatabase.PExecute("INSERT INTO character_skills (guid, skill, value, max) VALUES ('%u', '%u', '%u', '%u')",
16744 GetGUIDLow(), itr->first, value, max);
16745 break;
16746 case SKILL_CHANGED:
16747 CharacterDatabase.PExecute("UPDATE character_skills SET value = '%u',max = '%u'WHERE guid = '%u' AND skill = '%u' ",
16748 value, max, GetGUIDLow(), itr->first );
16749 break;
16751 itr->second.uState = SKILL_UNCHANGED;
16753 ++itr;
16757 void Player::_SaveSpells()
16759 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
16761 if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.state == PLAYERSPELL_CHANGED)
16762 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
16764 // add only changed/new not dependent spells
16765 if (!itr->second.dependent && (itr->second.state == PLAYERSPELL_NEW || itr->second.state == PLAYERSPELL_CHANGED))
16766 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);
16768 if (itr->second.state == PLAYERSPELL_REMOVED)
16769 m_spells.erase(itr++);
16770 else
16772 itr->second.state = PLAYERSPELL_UNCHANGED;
16773 ++itr;
16779 void Player::outDebugValues() const
16781 if(!sLog.IsOutDebug()) // optimize disabled debug output
16782 return;
16784 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
16785 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
16786 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
16787 sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
16788 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
16789 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
16790 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
16791 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
16792 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
16793 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
16794 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
16795 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
16798 /*********************************************************/
16799 /*** FLOOD FILTER SYSTEM ***/
16800 /*********************************************************/
16802 void Player::UpdateSpeakTime()
16804 // ignore chat spam protection for GMs in any mode
16805 if(GetSession()->GetSecurity() > SEC_PLAYER)
16806 return;
16808 time_t current = time (NULL);
16809 if(m_speakTime > current)
16811 uint32 max_count = sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_COUNT);
16812 if(!max_count)
16813 return;
16815 ++m_speakCount;
16816 if(m_speakCount >= max_count)
16818 // prevent overwrite mute time, if message send just before mutes set, for example.
16819 time_t new_mute = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MUTE_TIME);
16820 if(GetSession()->m_muteTime < new_mute)
16821 GetSession()->m_muteTime = new_mute;
16823 m_speakCount = 0;
16826 else
16827 m_speakCount = 0;
16829 m_speakTime = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_DELAY);
16832 bool Player::CanSpeak() const
16834 return GetSession()->m_muteTime <= time (NULL);
16837 /*********************************************************/
16838 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16839 /*********************************************************/
16841 void Player::SendAttackSwingNotInRange()
16843 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16844 GetSession()->SendPacket( &data );
16847 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16849 std::ostringstream ss;
16850 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16851 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16852 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16853 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16854 sLog.outDebug("%s", ss.str().c_str());
16855 CharacterDatabase.Execute(ss.str().c_str());
16858 void Player::SaveDataFieldToDB()
16860 std::ostringstream ss;
16861 ss<<"UPDATE characters SET data='";
16863 for(uint16 i = 0; i < m_valuesCount; ++i )
16865 ss << GetUInt32Value(i) << " ";
16867 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16869 CharacterDatabase.Execute(ss.str().c_str());
16872 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16874 std::ostringstream ss2;
16875 ss2 << "UPDATE characters SET data='";
16876 int i = 0;
16877 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16879 ss2 << tokens[i] << " ";
16881 ss2 << "' WHERE guid='" << GUID_LOPART(guid) << "'";
16883 return CharacterDatabase.Execute(ss2.str().c_str());
16886 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16888 char buf[11];
16889 snprintf(buf,11,"%u",value);
16891 if(index >= tokens.size())
16892 return;
16894 tokens[index] = buf;
16897 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16899 Tokens tokens;
16900 if(!LoadValuesArrayFromDB(tokens,guid))
16901 return;
16903 if(index >= tokens.size())
16904 return;
16906 char buf[11];
16907 snprintf(buf,11,"%u",value);
16908 tokens[index] = buf;
16910 SaveValuesArrayInDB(tokens,guid);
16913 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16915 uint32 temp;
16916 memcpy(&temp, &value, sizeof(value));
16917 Player::SetUInt32ValueInDB(index, temp, guid);
16920 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16922 // 0
16923 QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
16924 if(!result)
16925 return;
16927 Field* fields = result->Fetch();
16929 uint32 player_bytes2 = fields[0].GetUInt32();
16930 player_bytes2 &= ~0xFF;
16931 player_bytes2 |= facialHair;
16933 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));
16935 delete result;
16938 void Player::SendAttackSwingDeadTarget()
16940 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16941 GetSession()->SendPacket( &data );
16944 void Player::SendAttackSwingCantAttack()
16946 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16947 GetSession()->SendPacket( &data );
16950 void Player::SendAttackSwingCancelAttack()
16952 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16953 GetSession()->SendPacket( &data );
16956 void Player::SendAttackSwingBadFacingAttack()
16958 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16959 GetSession()->SendPacket( &data );
16962 void Player::SendAutoRepeatCancel(Unit *target)
16964 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
16965 data << target->GetPackGUID(); // may be it's target guid
16966 GetSession()->SendPacket( &data );
16969 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16971 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16972 data << uint32(Area);
16973 data << uint32(Experience);
16974 GetSession()->SendPacket(&data);
16977 void Player::SendDungeonDifficulty(bool IsInGroup)
16979 uint8 val = 0x00000001;
16980 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16981 data << uint32(GetDungeonDifficulty());
16982 data << uint32(val);
16983 data << uint32(IsInGroup);
16984 GetSession()->SendPacket(&data);
16987 void Player::SendRaidDifficulty(bool IsInGroup)
16989 uint8 val = 0x00000001;
16990 WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
16991 data << uint32(GetRaidDifficulty());
16992 data << uint32(val);
16993 data << uint32(IsInGroup);
16994 GetSession()->SendPacket(&data);
16997 void Player::SendResetFailedNotify(uint32 mapid)
16999 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
17000 data << uint32(mapid);
17001 GetSession()->SendPacket(&data);
17004 /// Reset all solo instances and optionally send a message on success for each
17005 void Player::ResetInstances(uint8 method, bool isRaid)
17007 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
17009 // we assume that when the difficulty changes, all instances that can be reset will be
17010 Difficulty diff = GetDifficulty(isRaid);
17012 for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
17014 InstanceSave *p = itr->second.save;
17015 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
17016 if(!entry || entry->IsRaid() != isRaid || !p->CanReset())
17018 ++itr;
17019 continue;
17022 if(method == INSTANCE_RESET_ALL)
17024 // the "reset all instances" method can only reset normal maps
17025 if(entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
17027 ++itr;
17028 continue;
17032 // if the map is loaded, reset it
17033 Map *map = sMapMgr.FindMap(p->GetMapId(), p->GetInstanceId());
17034 if(map && map->IsDungeon())
17035 ((InstanceMap*)map)->Reset(method);
17037 // since this is a solo instance there should not be any players inside
17038 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
17039 SendResetInstanceSuccess(p->GetMapId());
17041 p->DeleteFromDB();
17042 m_boundInstances[diff].erase(itr++);
17044 // the following should remove the instance save from the manager and delete it as well
17045 p->RemovePlayer(this);
17049 void Player::SendResetInstanceSuccess(uint32 MapId)
17051 WorldPacket data(SMSG_INSTANCE_RESET, 4);
17052 data << uint32(MapId);
17053 GetSession()->SendPacket(&data);
17056 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
17058 // TODO: find what other fail reasons there are besides players in the instance
17059 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
17060 data << uint32(reason);
17061 data << uint32(MapId);
17062 GetSession()->SendPacket(&data);
17065 /*********************************************************/
17066 /*** Update timers ***/
17067 /*********************************************************/
17069 ///checks the 15 afk reports per 5 minutes limit
17070 void Player::UpdateAfkReport(time_t currTime)
17072 if(m_bgData.bgAfkReportedTimer <= currTime)
17074 m_bgData.bgAfkReportedCount = 0;
17075 m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
17079 void Player::UpdateContestedPvP(uint32 diff)
17081 if(!m_contestedPvPTimer||isInCombat())
17082 return;
17083 if(m_contestedPvPTimer <= diff)
17085 ResetContestedPvP();
17087 else
17088 m_contestedPvPTimer -= diff;
17091 void Player::UpdatePvPFlag(time_t currTime)
17093 if(!IsPvP())
17094 return;
17095 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
17096 return;
17098 UpdatePvP(false);
17101 void Player::UpdateDuelFlag(time_t currTime)
17103 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
17104 return;
17106 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
17107 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
17109 duel->startTimer = 0;
17110 duel->startTime = currTime;
17111 duel->opponent->duel->startTimer = 0;
17112 duel->opponent->duel->startTime = currTime;
17115 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
17117 if(!pet)
17118 pet = GetPet();
17120 if(!pet || pet->GetOwnerGUID()!=GetGUID())
17121 return;
17123 // not save secondary permanent pet as current
17124 if (pet && m_temporaryUnsummonedPetNumber != pet->GetCharmInfo()->GetPetNumber() && mode == PET_SAVE_AS_CURRENT)
17125 mode = PET_SAVE_NOT_IN_SLOT;
17127 if(returnreagent && pet && mode != PET_SAVE_AS_CURRENT)
17129 //returning of reagents only for players, so best done here
17130 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
17131 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
17133 if(spellInfo)
17135 for(uint32 i = 0; i < 7; ++i)
17137 if(spellInfo->Reagent[i] > 0)
17139 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
17140 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
17141 if( msg == EQUIP_ERR_OK )
17143 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
17144 if(IsInWorld())
17145 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
17152 // only if current pet in slot
17153 switch(pet->getPetType())
17155 case MINI_PET:
17156 m_miniPet = 0;
17157 break;
17158 case GUARDIAN_PET:
17159 RemoveGuardian(pet);
17160 break;
17161 default:
17162 if(GetPetGUID() == pet->GetGUID())
17163 SetPet(NULL);
17164 break;
17167 pet->CombatStop();
17169 pet->SavePetToDB(mode);
17171 pet->AddObjectToRemoveList();
17172 pet->m_removed = true;
17174 if(pet->isControlled())
17176 RemovePetActionBar();
17178 if(GetGroup())
17179 SetGroupUpdateFlag(GROUP_UPDATE_PET);
17183 void Player::RemoveMiniPet()
17185 if(Pet* pet = GetMiniPet())
17187 pet->Remove(PET_SAVE_AS_DELETED);
17188 m_miniPet = 0;
17192 Pet* Player::GetMiniPet()
17194 if(!m_miniPet)
17195 return NULL;
17196 return GetMap()->GetPet(m_miniPet);
17199 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
17201 *data << (uint8)msgtype;
17202 *data << (uint32)language;
17203 *data << (uint64)GetGUID();
17204 *data << (uint32)language; //language 2.1.0 ?
17205 *data << (uint64)GetGUID();
17206 *data << (uint32)(text.length()+1);
17207 *data << text;
17208 *data << (uint8)chatTag();
17211 void Player::Say(const std::string& text, const uint32 language)
17213 WorldPacket data(SMSG_MESSAGECHAT, 200);
17214 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
17215 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY),true);
17218 void Player::Yell(const std::string& text, const uint32 language)
17220 WorldPacket data(SMSG_MESSAGECHAT, 200);
17221 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
17222 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL),true);
17225 void Player::TextEmote(const std::string& text)
17227 WorldPacket data(SMSG_MESSAGECHAT, 200);
17228 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
17229 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
17232 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
17234 if (language != LANG_ADDON) // if not addon data
17235 language = LANG_UNIVERSAL; // whispers should always be readable
17237 Player *rPlayer = sObjectMgr.GetPlayer(receiver);
17239 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
17240 if(!rPlayer->isDND() || isGameMaster())
17242 WorldPacket data(SMSG_MESSAGECHAT, 200);
17243 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
17244 rPlayer->GetSession()->SendPacket(&data);
17246 // not send confirmation for addon messages
17247 if (language != LANG_ADDON)
17249 data.Initialize(SMSG_MESSAGECHAT, 200);
17250 rPlayer->BuildPlayerChat(&data, CHAT_MSG_WHISPER_INFORM, text, language);
17251 GetSession()->SendPacket(&data);
17254 else
17256 // announce to player that player he is whispering to is dnd and cannot receive his message
17257 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
17260 if(!isAcceptWhispers())
17262 SetAcceptWhispers(true);
17263 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
17266 // announce to player that player he is whispering to is afk
17267 if(rPlayer->isAFK())
17268 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
17270 // if player whisper someone, auto turn of dnd to be able to receive an answer
17271 if(isDND() && !rPlayer->isGameMaster())
17272 ToggleDND();
17275 void Player::PetSpellInitialize()
17277 Pet* pet = GetPet();
17279 if(!pet)
17280 return;
17282 sLog.outDebug("Pet Spells Groups");
17284 CharmInfo *charmInfo = pet->GetCharmInfo();
17286 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17287 data << uint64(pet->GetGUID());
17288 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
17289 data << uint32(0);
17290 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17292 // action bar loop
17293 charmInfo->BuildActionBar(&data);
17295 size_t spellsCountPos = data.wpos();
17297 // spells count
17298 uint8 addlist = 0;
17299 data << uint8(addlist); // placeholder
17301 if (pet->IsPermanentPetFor(this))
17303 // spells loop
17304 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
17306 if(itr->second.state == PETSPELL_REMOVED)
17307 continue;
17309 data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
17310 ++addlist;
17314 data.put<uint8>(spellsCountPos, addlist);
17316 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
17317 data << uint8(cooldownsCount);
17319 time_t curTime = time(NULL);
17321 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
17323 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
17325 data << uint32(itr->first); // spellid
17326 data << uint16(0); // spell category?
17327 data << uint32(cooldown); // cooldown
17328 data << uint32(0); // category cooldown
17331 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
17333 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
17335 data << uint32(itr->first); // spellid
17336 data << uint16(0); // spell category?
17337 data << uint32(0); // cooldown
17338 data << uint32(cooldown); // category cooldown
17341 GetSession()->SendPacket(&data);
17344 void Player::SendPetGUIDs()
17346 if(!GetPetGUID())
17347 return;
17349 // Later this function might get modified for multiple guids
17350 WorldPacket data(SMSG_PET_GUIDS, 12);
17351 data << uint32(1); // count
17352 data << uint64(GetPetGUID());
17353 GetSession()->SendPacket(&data);
17356 void Player::PossessSpellInitialize()
17358 Unit* charm = GetCharm();
17360 if(!charm)
17361 return;
17363 CharmInfo *charmInfo = charm->GetCharmInfo();
17365 if(!charmInfo)
17367 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17368 return;
17371 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17372 data << uint64(charm->GetGUID());
17373 data << uint16(0);
17374 data << uint32(0);
17375 data << uint32(0);
17377 charmInfo->BuildActionBar(&data);
17379 data << uint8(0); // spells count
17380 data << uint8(0); // cooldowns count
17382 GetSession()->SendPacket(&data);
17385 void Player::CharmSpellInitialize()
17387 Unit* charm = GetCharm();
17389 if(!charm)
17390 return;
17392 CharmInfo *charmInfo = charm->GetCharmInfo();
17393 if(!charmInfo)
17395 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17396 return;
17399 uint8 addlist = 0;
17401 if(charm->GetTypeId() != TYPEID_PLAYER)
17403 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
17405 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
17407 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17409 if(charmInfo->GetCharmSpell(i)->GetAction())
17410 ++addlist;
17415 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
17416 data << uint64(charm->GetGUID());
17417 data << uint16(0);
17418 data << uint32(0);
17420 if(charm->GetTypeId() != TYPEID_PLAYER)
17421 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17422 else
17423 data << uint8(0) << uint8(0) << uint16(0);
17425 charmInfo->BuildActionBar(&data);
17427 data << uint8(addlist);
17429 if(addlist)
17431 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17433 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
17434 if(cspell->GetAction())
17435 data << uint32(cspell->packedData);
17439 data << uint8(0); // cooldowns count
17441 GetSession()->SendPacket(&data);
17444 void Player::RemovePetActionBar()
17446 WorldPacket data(SMSG_PET_SPELLS, 8);
17447 data << uint64(0);
17448 SendDirectMessage(&data);
17451 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
17453 if (!mod || !spellInfo)
17454 return false;
17456 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
17458 // prevent apply to any spell except spell that trigger expire
17459 if(spell)
17461 if(mod->lastAffected != spell)
17462 return false;
17464 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
17465 return false;
17468 return mod->isAffectedOnSpell(spellInfo);
17471 void Player::AddSpellMod(SpellModifier* mod, bool apply)
17473 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
17475 for(int eff = 0; eff < 96; ++eff)
17477 uint64 _mask = 0;
17478 uint32 _mask2= 0;
17480 if (eff < 64)
17481 _mask = uint64(1) << (eff - 0);
17482 else
17483 _mask2= uint32(1) << (eff - 64);
17485 if ( mod->mask & _mask || mod->mask2 & _mask2)
17487 int32 val = 0;
17488 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
17490 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
17491 val += (*itr)->value;
17493 val += apply ? mod->value : -(mod->value);
17494 WorldPacket data(Opcode, (1+1+4));
17495 data << uint8(eff);
17496 data << uint8(mod->op);
17497 data << int32(val);
17498 SendDirectMessage(&data);
17502 if (apply)
17503 m_spellMods[mod->op].push_back(mod);
17504 else
17506 if (mod->charges == -1)
17507 --m_SpellModRemoveCount;
17508 m_spellMods[mod->op].remove(mod);
17509 delete mod;
17513 void Player::RemoveSpellMods(Spell const* spell)
17515 if(!spell || (m_SpellModRemoveCount == 0))
17516 return;
17518 for(int i=0;i<MAX_SPELLMOD;++i)
17520 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
17522 SpellModifier *mod = *itr;
17523 ++itr;
17525 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
17527 RemoveAurasDueToSpell(mod->spellId);
17528 if (m_spellMods[i].empty())
17529 break;
17530 else
17531 itr = m_spellMods[i].begin();
17537 // send Proficiency
17538 void Player::SendProficiency(uint8 pr1, uint32 pr2)
17540 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
17541 data << uint8(pr1) << uint32(pr2);
17542 GetSession()->SendPacket (&data);
17545 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
17547 QueryResult *result = NULL;
17548 if(type == 10)
17549 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17550 else
17551 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17552 if(result)
17554 do // this part effectively does nothing, since the deletion / modification only takes place _after_ the PetitionQuery. Though I don't know if the result remains intact if I execute the delete query beforehand.
17555 { // and SendPetitionQueryOpcode reads data from the DB
17556 Field *fields = result->Fetch();
17557 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
17558 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
17560 // send update if charter owner in game
17561 Player* owner = sObjectMgr.GetPlayer(ownerguid);
17562 if(owner)
17563 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
17565 } while ( result->NextRow() );
17567 delete result;
17569 if(type==10)
17570 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17571 else
17572 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17575 CharacterDatabase.BeginTransaction();
17576 if(type == 10)
17578 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
17579 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
17581 else
17583 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17584 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17586 CharacterDatabase.CommitTransaction();
17589 void Player::LeaveAllArenaTeams(uint64 guid)
17591 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));
17592 if(!result)
17593 return;
17597 Field *fields = result->Fetch();
17598 uint32 at_id = fields[0].GetUInt32();
17599 if(at_id != 0)
17601 ArenaTeam * at = sObjectMgr.GetArenaTeamById(at_id);
17602 if(at)
17603 at->DelMember(guid);
17605 } while (result->NextRow());
17607 delete result;
17610 void Player::SetRestBonus (float rest_bonus_new)
17612 // Prevent resting on max level
17613 if(getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
17614 rest_bonus_new = 0;
17616 if(rest_bonus_new < 0)
17617 rest_bonus_new = 0;
17619 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5f/2.0f;
17621 if(rest_bonus_new > rest_bonus_max)
17622 m_rest_bonus = rest_bonus_max;
17623 else
17624 m_rest_bonus = rest_bonus_new;
17626 // update data for client
17627 if(m_rest_bonus>10)
17628 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
17629 else if(m_rest_bonus<=1)
17630 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
17632 //RestTickUpdate
17633 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
17636 void Player::HandleStealthedUnitsDetection()
17638 std::list<Unit*> stealthedUnits;
17640 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17641 Cell cell(p);
17642 cell.data.Part.reserved = ALL_DISTRICT;
17643 cell.SetNoCreate();
17645 MaNGOS::AnyStealthedCheck u_check;
17646 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
17648 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
17649 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
17651 cell.Visit(p, world_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17652 cell.Visit(p, grid_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17654 WorldObject const* viewPoint = GetViewPoint();
17656 for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
17658 if((*i)==this)
17659 continue;
17661 bool hasAtClient = HaveAtClient((*i));
17662 bool hasDetected = (*i)->isVisibleForOrDetect(this, viewPoint, true);
17664 if (hasDetected)
17666 if(!hasAtClient)
17668 ObjectGuid i_guid = (*i)->GetGUID();
17669 (*i)->SendCreateUpdateToPlayer(this);
17670 m_clientGUIDs.insert(i_guid);
17672 #ifdef MANGOS_DEBUG
17673 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17674 sLog.outDebug("%s is detected in stealth by player %u. Distance = %f",i_guid.GetString().c_str(),GetGUIDLow(),GetDistance(*i));
17675 #endif
17677 // target aura duration for caster show only if target exist at caster client
17678 // send data at target visibility change (adding to client)
17679 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
17680 SendAurasForTarget(*i);
17683 else
17685 if(hasAtClient)
17687 (*i)->DestroyForPlayer(this);
17688 m_clientGUIDs.erase((*i)->GetGUID());
17694 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
17696 if(nodes.size() < 2)
17697 return false;
17699 // 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
17700 if(GetSession()->isLogingOut() || isInCombat())
17702 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17703 data << uint32(ERR_TAXIPLAYERBUSY);
17704 GetSession()->SendPacket(&data);
17705 return false;
17708 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
17709 return false;
17711 // taximaster case
17712 if(npc)
17714 // not let cheating with start flight mounted
17715 if(IsMounted())
17717 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17718 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
17719 GetSession()->SendPacket(&data);
17720 return false;
17723 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17725 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17726 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
17727 GetSession()->SendPacket(&data);
17728 return false;
17731 // 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
17732 if(IsNonMeleeSpellCasted(false))
17734 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17735 data << uint32(ERR_TAXIPLAYERBUSY);
17736 GetSession()->SendPacket(&data);
17737 return false;
17740 // cast case or scripted call case
17741 else
17743 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
17745 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17746 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
17748 if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
17749 if (spell->m_spellInfo->Id != spellid)
17750 InterruptSpell(CURRENT_GENERIC_SPELL,false);
17752 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
17754 if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
17755 if (spell->m_spellInfo->Id != spellid)
17756 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
17759 uint32 sourcenode = nodes[0];
17761 // starting node too far away (cheat?)
17762 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
17763 if (!node)
17765 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17766 data << uint32(ERR_TAXINOSUCHPATH);
17767 GetSession()->SendPacket(&data);
17768 return false;
17771 // check node starting pos data set case if provided
17772 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
17774 if (node->map_id != GetMapId() ||
17775 (node->x - GetPositionX())*(node->x - GetPositionX())+
17776 (node->y - GetPositionY())*(node->y - GetPositionY())+
17777 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
17778 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
17780 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17781 data << uint32(ERR_TAXITOOFARAWAY);
17782 GetSession()->SendPacket(&data);
17783 return false;
17786 // node must have pos if taxi master case (npc != NULL)
17787 else if (npc)
17789 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17790 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17791 GetSession()->SendPacket(&data);
17792 return false;
17795 // Prepare to flight start now
17797 // stop combat at start taxi flight if any
17798 CombatStop();
17800 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17801 TradeCancel(true);
17803 // clean not finished taxi path if any
17804 m_taxi.ClearTaxiDestinations();
17806 // 0 element current node
17807 m_taxi.AddTaxiDestination(sourcenode);
17809 // fill destinations path tail
17810 uint32 sourcepath = 0;
17811 uint32 totalcost = 0;
17813 uint32 prevnode = sourcenode;
17814 uint32 lastnode = 0;
17816 for(uint32 i = 1; i < nodes.size(); ++i)
17818 uint32 path, cost;
17820 lastnode = nodes[i];
17821 sObjectMgr.GetTaxiPath(prevnode, lastnode, path, cost);
17823 if(!path)
17825 m_taxi.ClearTaxiDestinations();
17826 return false;
17829 totalcost += cost;
17831 if(prevnode == sourcenode)
17832 sourcepath = path;
17834 m_taxi.AddTaxiDestination(lastnode);
17836 prevnode = lastnode;
17839 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
17840 uint32 mount_display_id = sObjectMgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
17842 // in spell case allow 0 model
17843 if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
17845 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17846 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17847 GetSession()->SendPacket(&data);
17848 m_taxi.ClearTaxiDestinations();
17849 return false;
17852 uint32 money = GetMoney();
17854 if (npc)
17855 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17857 if(money < totalcost)
17859 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17860 data << uint32(ERR_TAXINOTENOUGHMONEY);
17861 GetSession()->SendPacket(&data);
17862 m_taxi.ClearTaxiDestinations();
17863 return false;
17866 //Checks and preparations done, DO FLIGHT
17867 ModifyMoney(-(int32)totalcost);
17868 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
17869 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
17871 // prevent stealth flight
17872 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17874 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17875 data << uint32(ERR_TAXIOK);
17876 GetSession()->SendPacket(&data);
17878 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17880 GetSession()->SendDoFlight(mount_display_id, sourcepath);
17882 return true;
17885 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
17887 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
17888 if(!entry)
17889 return false;
17891 std::vector<uint32> nodes;
17893 nodes.resize(2);
17894 nodes[0] = entry->from;
17895 nodes[1] = entry->to;
17897 return ActivateTaxiPathTo(nodes,NULL,spellid);
17900 void Player::ContinueTaxiFlight()
17902 uint32 sourceNode = m_taxi.GetTaxiSource();
17903 if (!sourceNode)
17904 return;
17906 sLog.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
17908 uint32 mountDisplayId = sObjectMgr.GetTaxiMountDisplayId(sourceNode, GetTeam(),true);
17909 uint32 path = m_taxi.GetCurrentTaxiPath();
17911 // search appropriate start path node
17912 uint32 startNode = 0;
17914 TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
17916 float distPrev = MAP_SIZE*MAP_SIZE;
17917 float distNext =
17918 (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
17919 (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
17920 (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
17922 for(uint32 i = 1; i < nodeList.size(); ++i)
17924 TaxiPathNode const& node = nodeList[i];
17925 TaxiPathNode const& prevNode = nodeList[i-1];
17927 // skip nodes at another map
17928 if(node.mapid != GetMapId())
17929 continue;
17931 distPrev = distNext;
17933 distNext =
17934 (node.x-GetPositionX())*(node.x-GetPositionX())+
17935 (node.y-GetPositionY())*(node.y-GetPositionY())+
17936 (node.z-GetPositionZ())*(node.z-GetPositionZ());
17938 float distNodes =
17939 (node.x-prevNode.x)*(node.x-prevNode.x)+
17940 (node.y-prevNode.y)*(node.y-prevNode.y)+
17941 (node.z-prevNode.z)*(node.z-prevNode.z);
17943 if(distNext + distPrev < distNodes)
17945 startNode = i;
17946 break;
17950 GetSession()->SendDoFlight(mountDisplayId, path, startNode);
17953 void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17955 // last check 2.0.10
17956 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17957 data << uint64(GetGUID());
17958 data << uint8(0x0); // flags (0x1, 0x2)
17959 time_t curTime = time(NULL);
17960 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17962 if (itr->second.state == PLAYERSPELL_REMOVED)
17963 continue;
17964 uint32 unSpellId = itr->first;
17965 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17966 if (!spellInfo)
17968 ASSERT(spellInfo);
17969 continue;
17972 // Not send cooldown for this spells
17973 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17974 continue;
17976 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17978 data << uint32(unSpellId);
17979 data << uint32(unTimeMs); // in m.secs
17980 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17983 GetSession()->SendPacket(&data);
17986 void Player::InitDataForForm(bool reapplyMods)
17988 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17989 if(ssEntry && ssEntry->attackSpeed)
17991 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17992 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17993 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17995 else
17996 SetRegularAttackTime();
17998 switch(m_form)
18000 case FORM_CAT:
18002 if(getPowerType()!=POWER_ENERGY)
18003 setPowerType(POWER_ENERGY);
18004 break;
18006 case FORM_BEAR:
18007 case FORM_DIREBEAR:
18009 if(getPowerType()!=POWER_RAGE)
18010 setPowerType(POWER_RAGE);
18011 break;
18013 default: // 0, for example
18015 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
18016 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
18017 setPowerType(Powers(cEntry->powerType));
18018 break;
18022 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
18023 if (!reapplyMods)
18024 UpdateEquipSpellsAtFormChange();
18026 UpdateAttackPowerAndDamage();
18027 UpdateAttackPowerAndDamage(true);
18030 void Player::InitDisplayIds()
18032 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
18033 if(!info)
18035 sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
18036 return;
18039 uint8 gender = getGender();
18040 switch(gender)
18042 case GENDER_FEMALE:
18043 SetDisplayId(info->displayId_f );
18044 SetNativeDisplayId(info->displayId_f );
18045 break;
18046 case GENDER_MALE:
18047 SetDisplayId(info->displayId_m );
18048 SetNativeDisplayId(info->displayId_m );
18049 break;
18050 default:
18051 sLog.outError("Invalid gender %u for player",gender);
18052 return;
18056 // Return true is the bought item has a max count to force refresh of window by caller
18057 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot)
18059 // cheating attempt
18060 if (count < 1) count = 1;
18062 if (!isAlive())
18063 return false;
18065 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
18066 if (!pProto)
18068 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
18069 return false;
18072 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
18073 if (!pCreature)
18075 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
18076 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
18077 return false;
18080 VendorItemData const* vItems = pCreature->GetVendorItems();
18081 if(!vItems || vItems->Empty())
18083 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
18084 return false;
18087 size_t vendor_slot = vItems->FindItemSlot(item);
18088 if (vendor_slot >= vItems->GetItemCount())
18090 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
18091 return false;
18094 VendorItem const* crItem = vItems->m_items[vendor_slot];
18096 // check current item amount if it limited
18097 if (crItem->maxcount != 0)
18099 if (pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
18101 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
18102 return false;
18106 if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
18108 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
18109 return false;
18112 if (crItem->ExtendedCost)
18114 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
18115 if (!iece)
18117 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
18118 return false;
18121 // honor points price
18122 if (GetHonorPoints() < (iece->reqhonorpoints * count))
18124 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
18125 return false;
18128 // arena points price
18129 if (GetArenaPoints() < (iece->reqarenapoints * count))
18131 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
18132 return false;
18135 // item base price
18136 for (uint8 i = 0; i < 5; ++i)
18138 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
18140 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
18141 return false;
18145 // check for personal arena rating requirement
18146 if( GetMaxPersonalArenaRatingRequirement(iece->reqarenaslot) < iece->reqpersonalarenarating )
18148 // probably not the proper equip err
18149 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
18150 return false;
18154 uint32 price = pProto->BuyPrice * count;
18156 // reputation discount
18157 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
18159 if (GetMoney() < price)
18161 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
18162 return false;
18165 if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
18167 ItemPosCountVec dest;
18168 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
18169 if (msg != EQUIP_ERR_OK)
18171 SendEquipError( msg, NULL, NULL, item );
18172 return false;
18175 ModifyMoney( -(int32)price );
18176 if (crItem->ExtendedCost) // case for new honor system
18178 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
18179 if (iece->reqhonorpoints)
18180 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
18181 if (iece->reqarenapoints)
18182 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
18183 for (uint8 i = 0; i < 5; ++i)
18185 if (iece->reqitem[i])
18186 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
18190 if (Item *it = StoreNewItem( dest, item, true ))
18192 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
18194 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
18195 data << uint64(pCreature->GetGUID());
18196 data << uint32(vendor_slot+1); // numbered from 1 at client
18197 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
18198 data << uint32(count);
18199 GetSession()->SendPacket(&data);
18201 SendNewItem(it, pProto->BuyCount*count, true, false, false);
18204 else if (IsEquipmentPos(bag, slot))
18206 if (pProto->BuyCount * count != 1)
18208 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
18209 return false;
18212 uint16 dest;
18213 uint8 msg = CanEquipNewItem( slot, dest, item, false );
18214 if (msg != EQUIP_ERR_OK)
18216 SendEquipError( msg, NULL, NULL, item );
18217 return false;
18220 ModifyMoney( -(int32)price );
18221 if (crItem->ExtendedCost) // case for new honor system
18223 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
18224 if (iece->reqhonorpoints)
18225 ModifyHonorPoints( - int32(iece->reqhonorpoints));
18226 if (iece->reqarenapoints)
18227 ModifyArenaPoints( - int32(iece->reqarenapoints));
18228 for (uint8 i = 0; i < 5; ++i)
18230 if(iece->reqitem[i])
18231 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
18235 if (Item *it = EquipNewItem( dest, item, true ))
18237 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
18239 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
18240 data << uint64(pCreature->GetGUID());
18241 data << uint32(vendor_slot + 1); // numbered from 1 at client
18242 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
18243 data << uint32(count);
18244 GetSession()->SendPacket(&data);
18246 SendNewItem(it, pProto->BuyCount*count, true, false, false);
18248 AutoUnequipOffhandIfNeed();
18251 else
18253 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
18254 return false;
18257 return crItem->maxcount != 0;
18260 uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot)
18262 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
18263 // the personal rating of the arena team must match the required limit as well
18264 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
18265 uint32 max_personal_rating = 0;
18266 for(int i = minarenaslot; i < MAX_ARENA_SLOT; ++i)
18268 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(GetArenaTeamId(i)))
18270 uint32 p_rating = GetArenaPersonalRating(i);
18271 uint32 t_rating = at->GetRating();
18272 p_rating = p_rating < t_rating ? p_rating : t_rating;
18273 if(max_personal_rating < p_rating)
18274 max_personal_rating = p_rating;
18277 return max_personal_rating;
18280 void Player::UpdateHomebindTime(uint32 time)
18282 // GMs never get homebind timer online
18283 if (m_InstanceValid || isGameMaster())
18285 if(m_HomebindTimer) // instance valid, but timer not reset
18287 // hide reminder
18288 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
18289 data << uint32(0);
18290 data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
18291 GetSession()->SendPacket(&data);
18293 // instance is valid, reset homebind timer
18294 m_HomebindTimer = 0;
18296 else if (m_HomebindTimer > 0)
18298 if (time >= m_HomebindTimer)
18300 // teleport to nearest graveyard
18301 RepopAtGraveyard();
18303 else
18304 m_HomebindTimer -= time;
18306 else
18308 // instance is invalid, start homebind timer
18309 m_HomebindTimer = 60000;
18310 // send message to player
18311 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
18312 data << uint32(m_HomebindTimer);
18313 data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
18314 GetSession()->SendPacket(&data);
18315 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
18319 void Player::UpdatePvP(bool state, bool ovrride)
18321 if(!state || ovrride)
18323 SetPvP(state);
18324 pvpInfo.endTimer = 0;
18326 else
18328 if(pvpInfo.endTimer != 0)
18329 pvpInfo.endTimer = time(NULL);
18330 else
18331 SetPvP(state);
18335 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
18337 // init cooldown values
18338 uint32 cat = 0;
18339 int32 rec = -1;
18340 int32 catrec = -1;
18342 // some special item spells without correct cooldown in SpellInfo
18343 // cooldown information stored in item prototype
18344 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
18346 if(itemId)
18348 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
18350 for(int idx = 0; idx < 5; ++idx)
18352 if(proto->Spells[idx].SpellId == spellInfo->Id)
18354 cat = proto->Spells[idx].SpellCategory;
18355 rec = proto->Spells[idx].SpellCooldown;
18356 catrec = proto->Spells[idx].SpellCategoryCooldown;
18357 break;
18363 // if no cooldown found above then base at DBC data
18364 if(rec < 0 && catrec < 0)
18366 cat = spellInfo->Category;
18367 rec = spellInfo->RecoveryTime;
18368 catrec = spellInfo->CategoryRecoveryTime;
18371 time_t curTime = time(NULL);
18373 time_t catrecTime;
18374 time_t recTime;
18376 // overwrite time for selected category
18377 if(infinityCooldown)
18379 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
18380 // but not allow ignore until reset or re-login
18381 catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
18382 recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
18384 else
18386 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
18387 // prevent 0 cooldowns set by another way
18388 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
18389 rec = GetAttackTime(RANGED_ATTACK);
18391 // Now we have cooldown data (if found any), time to apply mods
18392 if(rec > 0)
18393 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
18395 if(catrec > 0)
18396 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
18398 // replace negative cooldowns by 0
18399 if (rec < 0) rec = 0;
18400 if (catrec < 0) catrec = 0;
18402 // no cooldown after applying spell mods
18403 if( rec == 0 && catrec == 0)
18404 return;
18406 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
18407 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
18410 // self spell cooldown
18411 if(recTime > 0)
18412 AddSpellCooldown(spellInfo->Id, itemId, recTime);
18414 // category spells
18415 if (cat && catrec > 0)
18417 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
18418 if(i_scstore != sSpellCategoryStore.end())
18420 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
18422 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
18423 continue;
18425 AddSpellCooldown(*i_scset, itemId, catrecTime);
18431 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
18433 SpellCooldown sc;
18434 sc.end = end_time;
18435 sc.itemid = itemid;
18436 m_spellCooldowns[spellid] = sc;
18439 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
18441 // start cooldowns at server side, if any
18442 AddSpellAndCategoryCooldowns(spellInfo, itemId, spell);
18444 // Send activate cooldown timer (possible 0) at client side
18445 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
18446 data << uint32(spellInfo->Id);
18447 data << uint64(GetGUID());
18448 SendDirectMessage(&data);
18451 void Player::UpdatePotionCooldown(Spell* spell)
18453 // no potion used i combat or still in combat
18454 if(!m_lastPotionId || isInCombat())
18455 return;
18457 // Call not from spell cast, send cooldown event for item spells if no in combat
18458 if(!spell)
18460 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
18461 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
18462 for(int idx = 0; idx < 5; ++idx)
18463 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
18464 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
18465 SendCooldownEvent(spellInfo,m_lastPotionId);
18467 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
18468 else
18469 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
18471 m_lastPotionId = 0;
18474 //slot to be excluded while counting
18475 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
18477 if(!enchantmentcondition)
18478 return true;
18480 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
18482 if(!Condition)
18483 return true;
18485 uint8 curcount[4] = {0, 0, 0, 0};
18487 //counting current equipped gem colors
18488 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
18490 if(i == slot)
18491 continue;
18492 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
18493 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
18495 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18497 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18498 if(!enchant_id)
18499 continue;
18501 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18502 if(!enchantEntry)
18503 continue;
18505 uint32 gemid = enchantEntry->GemID;
18506 if(!gemid)
18507 continue;
18509 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
18510 if(!gemProto)
18511 continue;
18513 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
18514 if(!gemProperty)
18515 continue;
18517 uint8 GemColor = gemProperty->color;
18519 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
18521 if(tmpcolormask & GemColor)
18522 ++curcount[b];
18528 bool activate = true;
18530 for(int i = 0; i < 5; ++i)
18532 if(!Condition->Color[i])
18533 continue;
18535 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
18537 // if have <CompareColor> use them as count, else use <value> from Condition
18538 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
18540 switch(Condition->Comparator[i])
18542 case 2: // requires less <color> than (<value> || <comparecolor>) gems
18543 activate &= (_cur_gem < _cmp_gem) ? true : false;
18544 break;
18545 case 3: // requires more <color> than (<value> || <comparecolor>) gems
18546 activate &= (_cur_gem > _cmp_gem) ? true : false;
18547 break;
18548 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
18549 activate &= (_cur_gem >= _cmp_gem) ? true : false;
18550 break;
18554 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");
18556 return activate;
18559 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
18561 //cycle all equipped items
18562 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18564 //enchants for the slot being socketed are handled by Player::ApplyItemMods
18565 if(slot == exceptslot)
18566 continue;
18568 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18570 if(!pItem || !pItem->GetProto()->Socket[0].Color)
18571 continue;
18573 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18575 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18576 if(!enchant_id)
18577 continue;
18579 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18580 if(!enchantEntry)
18581 continue;
18583 uint32 condition = enchantEntry->EnchantmentCondition;
18584 if(condition)
18586 //was enchant active with/without item?
18587 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
18588 //should it now be?
18589 if(wasactive != EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
18591 // ignore item gem conditions
18592 //if state changed, (dis)apply enchant
18593 ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true);
18600 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
18601 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
18603 //cycle all equipped items
18604 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18606 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
18607 if(slot == exceptslot)
18608 continue;
18610 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18612 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
18613 continue;
18615 //cycle all (gem)enchants
18616 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18618 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18619 if(!enchant_id) //if no enchant go to next enchant(slot)
18620 continue;
18622 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18623 if(!enchantEntry)
18624 continue;
18626 //only metagems to be (de)activated, so only enchants with condition
18627 uint32 condition = enchantEntry->EnchantmentCondition;
18628 if(condition)
18629 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
18634 void Player::SetBattleGroundEntryPoint()
18636 // Taxi path store
18637 if (!m_taxi.empty())
18639 m_bgData.mountSpell = 0;
18640 m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
18641 m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
18643 // On taxi we don't need check for dungeon
18644 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18645 return;
18647 else
18649 m_bgData.ClearTaxiPath();
18651 // Mount spell id storing
18652 if (IsMounted())
18654 AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED);
18655 if (!auras.empty())
18656 m_bgData.mountSpell = (*auras.begin())->GetId();
18658 else
18659 m_bgData.mountSpell = 0;
18661 // If map is dungeon find linked graveyard
18662 if(GetMap()->IsDungeon())
18664 if (const WorldSafeLocsEntry* entry = sObjectMgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
18666 m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
18667 return;
18669 else
18670 sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
18672 // If new entry point is not BG or arena set it
18673 else if (!GetMap()->IsBattleGroundOrArena())
18675 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18676 return;
18680 // In error cases use homebind position
18681 m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
18684 void Player::LeaveBattleground(bool teleportToEntryPoint)
18686 if(BattleGround *bg = GetBattleGround())
18688 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
18690 // call after remove to be sure that player resurrected for correct cast
18691 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BOOL_BATTLEGROUND_CAST_DESERTER) )
18693 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
18695 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
18696 if(IsBeingTeleportedFar())
18698 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
18699 return;
18702 CastSpell(this, 26013, true); // Deserter
18708 bool Player::CanJoinToBattleground() const
18710 // check Deserter debuff
18711 if(GetDummyAura(26013))
18712 return false;
18714 return true;
18717 bool Player::CanReportAfkDueToLimit()
18719 // a player can complain about 15 people per 5 minutes
18720 if(m_bgData.bgAfkReportedCount++ >= 15)
18721 return false;
18723 return true;
18726 ///This player has been blamed to be inactive in a battleground
18727 void Player::ReportedAfkBy(Player* reporter)
18729 BattleGround *bg = GetBattleGround();
18730 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
18731 return;
18733 // check if player has 'Idle' or 'Inactive' debuff
18734 if(m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680, EFFECT_INDEX_0) && !HasAura(43681, EFFECT_INDEX_0) && reporter->CanReportAfkDueToLimit())
18736 m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
18737 // 3 players have to complain to apply debuff
18738 if(m_bgData.bgAfkReporter.size() >= 3)
18740 // cast 'Idle' spell
18741 CastSpell(this, 43680, true);
18742 m_bgData.bgAfkReporter.clear();
18747 WorldObject const* Player::GetViewPoint() const
18749 if(uint64 far_sight = GetFarSight())
18751 WorldObject const* viewPoint = GetMap()->GetWorldObject(far_sight);
18752 return viewPoint ? viewPoint : this; // always expected not NULL
18754 else
18755 return this;
18758 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
18760 // gamemaster in GM mode see all, including ghosts
18761 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
18762 return true;
18764 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
18765 if (InBattleGround())
18767 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
18768 return false;
18769 return true;
18772 // Live player see live player or dead player with not realized corpse
18773 if(pl->isAlive() || pl->m_deathTimer > 0)
18775 return isAlive() || m_deathTimer > 0;
18778 // Ghost see other friendly ghosts, that's for sure
18779 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
18780 return true;
18782 // Dead player see live players near own corpse
18783 if(isAlive())
18785 Corpse *corpse = pl->GetCorpse();
18786 if(corpse)
18788 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
18789 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO)))
18790 return true;
18794 // and not see any other
18795 return false;
18798 bool Player::IsVisibleGloballyFor( Player* u ) const
18800 if(!u)
18801 return false;
18803 // Always can see self
18804 if (u==this)
18805 return true;
18807 // Visible units, always are visible for all players
18808 if (GetVisibility() == VISIBILITY_ON)
18809 return true;
18811 // GMs are visible for higher gms (or players are visible for gms)
18812 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
18813 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
18815 // non faction visibility non-breakable for non-GMs
18816 if (GetVisibility() == VISIBILITY_OFF)
18817 return false;
18819 // non-gm stealth/invisibility not hide from global player lists
18820 return true;
18823 template<class T>
18824 inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/)
18828 template<>
18829 inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
18831 if (p->GetPetGUID()==t->GetGUID() && ((Creature*)t)->isPet())
18832 ((Pet*)t)->Remove(PET_SAVE_NOT_IN_SLOT, true);
18835 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target)
18837 if(HaveAtClient(target))
18839 if(!target->isVisibleForInState(this, viewPoint, true))
18841 if (target->GetTypeId()==TYPEID_UNIT)
18842 BeforeVisibilityDestroy<Creature>((Creature*)target,this);
18844 ObjectGuid t_guid = target->GetGUID();
18846 target->DestroyForPlayer(this);
18847 m_clientGUIDs.erase(t_guid);
18849 #ifdef MANGOS_DEBUG
18850 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18851 sLog.outDebug("%s out of range for player %u. Distance = %f",t_guid.GetString().c_str(),GetGUIDLow(),GetDistance(target));
18852 #endif
18855 else
18857 if(target->isVisibleForInState(this, viewPoint, false))
18859 target->SendCreateUpdateToPlayer(this);
18860 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
18861 m_clientGUIDs.insert(target->GetGUID());
18863 #ifdef MANGOS_DEBUG
18864 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18865 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18866 #endif
18868 // target aura duration for caster show only if target exist at caster client
18869 // send data at target visibility change (adding to client)
18870 if(target!=this && target->isType(TYPEMASK_UNIT))
18871 SendAurasForTarget((Unit*)target);
18873 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
18874 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18879 template<class T>
18880 inline void UpdateVisibilityOf_helper(ObjectGuidSet& s64, T* target)
18882 s64.insert(target->GetGUID());
18885 template<>
18886 inline void UpdateVisibilityOf_helper(ObjectGuidSet& s64, GameObject* target)
18888 if(!target->IsTransport())
18889 s64.insert(target->GetGUID());
18892 template<class T>
18893 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, UpdateDataMapType& /*data_updates*/, std::set<WorldObject*>& visibleNow)
18895 if(HaveAtClient(target))
18897 if(!target->isVisibleForInState(this,viewPoint,true))
18899 BeforeVisibilityDestroy<T>(target,this);
18901 ObjectGuid t_guid = target->GetGUID();
18903 target->BuildOutOfRangeUpdateBlock(&data);
18904 m_clientGUIDs.erase(t_guid);
18906 #ifdef MANGOS_DEBUG
18907 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18908 sLog.outDebug("%s is out of range for player %u. Distance = %f",t_guid.GetString().c_str(),GetGUIDLow(),GetDistance(target));
18909 #endif
18912 else
18914 if(target->isVisibleForInState(this,viewPoint,false))
18916 visibleNow.insert(target);
18917 target->BuildCreateUpdateBlockForPlayer(&data, this);
18918 UpdateVisibilityOf_helper(m_clientGUIDs,target);
18920 #ifdef MANGOS_DEBUG
18921 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18922 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));
18923 #endif
18928 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18929 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18930 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18931 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18932 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18934 void Player::InitPrimaryProfessions()
18936 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL));
18939 void Player::SendComboPoints()
18941 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
18942 if (combotarget)
18944 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
18945 data << combotarget->GetPackGUID();
18946 data << uint8(m_comboPoints);
18947 GetSession()->SendPacket(&data);
18951 void Player::AddComboPoints(Unit* target, int8 count)
18953 if(!count)
18954 return;
18956 // without combo points lost (duration checked in aura)
18957 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18959 if(target->GetGUID() == m_comboTarget)
18961 m_comboPoints += count;
18963 else
18965 if(m_comboTarget)
18966 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
18967 target2->RemoveComboPointHolder(GetGUIDLow());
18969 m_comboTarget = target->GetGUID();
18970 m_comboPoints = count;
18972 target->AddComboPointHolder(GetGUIDLow());
18975 if (m_comboPoints > 5) m_comboPoints = 5;
18976 if (m_comboPoints < 0) m_comboPoints = 0;
18978 SendComboPoints();
18981 void Player::ClearComboPoints()
18983 if(!m_comboTarget)
18984 return;
18986 // without combopoints lost (duration checked in aura)
18987 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18989 m_comboPoints = 0;
18991 SendComboPoints();
18993 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18994 target->RemoveComboPointHolder(GetGUIDLow());
18996 m_comboTarget = 0;
18999 void Player::SetGroup(Group *group, int8 subgroup)
19001 if(group == NULL)
19002 m_group.unlink();
19003 else
19005 // never use SetGroup without a subgroup unless you specify NULL for group
19006 assert(subgroup >= 0);
19007 m_group.link(group, this);
19008 m_group.setSubGroup((uint8)subgroup);
19012 void Player::SendInitialPacketsBeforeAddToMap()
19014 GetSocial()->SendSocialList();
19016 // Homebind
19017 WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
19018 data << m_homebindX << m_homebindY << m_homebindZ;
19019 data << (uint32) m_homebindMapId;
19020 data << (uint32) m_homebindAreaId;
19021 GetSession()->SendPacket(&data);
19023 // SMSG_SET_PROFICIENCY
19024 // SMSG_SET_PCT_SPELL_MODIFIER
19025 // SMSG_SET_FLAT_SPELL_MODIFIER
19027 SendTalentsInfoData(false);
19029 data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4+4);
19030 data << uint32(0);
19031 data << uint32(0);
19032 GetSession()->SendPacket(&data);
19034 SendInitialSpells();
19036 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
19037 data << uint32(0); // count, for(count) uint32;
19038 GetSession()->SendPacket(&data);
19040 SendInitialActionButtons();
19041 m_reputationMgr.SendInitialReputations();
19043 if(!isAlive())
19044 SendCorpseReclaimDelay(true);
19046 SendInitWorldStates(GetZoneId(), GetAreaId());
19048 SendEquipmentSetList();
19050 m_achievementMgr.SendAllAchievementData();
19052 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
19053 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
19054 data << (float)0.01666667f; // game speed
19055 data << uint32(0); // added in 3.1.2
19056 GetSession()->SendPacket( &data );
19058 // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
19059 // SMSG_PET_GUIDS
19060 // SMSG_POWER_UPDATE
19062 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
19063 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || HasAuraType(SPELL_AURA_FLY) || isInFlight())
19064 m_movementInfo.AddMovementFlag(MOVEFLAG_FLYING);
19066 m_mover = this;
19069 void Player::SendInitialPacketsAfterAddToMap()
19071 // update zone
19072 uint32 newzone, newarea;
19073 GetZoneAndAreaId(newzone,newarea);
19074 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
19076 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
19077 data << uint32(0x00000000); // on blizz it increments periodically
19078 GetSession()->SendPacket(&data);
19080 CastSpell(this, 836, true); // LOGINEFFECT
19082 // set some aura effects that send packet to player client after add player to map
19083 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
19084 // same auras state lost at far teleport, send it one more time in this case also
19085 static const AuraType auratypes[] =
19087 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
19088 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
19089 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
19091 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
19093 Unit::AuraList const& auraList = GetAurasByType(*itr);
19094 if(!auraList.empty())
19095 auraList.front()->ApplyModifier(true,true);
19098 if(HasAuraType(SPELL_AURA_MOD_STUN))
19099 SetMovement(MOVE_ROOT);
19101 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
19102 if(HasAuraType(SPELL_AURA_MOD_ROOT))
19104 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
19105 data2 << GetPackGUID();
19106 data2 << (uint32)2;
19107 SendMessageToSet(&data2,true);
19110 SendAurasForTarget(this);
19111 SendEnchantmentDurations(); // must be after add to map
19112 SendItemDurations(); // must be after add to map
19115 void Player::SendUpdateToOutOfRangeGroupMembers()
19117 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
19118 return;
19119 if(Group* group = GetGroup())
19120 group->UpdatePlayerOutOfRange(this);
19122 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
19123 m_auraUpdateMask = 0;
19124 if(Pet *pet = GetPet())
19125 pet->ResetAuraUpdateMask();
19128 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
19130 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
19131 data << uint32(mapid);
19132 data << uint8(reason); // transfer abort reason
19133 switch(reason)
19135 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
19136 case TRANSFER_ABORT_DIFFICULTY:
19137 case TRANSFER_ABORT_UNIQUE_MESSAGE:
19138 data << uint8(arg);
19139 break;
19141 GetSession()->SendPacket(&data);
19144 void Player::SendInstanceResetWarning( uint32 mapid, Difficulty difficulty, uint32 time )
19146 // type of warning, based on the time remaining until reset
19147 uint32 type;
19148 if(time > 3600)
19149 type = RAID_INSTANCE_WELCOME;
19150 else if(time > 900 && time <= 3600)
19151 type = RAID_INSTANCE_WARNING_HOURS;
19152 else if(time > 300 && time <= 900)
19153 type = RAID_INSTANCE_WARNING_MIN;
19154 else
19155 type = RAID_INSTANCE_WARNING_MIN_SOON;
19157 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
19158 data << uint32(type);
19159 data << uint32(mapid);
19160 data << uint32(difficulty); // difficulty
19161 data << uint32(time);
19162 if(type == RAID_INSTANCE_WELCOME)
19164 data << uint8(0); // is your (1)
19165 data << uint8(0); // is extended (1), ignored if prev field is 0
19167 GetSession()->SendPacket(&data);
19170 void Player::ApplyEquipCooldown( Item * pItem )
19172 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
19174 _Spell const& spellData = pItem->GetProto()->Spells[i];
19176 // no spell
19177 if( !spellData.SpellId )
19178 continue;
19180 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
19181 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
19182 continue;
19184 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
19186 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
19187 data << pItem->GetGUID();
19188 data << uint32(spellData.SpellId);
19189 GetSession()->SendPacket(&data);
19193 void Player::resetSpells()
19195 // not need after this call
19196 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
19197 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
19199 // make full copy of map (spells removed and marked as deleted at another spell remove
19200 // and we can't use original map for safe iterative with visit each spell at loop end
19201 PlayerSpellMap smap = GetSpellMap();
19203 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
19204 removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
19206 learnDefaultSpells();
19207 learnQuestRewardedSpells();
19210 void Player::learnDefaultSpells()
19212 // learn default race/class spells
19213 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(),getClass());
19214 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
19216 uint32 tspell = *itr;
19217 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
19218 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
19219 addSpell(tspell,true,true,true,false);
19220 else // but send in normal spell in game learn case
19221 learnSpell(tspell,true);
19225 void Player::learnQuestRewardedSpells(Quest const* quest)
19227 uint32 spell_id = quest->GetRewSpellCast();
19229 // skip quests without rewarded spell
19230 if( !spell_id )
19231 return;
19233 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
19234 if(!spellInfo)
19235 return;
19237 // check learned spells state
19238 bool found = false;
19239 for(int i=0; i < MAX_EFFECT_INDEX; ++i)
19241 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
19243 found = true;
19244 break;
19248 // skip quests with not teaching spell or already known spell
19249 if(!found)
19250 return;
19252 // prevent learn non first rank unknown profession and second specialization for same profession)
19253 uint32 learned_0 = spellInfo->EffectTriggerSpell[EFFECT_INDEX_0];
19254 if( sSpellMgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
19256 // not have first rank learned (unlearned prof?)
19257 uint32 first_spell = sSpellMgr.GetFirstSpellInChain(learned_0);
19258 if( !HasSpell(first_spell) )
19259 return;
19261 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
19262 if(!learnedInfo)
19263 return;
19265 // specialization
19266 if (learnedInfo->Effect[EFFECT_INDEX_0] == SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[EFFECT_INDEX_1] == 0)
19268 // search other specialization for same prof
19269 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
19271 if(itr->second.state == PLAYERSPELL_REMOVED || itr->first==learned_0)
19272 continue;
19274 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
19275 if(!itrInfo)
19276 return;
19278 // compare only specializations
19279 if (itrInfo->Effect[EFFECT_INDEX_0] != SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[EFFECT_INDEX_1] != 0)
19280 continue;
19282 // compare same chain spells
19283 if(sSpellMgr.GetFirstSpellInChain(itr->first) != first_spell)
19284 continue;
19286 // now we have 2 specialization, learn possible only if found is lesser specialization rank
19287 if(!sSpellMgr.IsHighRankOfSpell(learned_0,itr->first))
19288 return;
19293 CastSpell( this, spell_id, true);
19296 void Player::learnQuestRewardedSpells()
19298 // learn spells received from quest completing
19299 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
19301 // skip no rewarded quests
19302 if(!itr->second.m_rewarded)
19303 continue;
19305 Quest const* quest = sObjectMgr.GetQuestTemplate(itr->first);
19306 if( !quest )
19307 continue;
19309 learnQuestRewardedSpells(quest);
19313 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
19315 uint32 raceMask = getRaceMask();
19316 uint32 classMask = getClassMask();
19317 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
19319 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
19320 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
19321 continue;
19322 // Check race if set
19323 if (pAbility->racemask && !(pAbility->racemask & raceMask))
19324 continue;
19325 // Check class if set
19326 if (pAbility->classmask && !(pAbility->classmask & classMask))
19327 continue;
19329 if (sSpellStore.LookupEntry(pAbility->spellId))
19331 // need unlearn spell
19332 if (skill_value < pAbility->req_skill_value)
19333 removeSpell(pAbility->spellId);
19334 // need learn
19335 else if (!IsInWorld())
19336 addSpell(pAbility->spellId,true,true,true,false);
19337 else
19338 learnSpell(pAbility->spellId,true);
19343 void Player::SendAurasForTarget(Unit *target)
19345 if(target->GetVisibleAuras()->empty()) // speedup things
19346 return;
19348 WorldPacket data(SMSG_AURA_UPDATE_ALL);
19349 data << target->GetPackGUID();
19351 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
19352 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
19354 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
19356 if(Aura *aura = target->GetAura(itr->second, SpellEffectIndex(j)))
19358 data << uint8(aura->GetAuraSlot());
19359 data << uint32(aura->GetId());
19361 if(aura->GetId())
19363 uint8 auraFlags = aura->GetAuraFlags();
19364 // flags
19365 data << uint8(auraFlags);
19366 // level
19367 data << uint8(aura->GetAuraLevel());
19368 // charges
19369 if (aura->GetAuraCharges())
19370 data << uint8(aura->GetAuraCharges() * aura->GetStackAmount());
19371 else
19372 data << uint8(aura->GetStackAmount());
19374 if(!(auraFlags & AFLAG_NOT_CASTER))
19376 data << uint8(0); // packed GUID of someone (caster?)
19379 if(auraFlags & AFLAG_DURATION) // include aura duration
19381 data << uint32(aura->GetAuraMaxDuration());
19382 data << uint32(aura->GetAuraDuration());
19385 break;
19390 GetSession()->SendPacket(&data);
19393 void Player::SetDailyQuestStatus( uint32 quest_id )
19395 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19397 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
19399 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
19400 m_lastDailyQuestTime = time(NULL); // last daily quest time
19401 m_DailyQuestChanged = true;
19402 break;
19407 void Player::ResetDailyQuestStatus()
19409 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19410 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
19412 // DB data deleted in caller
19413 m_DailyQuestChanged = false;
19414 m_lastDailyQuestTime = 0;
19417 BattleGround* Player::GetBattleGround() const
19419 if(GetBattleGroundId()==0)
19420 return NULL;
19422 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
19425 bool Player::InArena() const
19427 BattleGround *bg = GetBattleGround();
19428 if(!bg || !bg->isArena())
19429 return false;
19431 return true;
19434 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
19436 // get a template bg instead of running one
19437 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
19438 if(!bg)
19439 return false;
19441 // limit check leel to dbc compatible level range
19442 uint32 level = getLevel();
19443 if (level > DEFAULT_MAX_LEVEL)
19444 level = DEFAULT_MAX_LEVEL;
19446 if(level < bg->GetMinLevel() || level > bg->GetMaxLevel())
19447 return false;
19449 return true;
19452 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
19454 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
19455 if(!vendor_faction || !vendor_faction->faction)
19456 return 1.0f;
19458 ReputationRank rank = GetReputationRank(vendor_faction->faction);
19459 if(rank <= REP_NEUTRAL)
19460 return 1.0f;
19462 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
19465 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
19467 uint32 racemask = getRaceMask();
19468 uint32 classmask = getClassMask();
19470 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
19471 if (bounds.first==bounds.second)
19472 return true;
19474 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
19476 // skip wrong race skills
19477 if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
19478 continue;
19480 // skip wrong class skills
19481 if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
19482 continue;
19484 return true;
19487 return false;
19490 bool Player::HasQuestForGO(int32 GOId) const
19492 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
19494 uint32 questid = GetQuestSlotQuestId(i);
19495 if ( questid == 0 )
19496 continue;
19498 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
19499 if(qs_itr == mQuestStatus.end())
19500 continue;
19502 QuestStatusData const& qs = qs_itr->second;
19504 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
19506 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
19507 if(!qinfo)
19508 continue;
19510 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
19511 continue;
19513 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
19515 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
19516 continue;
19518 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
19519 return true;
19523 return false;
19526 void Player::UpdateForQuestWorldObjects()
19528 if(m_clientGUIDs.empty())
19529 return;
19531 UpdateData udata;
19532 WorldPacket packet;
19533 for(ObjectGuidSet::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
19535 if (itr->IsGameobject())
19537 if (GameObject *obj = GetMap()->GetGameObject(*itr))
19538 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
19540 else if (itr->IsCreatureOrVehicle())
19542 Creature *obj = GetMap()->GetCreatureOrPetOrVehicle(*itr);
19543 if(!obj)
19544 continue;
19546 // check if this unit requires quest specific flags
19547 if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
19548 continue;
19550 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(obj->GetEntry());
19551 for(SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
19553 if(_itr->second.questStart || _itr->second.questEnd)
19555 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
19556 break;
19561 udata.BuildPacket(&packet);
19562 GetSession()->SendPacket(&packet);
19565 void Player::SummonIfPossible(bool agree)
19567 if(!agree)
19569 m_summon_expire = 0;
19570 return;
19573 // expire and auto declined
19574 if(m_summon_expire < time(NULL))
19575 return;
19577 // stop taxi flight at summon
19578 if(isInFlight())
19580 GetMotionMaster()->MovementExpired();
19581 m_taxi.ClearTaxiDestinations();
19584 // drop flag at summon
19585 // 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
19586 if(BattleGround *bg = GetBattleGround())
19587 bg->EventPlayerDroppedFlag(this);
19589 m_summon_expire = 0;
19591 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
19593 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
19596 void Player::RemoveItemDurations( Item *item )
19598 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
19600 if(*itr==item)
19602 m_itemDuration.erase(itr);
19603 break;
19608 void Player::AddItemDurations( Item *item )
19610 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
19612 m_itemDuration.push_back(item);
19613 item->SendTimeUpdate(this);
19617 void Player::AutoUnequipOffhandIfNeed()
19619 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
19620 if(!offItem)
19621 return;
19623 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
19624 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
19625 return;
19627 ItemPosCountVec off_dest;
19628 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
19629 if( off_msg == EQUIP_ERR_OK )
19631 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19632 StoreItem( off_dest, offItem, true );
19634 else
19636 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19637 CharacterDatabase.BeginTransaction();
19638 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
19639 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
19640 CharacterDatabase.CommitTransaction();
19642 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
19643 MailDraft(subject).AddItem(offItem).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
19647 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
19649 if(spellInfo->EquippedItemClass < 0)
19650 return true;
19652 // scan other equipped items for same requirements (mostly 2 daggers/etc)
19653 // for optimize check 2 used cases only
19654 switch(spellInfo->EquippedItemClass)
19656 case ITEM_CLASS_WEAPON:
19658 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
19659 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19660 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19661 return true;
19662 break;
19664 case ITEM_CLASS_ARMOR:
19666 // tabard not have dependent spells
19667 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
19668 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19669 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19670 return true;
19672 // shields can be equipped to offhand slot
19673 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
19674 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19675 return true;
19677 // ranged slot can have some armor subclasses
19678 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
19679 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19680 return true;
19682 break;
19684 default:
19685 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
19686 break;
19689 return false;
19692 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
19694 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
19695 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
19696 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
19697 return true;
19699 // Check no reagent use mask
19700 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
19701 uint32 noReagentMask_2 = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+2);
19702 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
19703 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
19704 return true;
19706 return false;
19709 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
19711 AuraMap& auras = GetAuras();
19712 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
19714 Aura* aura = itr->second;
19716 // skip passive (passive item dependent spells work in another way) and not self applied auras
19717 SpellEntry const* spellInfo = aura->GetSpellProto();
19718 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
19720 ++itr;
19721 continue;
19724 // skip if not item dependent or have alternative item
19725 if(HasItemFitToSpellReqirements(spellInfo,pItem))
19727 ++itr;
19728 continue;
19731 // no alt item, remove aura, restart check
19732 RemoveAurasDueToSpell(aura->GetId());
19733 itr = auras.begin();
19736 // currently casted spells can be dependent from item
19737 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
19738 if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
19739 if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
19740 InterruptSpell(CurrentSpellTypes(i));
19743 uint32 Player::GetResurrectionSpellId()
19745 // search priceless resurrection possibilities
19746 uint32 prio = 0;
19747 uint32 spell_id = 0;
19748 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
19749 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
19751 // Soulstone Resurrection // prio: 3 (max, non death persistent)
19752 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
19754 switch((*itr)->GetId())
19756 case 20707: spell_id = 3026; break; // rank 1
19757 case 20762: spell_id = 20758; break; // rank 2
19758 case 20763: spell_id = 20759; break; // rank 3
19759 case 20764: spell_id = 20760; break; // rank 4
19760 case 20765: spell_id = 20761; break; // rank 5
19761 case 27239: spell_id = 27240; break; // rank 6
19762 case 47883: spell_id = 47882; break; // rank 7
19763 default:
19764 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
19765 continue;
19768 prio = 3;
19770 // Twisting Nether // prio: 2 (max)
19771 else if((*itr)->GetId()==23701 && roll_chance_i(10))
19773 prio = 2;
19774 spell_id = 23700;
19778 // Reincarnation (passive spell) // prio: 1
19779 // Glyph of Renewed Life remove reagent requiremnnt
19780 if (prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasItemCount(17030,1) || HasAura(58059, EFFECT_INDEX_0)))
19781 spell_id = 21169;
19783 return spell_id;
19786 // Used in triggers for check "Only to targets that grant experience or honor" req
19787 bool Player::isHonorOrXPTarget(Unit* pVictim) const
19789 uint32 v_level = pVictim->getLevel();
19790 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
19792 // Victim level less gray level
19793 if(v_level<=k_grey)
19794 return false;
19796 if(pVictim->GetTypeId() == TYPEID_UNIT)
19798 if (((Creature*)pVictim)->isTotem() ||
19799 ((Creature*)pVictim)->isPet() ||
19800 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
19801 return false;
19803 return true;
19806 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
19808 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
19810 // prepare data for near group iteration (PvP and !PvP cases)
19811 uint32 xp = 0;
19812 bool honored_kill = false;
19814 if(Group *pGroup = GetGroup())
19816 uint32 count = 0;
19817 uint32 sum_level = 0;
19818 Player* member_with_max_level = NULL;
19819 Player* not_gray_member_with_max_level = NULL;
19821 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
19823 if(member_with_max_level)
19825 /// not get Xp in PvP or no not gray players in group
19826 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
19828 /// skip in check PvP case (for speed, not used)
19829 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
19830 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
19831 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
19833 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19835 Player* pGroupGuy = itr->getSource();
19836 if(!pGroupGuy)
19837 continue;
19839 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
19840 continue; // member (alive or dead) or his corpse at req. distance
19842 // honor can be in PvP and !PvP (racial leader) cases (for alive)
19843 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
19844 honored_kill = true;
19846 // xp and reputation only in !PvP case
19847 if(!PvP)
19849 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
19851 // if is in dungeon then all receive full reputation at kill
19852 // rewarded any alive/dead/near_corpse group member
19853 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
19855 // XP updated only for alive group member
19856 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
19857 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
19859 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
19861 pGroupGuy->GiveXP(itr_xp, pVictim);
19862 if(Pet* pet = pGroupGuy->GetPet())
19863 pet->GivePetXP(itr_xp/2);
19866 // quest objectives updated only for alive group member or dead but with not released body
19867 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19869 // normal creature (not pet/etc) can be only in !PvP case
19870 if(pVictim->GetTypeId()==TYPEID_UNIT)
19871 pGroupGuy->KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19877 else // if (!pGroup)
19879 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
19881 // honor can be in PvP and !PvP (racial leader) cases
19882 if(RewardHonor(pVictim,1))
19883 honored_kill = true;
19885 // xp and reputation only in !PvP case
19886 if(!PvP)
19888 RewardReputation(pVictim,1);
19889 GiveXP(xp, pVictim);
19891 if(Pet* pet = GetPet())
19892 pet->GivePetXP(xp);
19894 // normal creature (not pet/etc) can be only in !PvP case
19895 if(pVictim->GetTypeId()==TYPEID_UNIT)
19896 KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19899 return xp || honored_kill;
19902 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
19904 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
19906 // prepare data for near group iteration
19907 if(Group *pGroup = GetGroup())
19909 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19911 Player* pGroupGuy = itr->getSource();
19912 if(!pGroupGuy)
19913 continue;
19915 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
19916 continue; // member (alive or dead) or his corpse at req. distance
19918 // quest objectives updated only for alive group member or dead but with not released body
19919 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19920 pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
19923 else // if (!pGroup)
19924 KilledMonsterCredit(creature_id, creature_guid);
19927 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
19929 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE)))
19930 return true;
19932 if (isAlive())
19933 return false;
19935 Corpse* corpse = GetCorpse();
19936 if (!corpse)
19937 return false;
19939 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE));
19942 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
19944 Item* item = GetWeaponForAttack(attType,true,true);
19946 // unarmed only with base attack
19947 if(attType != BASE_ATTACK && !item)
19948 return 0;
19950 // weapon skill or (unarmed for base attack)
19951 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
19952 return GetBaseSkillValue(skill);
19955 void Player::ResurectUsingRequestData()
19957 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
19958 if(IS_PLAYER_GUID(m_resurrectGUID))
19959 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
19961 //we cannot resurrect player when we triggered far teleport
19962 //player will be resurrected upon teleportation
19963 if(IsBeingTeleportedFar())
19965 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
19966 return;
19969 ResurrectPlayer(0.0f,false);
19971 if(GetMaxHealth() > m_resurrectHealth)
19972 SetHealth( m_resurrectHealth );
19973 else
19974 SetHealth( GetMaxHealth() );
19976 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
19977 SetPower(POWER_MANA, m_resurrectMana );
19978 else
19979 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
19981 SetPower(POWER_RAGE, 0 );
19983 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
19985 SpawnCorpseBones();
19988 void Player::SetClientControl(Unit* target, uint8 allowMove)
19990 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
19991 data << target->GetPackGUID();
19992 data << uint8(allowMove);
19993 GetSession()->SendPacket(&data);
19996 void Player::UpdateZoneDependentAuras( uint32 newZone )
19998 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19999 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newZone);
20000 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
20001 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
20002 if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
20003 CastSpell(this,itr->second->spellId,true);
20006 void Player::UpdateAreaDependentAuras( uint32 newArea )
20008 // remove auras from spells with area limitations
20009 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
20011 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
20012 if(sSpellMgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
20013 RemoveAura(iter);
20014 else
20015 ++iter;
20018 // some auras applied at subzone enter
20019 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newArea);
20020 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
20021 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
20022 if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
20023 CastSpell(this,itr->second->spellId,true);
20026 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
20028 if ((pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
20029 (!pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
20031 return copseReclaimDelay[0];
20034 time_t now = time(NULL);
20035 // 0..2 full period
20036 uint32 count = (now < m_deathExpireTime) ? uint32((m_deathExpireTime - now)/DEATH_EXPIRE_STEP) : 0;
20037 return copseReclaimDelay[count];
20040 void Player::UpdateCorpseReclaimDelay()
20042 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
20044 if ((pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
20045 (!pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
20046 return;
20048 time_t now = time(NULL);
20049 if(now < m_deathExpireTime)
20051 // full and partly periods 1..3
20052 uint32 count = uint32((m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1);
20053 if(count < MAX_DEATH_COUNT)
20054 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
20055 else
20056 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
20058 else
20059 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
20062 void Player::SendCorpseReclaimDelay(bool load)
20064 Corpse* corpse = GetCorpse();
20065 if(!corpse)
20066 return;
20068 uint32 delay;
20069 if(load)
20071 if(corpse->GetGhostTime() > m_deathExpireTime)
20072 return;
20074 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
20076 uint32 count;
20077 if( pvp && sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
20078 !pvp && sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
20080 count = uint32(m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
20081 if(count>=MAX_DEATH_COUNT)
20082 count = MAX_DEATH_COUNT-1;
20084 else
20085 count=0;
20087 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
20089 time_t now = time(NULL);
20090 if(now >= expected_time)
20091 return;
20093 delay = uint32(expected_time-now);
20095 else
20096 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
20098 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
20099 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
20100 data << uint32(delay*IN_MILISECONDS);
20101 GetSession()->SendPacket( &data );
20104 Player* Player::GetNextRandomRaidMember(float radius)
20106 Group *pGroup = GetGroup();
20107 if(!pGroup)
20108 return NULL;
20110 std::vector<Player*> nearMembers;
20111 nearMembers.reserve(pGroup->GetMembersCount());
20113 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
20115 Player* Target = itr->getSource();
20117 // IsHostileTo check duel and controlled by enemy
20118 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
20119 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
20120 nearMembers.push_back(Target);
20123 if (nearMembers.empty())
20124 return NULL;
20126 uint32 randTarget = urand(0,nearMembers.size()-1);
20127 return nearMembers[randTarget];
20130 PartyResult Player::CanUninviteFromGroup() const
20132 const Group* grp = GetGroup();
20133 if(!grp)
20134 return PARTY_RESULT_YOU_NOT_IN_GROUP;
20136 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
20137 return PARTY_RESULT_YOU_NOT_LEADER;
20139 if(InBattleGround())
20140 return PARTY_RESULT_INVITE_RESTRICTED;
20142 return PARTY_RESULT_OK;
20145 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
20147 //we must move references from m_group to m_originalGroup
20148 SetOriginalGroup(GetGroup(), GetSubGroup());
20150 m_group.unlink();
20151 m_group.link(group, this);
20152 m_group.setSubGroup((uint8)subgroup);
20155 void Player::RemoveFromBattleGroundRaid()
20157 //remove existing reference
20158 m_group.unlink();
20159 if( Group* group = GetOriginalGroup() )
20161 m_group.link(group, this);
20162 m_group.setSubGroup(GetOriginalSubGroup());
20164 SetOriginalGroup(NULL);
20167 void Player::SetOriginalGroup(Group *group, int8 subgroup)
20169 if( group == NULL )
20170 m_originalGroup.unlink();
20171 else
20173 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
20174 assert(subgroup >= 0);
20175 m_originalGroup.link(group, this);
20176 m_originalGroup.setSubGroup((uint8)subgroup);
20180 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
20182 LiquidData liquid_status;
20183 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
20184 if (!res)
20186 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
20187 // Small hack for enable breath in WMO
20188 if (IsInWater())
20189 m_MirrorTimerFlags|=UNDERWATER_INWATER;
20190 return;
20193 // All liquids type - check under water position
20194 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
20196 if ( res & LIQUID_MAP_UNDER_WATER)
20197 m_MirrorTimerFlags |= UNDERWATER_INWATER;
20198 else
20199 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
20202 // Allow travel in dark water on taxi or transport
20203 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
20204 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
20205 else
20206 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
20208 // in lava check, anywhere in lava level
20209 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
20211 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
20212 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
20213 else
20214 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
20216 // in slime check, anywhere in slime level
20217 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
20219 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
20220 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
20221 else
20222 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
20226 void Player::SetCanParry( bool value )
20228 if(m_canParry==value)
20229 return;
20231 m_canParry = value;
20232 UpdateParryPercentage();
20235 void Player::SetCanBlock( bool value )
20237 if(m_canBlock==value)
20238 return;
20240 m_canBlock = value;
20241 UpdateBlockPercentage();
20244 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
20246 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
20247 if(itr->pos == pos)
20248 return true;
20250 return false;
20253 bool Player::CanUseBattleGroundObject()
20255 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
20256 // maybe gameobject code should handle that ForceReaction usage
20257 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
20258 return ( //InBattleGround() && // in battleground - not need, check in other cases
20259 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
20260 //player cannot use object when he is invulnerable (immune)
20261 !isTotalImmune() && // not totally immune
20262 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
20263 !HasStealthAura() && // not stealthed
20264 !HasInvisibilityAura() && // not invisible
20265 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, EFFECT_INDEX_0) &&// can't pickup
20266 isAlive() // live player
20270 bool Player::CanCaptureTowerPoint()
20272 return ( !HasStealthAura() && // not stealthed
20273 !HasInvisibilityAura() && // not invisible
20274 isAlive() // live player
20278 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
20280 uint32 level = getLevel();
20282 if(level > GT_MAX_LEVEL)
20283 level = GT_MAX_LEVEL; // max level in this dbc
20285 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
20286 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
20287 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
20289 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
20290 return 0;
20292 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
20294 if(!bsc) // shouldn't happen
20295 return 0xFFFFFFFF;
20297 float cost = 0;
20299 if(hairstyle != newhairstyle)
20300 cost += bsc->cost; // full price
20302 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
20303 cost += bsc->cost * 0.5f; // +1/2 of price
20305 if(facialhair != newfacialhair)
20306 cost += bsc->cost * 0.75f; // +3/4 of price
20308 return uint32(cost);
20311 void Player::InitGlyphsForLevel()
20313 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
20314 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
20315 if(gs->Order)
20316 SetGlyphSlot(gs->Order - 1, gs->Id);
20318 uint32 level = getLevel();
20319 uint32 value = 0;
20321 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
20322 if(level >= 15)
20323 value |= (0x01 | 0x02);
20324 if(level >= 30)
20325 value |= 0x08;
20326 if(level >= 50)
20327 value |= 0x04;
20328 if(level >= 70)
20329 value |= 0x10;
20330 if(level >= 80)
20331 value |= 0x20;
20333 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
20336 void Player::ApplyGlyph(uint8 slot, bool apply)
20338 if (uint32 glyph = GetGlyph(slot))
20340 if(GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
20342 if(apply)
20344 CastSpell(this, gp->SpellId, true);
20345 SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, glyph);
20347 else
20349 RemoveAurasDueToSpell(gp->SpellId);
20350 SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, 0);
20356 void Player::ApplyGlyphs(bool apply)
20358 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
20359 ApplyGlyph(i,apply);
20362 void Player::EnterVehicle(Vehicle *vehicle)
20364 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
20365 if(!ve)
20366 return;
20368 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
20369 if(!veSeat)
20370 return;
20372 vehicle->SetCharmerGUID(GetGUID());
20373 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20374 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20375 vehicle->setFaction(getFaction());
20377 SetCharm(vehicle); // charm
20378 SetFarSightGUID(vehicle->GetGUID()); // set view
20380 SetClientControl(vehicle, 1); // redirect controls to vehicle
20381 SetMover(vehicle);
20383 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
20384 GetSession()->SendPacket(&data);
20386 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
20387 data << GetPackGUID();
20388 data << uint32(0); // counter?
20389 data << uint32(MOVEFLAG_ONTRANSPORT); // transport
20390 data << uint16(0); // special flags
20391 data << uint32(getMSTime()); // time
20392 data << vehicle->GetPositionX(); // x
20393 data << vehicle->GetPositionY(); // y
20394 data << vehicle->GetPositionZ(); // z
20395 data << vehicle->GetOrientation(); // o
20396 // transport part, TODO: load/calculate seat offsets
20397 data << uint64(vehicle->GetGUID()); // transport guid
20398 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
20399 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
20400 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
20401 data << float(0); // transport orientation
20402 data << uint32(getMSTime()); // transport time
20403 data << uint8(0); // seat
20404 // end of transport part
20405 data << uint32(0); // fall time
20406 GetSession()->SendPacket(&data);
20408 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
20409 data << uint64(vehicle->GetGUID());
20410 data << uint16(0);
20411 data << uint32(0);
20412 data << uint32(0x00000101);
20414 for(uint32 i = 0; i < 10; ++i)
20415 data << uint16(0) << uint8(0) << uint8(i+8);
20417 data << uint8(0);
20418 data << uint8(0);
20419 GetSession()->SendPacket(&data);
20422 void Player::ExitVehicle(Vehicle *vehicle)
20424 vehicle->SetCharmerGUID(0);
20425 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20426 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20427 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
20429 SetCharm(NULL);
20430 SetFarSightGUID(0);
20432 SetClientControl(vehicle, 0);
20433 SetMover(NULL);
20435 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
20436 data << GetPackGUID();
20437 data << uint32(0); // counter?
20438 data << uint32(MOVEFLAG_ROOT); // fly unk
20439 data << uint16(MOVEFLAG2_UNK4); // special flags
20440 data << uint32(getMSTime()); // time
20441 data << vehicle->GetPositionX(); // x
20442 data << vehicle->GetPositionY(); // y
20443 data << vehicle->GetPositionZ(); // z
20444 data << vehicle->GetOrientation(); // o
20445 data << uint32(0); // fall time
20446 GetSession()->SendPacket(&data);
20448 RemovePetActionBar();
20450 // maybe called at dummy aura remove?
20451 // CastSpell(this, 45472, true); // Parachute
20454 bool Player::isTotalImmune()
20456 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
20458 uint32 immuneMask = 0;
20459 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
20461 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
20462 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
20463 return true;
20465 return false;
20468 bool Player::HasTitle(uint32 bitIndex)
20470 if (bitIndex > MAX_TITLE_INDEX)
20471 return false;
20473 uint32 fieldIndexOffset = bitIndex / 32;
20474 uint32 flag = 1 << (bitIndex % 32);
20475 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20478 void Player::SetTitle(CharTitlesEntry const* title, bool lost)
20480 uint32 fieldIndexOffset = title->bit_index / 32;
20481 uint32 flag = 1 << (title->bit_index % 32);
20483 if(lost)
20485 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20486 return;
20488 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20490 else
20492 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20493 return;
20495 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20498 WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
20499 data << uint32(title->bit_index);
20500 data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
20501 GetSession()->SendPacket(&data);
20504 void Player::ConvertRune(uint8 index, RuneType newType)
20506 SetCurrentRune(index, newType);
20508 WorldPacket data(SMSG_CONVERT_RUNE, 2);
20509 data << uint8(index);
20510 data << uint8(newType);
20511 GetSession()->SendPacket(&data);
20514 void Player::ResyncRunes(uint8 count)
20516 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
20517 for(uint32 i = 0; i < count; ++i)
20519 data << uint8(GetCurrentRune(i)); // rune type
20520 data << uint8(255 - ((GetRuneCooldown(i) / REGEN_TIME_FULL) * 51)); // passed cooldown time (0-255)
20522 GetSession()->SendPacket(&data);
20525 void Player::AddRunePower(uint8 index)
20527 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
20528 data << uint32(1 << index); // mask (0x00-0x3F probably)
20529 GetSession()->SendPacket(&data);
20532 static RuneType runeSlotTypes[MAX_RUNES] = {
20533 /*0*/ RUNE_BLOOD,
20534 /*1*/ RUNE_BLOOD,
20535 /*2*/ RUNE_UNHOLY,
20536 /*3*/ RUNE_UNHOLY,
20537 /*4*/ RUNE_FROST,
20538 /*5*/ RUNE_FROST
20541 void Player::InitRunes()
20543 if(getClass() != CLASS_DEATH_KNIGHT)
20544 return;
20546 m_runes = new Runes;
20548 m_runes->runeState = 0;
20550 for(uint32 i = 0; i < MAX_RUNES; ++i)
20552 SetBaseRune(i, runeSlotTypes[i]); // init base types
20553 SetCurrentRune(i, runeSlotTypes[i]); // init current types
20554 SetRuneCooldown(i, 0); // reset cooldowns
20555 m_runes->SetRuneState(i);
20558 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
20559 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
20563 bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType ) const
20565 for(uint32 i = 0; i < MAX_RUNES; ++i)
20566 if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
20567 return false;
20569 return true;
20572 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
20574 Loot loot;
20575 loot.FillLoot (loot_id,store,this,true);
20577 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
20578 for(uint32 i = 0; i < max_slot; ++i)
20580 LootItem* lootItem = loot.LootItemInSlot(i,this);
20582 ItemPosCountVec dest;
20583 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
20584 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
20585 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20586 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
20587 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20588 if(msg != EQUIP_ERR_OK)
20590 SendEquipError( msg, NULL, NULL, lootItem->itemid );
20591 continue;
20594 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
20595 SendNewItem(pItem, lootItem->count, false, false, broadcast);
20599 uint32 Player::CalculateTalentsPoints() const
20601 uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
20603 if(getClass() != CLASS_DEATH_KNIGHT)
20604 return uint32(base_talent * sWorld.getConfig(CONFIG_FLOAT_RATE_TALENT));
20606 uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
20607 talentPointsForLevel += m_questRewardTalentCount;
20609 if(talentPointsForLevel > base_talent)
20610 talentPointsForLevel = base_talent;
20612 return uint32(talentPointsForLevel * sWorld.getConfig(CONFIG_FLOAT_RATE_TALENT));
20615 bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
20617 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
20618 uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
20619 return v_map != 571 || HasSpell(54197); // Cold Weather Flying
20622 struct DoPlayerLearnSpell
20624 DoPlayerLearnSpell(Player& _player) : player(_player) {}
20625 void operator() (uint32 spell_id) { player.learnSpell(spell_id,false); }
20626 Player& player;
20629 void Player::learnSpellHighRank(uint32 spellid)
20631 learnSpell(spellid,false);
20633 DoPlayerLearnSpell worker(*this);
20634 sSpellMgr.doForHighRanks(spellid,worker);
20637 void Player::_LoadSkills(QueryResult *result)
20639 // 0 1 2
20640 // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
20642 uint32 count = 0;
20643 if (result)
20647 Field *fields = result->Fetch();
20649 uint16 skill = fields[0].GetUInt16();
20650 uint16 value = fields[1].GetUInt16();
20651 uint16 max = fields[2].GetUInt16();
20653 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(skill);
20654 if(!pSkill)
20656 sLog.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill);
20657 continue;
20660 // set fixed skill ranges
20661 switch(GetSkillRangeType(pSkill,false))
20663 case SKILL_RANGE_LANGUAGE: // 300..300
20664 value = max = 300;
20665 break;
20666 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
20667 value = max = 1;
20668 break;
20669 default:
20670 break;
20673 if(value == 0)
20675 sLog.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
20676 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill );
20677 continue;
20680 // enable unlearn button for primary professions only
20681 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
20682 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,1));
20683 else
20684 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,0));
20686 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),MAKE_SKILL_VALUE(value, max));
20687 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20689 mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
20691 learnSkillRewardedSpells(skill, value);
20693 ++count;
20695 if(count >= PLAYER_MAX_SKILLS) // client limit
20697 sLog.outError("Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS);
20698 break;
20700 } while (result->NextRow());
20701 delete result;
20704 for (; count < PLAYER_MAX_SKILLS; ++count)
20706 SetUInt32Value(PLAYER_SKILL_INDEX(count), 0);
20707 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),0);
20708 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20711 // special settings
20712 if(getClass()==CLASS_DEATH_KNIGHT)
20714 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL));
20715 if(base_level < 1)
20716 base_level = 1;
20717 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
20718 if(base_skill < 1)
20719 base_skill = 1; // skill mast be known and then > 0 in any case
20721 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
20722 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
20723 if(GetPureSkillValue (SKILL_AXES) < base_skill)
20724 SetSkill(SKILL_AXES, base_skill,base_skill);
20725 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
20726 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
20727 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
20728 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
20729 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
20730 SetSkill(SKILL_SWORDS, base_skill,base_skill);
20731 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
20732 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
20733 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
20734 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
20735 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
20736 SetSkill(SKILL_UNARMED, base_skill,base_skill);
20740 uint32 Player::GetPhaseMaskForSpawn() const
20742 uint32 phase = PHASEMASK_NORMAL;
20743 if(!isGameMaster())
20744 phase = GetPhaseMask();
20745 else
20747 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
20748 if(!phases.empty())
20749 phase = phases.front()->GetMiscValue();
20752 // some aura phases include 1 normal map in addition to phase itself
20753 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
20754 return n_phase;
20756 return PHASEMASK_NORMAL;
20759 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
20761 ItemPrototype const* pProto = pItem->GetProto();
20763 // proto based limitations
20764 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
20765 return res;
20767 // check unique-equipped on gems
20768 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
20770 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
20771 if(!enchant_id)
20772 continue;
20773 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
20774 if(!enchantEntry)
20775 continue;
20777 ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID);
20778 if(!pGem)
20779 continue;
20781 // include for check equip another gems with same limit category for not equipped item (and then not counted)
20782 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
20783 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
20785 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
20786 return res;
20789 return EQUIP_ERR_OK;
20792 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
20794 // check unique-equipped on item
20795 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
20797 // there is an equip limit on this item
20798 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
20799 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20802 // check unique-equipped limit
20803 if (itemProto->ItemLimitCategory)
20805 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
20806 if(!limitEntry)
20807 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
20809 // NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case
20811 if(limit_count > limitEntry->maxCount)
20812 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS;
20814 // there is an equip limit on this item
20815 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
20816 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS;
20819 return EQUIP_ERR_OK;
20822 void Player::HandleFall(MovementInfo const& movementInfo)
20824 // calculate total z distance of the fall
20825 float z_diff = m_lastFallZ - movementInfo.GetPos()->z;
20826 sLog.outDebug("zDiff = %f", z_diff);
20828 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
20829 // 14.57 can be calculated by resolving damageperc formula below to 0
20830 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
20831 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
20832 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
20834 //Safe fall, fall height reduction
20835 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
20837 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
20839 if(damageperc >0 )
20841 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getConfig(CONFIG_FLOAT_RATE_DAMAGE_FALL));
20843 float height = movementInfo.GetPos()->z;
20844 UpdateGroundPositionZ(movementInfo.GetPos()->x, movementInfo.GetPos()->y, height);
20846 if (damage > 0)
20848 //Prevent fall damage from being more than the player maximum health
20849 if (damage > GetMaxHealth())
20850 damage = GetMaxHealth();
20852 // Gust of Wind
20853 if (GetDummyAura(43621))
20854 damage = GetMaxHealth()/2;
20856 uint32 original_health = GetHealth();
20857 uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
20859 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
20860 if (isAlive() && final_damage < original_health)
20861 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
20864 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
20865 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.GetPos()->z, height, GetPositionZ(), movementInfo.GetFallTime(), height, damage, safe_fall);
20870 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
20872 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
20875 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
20877 uint32 CurTalentPoints = GetFreeTalentPoints();
20879 if(CurTalentPoints == 0)
20880 return;
20882 if (talentRank >= MAX_TALENT_RANK)
20883 return;
20885 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
20887 if(!talentInfo)
20888 return;
20890 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
20892 if(!talentTabInfo)
20893 return;
20895 // prevent learn talent for different class (cheating)
20896 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
20897 return;
20899 // find current max talent rank
20900 uint32 curtalent_maxrank = 0;
20901 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20903 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20905 curtalent_maxrank = k + 1;
20906 break;
20910 // we already have same or higher talent rank learned
20911 if(curtalent_maxrank >= (talentRank + 1))
20912 return;
20914 // check if we have enough talent points
20915 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20916 return;
20918 // Check if it requires another talent
20919 if (talentInfo->DependsOn > 0)
20921 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20923 bool hasEnoughRank = false;
20924 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20926 if (depTalentInfo->RankID[i] != 0)
20927 if (HasSpell(depTalentInfo->RankID[i]))
20928 hasEnoughRank = true;
20930 if (!hasEnoughRank)
20931 return;
20935 // Find out how many points we have in this field
20936 uint32 spentPoints = 0;
20938 uint32 tTab = talentInfo->TalentTab;
20939 if (talentInfo->Row > 0)
20941 unsigned int numRows = sTalentStore.GetNumRows();
20942 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20944 // Someday, someone needs to revamp
20945 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20946 if (tmpTalent) // the way talents are tracked
20948 if (tmpTalent->TalentTab == tTab)
20950 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20952 if (tmpTalent->RankID[j] != 0)
20954 if (HasSpell(tmpTalent->RankID[j]))
20956 spentPoints += j + 1;
20965 // not have required min points spent in talent tree
20966 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
20967 return;
20969 // spell not set in talent.dbc
20970 uint32 spellid = talentInfo->RankID[talentRank];
20971 if( spellid == 0 )
20973 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20974 return;
20977 // already known
20978 if(HasSpell(spellid))
20979 return;
20981 // learn! (other talent ranks will unlearned at learning)
20982 learnSpell(spellid, false);
20983 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20985 // update free talent points
20986 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20989 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
20991 Pet *pet = GetPet();
20993 if(!pet)
20994 return;
20996 if(petGuid != pet->GetGUID())
20997 return;
20999 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
21001 if(CurTalentPoints == 0)
21002 return;
21004 if (talentRank >= MAX_PET_TALENT_RANK)
21005 return;
21007 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
21009 if(!talentInfo)
21010 return;
21012 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
21014 if(!talentTabInfo)
21015 return;
21017 CreatureInfo const *ci = pet->GetCreatureInfo();
21019 if(!ci)
21020 return;
21022 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
21024 if(!pet_family)
21025 return;
21027 if(pet_family->petTalentType < 0) // not hunter pet
21028 return;
21030 // prevent learn talent for different family (cheating)
21031 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
21032 return;
21034 // find current max talent rank
21035 int32 curtalent_maxrank = 0;
21036 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
21038 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
21040 curtalent_maxrank = k + 1;
21041 break;
21045 // we already have same or higher talent rank learned
21046 if(curtalent_maxrank >= int32(talentRank + 1))
21047 return;
21049 // check if we have enough talent points
21050 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
21051 return;
21053 // Check if it requires another talent
21054 if (talentInfo->DependsOn > 0)
21056 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
21058 bool hasEnoughRank = false;
21059 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
21061 if (depTalentInfo->RankID[i] != 0)
21062 if (pet->HasSpell(depTalentInfo->RankID[i]))
21063 hasEnoughRank = true;
21065 if (!hasEnoughRank)
21066 return;
21070 // Find out how many points we have in this field
21071 uint32 spentPoints = 0;
21073 uint32 tTab = talentInfo->TalentTab;
21074 if (talentInfo->Row > 0)
21076 unsigned int numRows = sTalentStore.GetNumRows();
21077 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
21079 // Someday, someone needs to revamp
21080 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
21081 if (tmpTalent) // the way talents are tracked
21083 if (tmpTalent->TalentTab == tTab)
21085 for (int j = 0; j < MAX_TALENT_RANK; ++j)
21087 if (tmpTalent->RankID[j] != 0)
21089 if (pet->HasSpell(tmpTalent->RankID[j]))
21091 spentPoints += j + 1;
21100 // not have required min points spent in talent tree
21101 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
21102 return;
21104 // spell not set in talent.dbc
21105 uint32 spellid = talentInfo->RankID[talentRank];
21106 if( spellid == 0 )
21108 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
21109 return;
21112 // already known
21113 if(pet->HasSpell(spellid))
21114 return;
21116 // learn! (other talent ranks will unlearned at learning)
21117 pet->learnSpell(spellid);
21118 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
21120 // update free talent points
21121 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
21124 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
21126 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
21128 if(apply)
21129 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
21130 else
21131 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
21135 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
21137 if (m_lastFallTime >= minfo.GetFallTime() || m_lastFallZ <= minfo.GetPos()->z || opcode == MSG_MOVE_FALL_LAND)
21138 SetFallInformation(minfo.GetFallTime(), minfo.GetPos()->z);
21141 void Player::UnsummonPetTemporaryIfAny()
21143 Pet* pet = GetPet();
21144 if(!pet)
21145 return;
21147 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
21149 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
21150 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
21153 RemovePet(pet, PET_SAVE_AS_CURRENT);
21156 void Player::ResummonPetTemporaryUnSummonedIfAny()
21158 if(!m_temporaryUnsummonedPetNumber)
21159 return;
21161 // not resummon in not appropriate state
21162 if(IsPetNeedBeTemporaryUnsummoned())
21163 return;
21165 if(GetPetGUID())
21166 return;
21168 Pet* NewPet = new Pet;
21169 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
21170 delete NewPet;
21172 m_temporaryUnsummonedPetNumber = 0;
21175 bool Player::canSeeSpellClickOn(Creature const *c) const
21177 if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
21178 return false;
21180 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(c->GetEntry());
21181 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
21182 if(itr->second.IsFitToRequirements(this))
21183 return true;
21185 return false;
21188 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
21190 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
21191 *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
21192 *data << uint8(m_activeSpec); // talent group index (0 or 1)
21194 if(m_specsCount)
21196 // loop through all specs (only 1 for now)
21197 for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
21199 uint8 talentIdCount = 0;
21200 size_t pos = data->wpos();
21201 *data << uint8(talentIdCount); // [PH], talentIdCount
21203 // find class talent tabs (all players have 3 talent tabs)
21204 uint32 const* talentTabIds = GetTalentTabPages(getClass());
21206 for(uint32 i = 0; i < 3; ++i)
21208 uint32 talentTabId = talentTabIds[i];
21210 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
21212 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
21213 if(!talentInfo)
21214 continue;
21216 // skip another tab talents
21217 if(talentInfo->TalentTab != talentTabId)
21218 continue;
21220 // find max talent rank
21221 int32 curtalent_maxrank = -1;
21222 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
21224 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
21226 curtalent_maxrank = k;
21227 break;
21231 // not learned talent
21232 if(curtalent_maxrank < 0)
21233 continue;
21235 *data << uint32(talentInfo->TalentID); // Talent.dbc
21236 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
21238 ++talentIdCount;
21242 data->put<uint8>(pos, talentIdCount); // put real count
21244 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
21246 // GlyphProperties.dbc
21247 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
21248 *data << uint16(m_glyphs[specIdx][i].GetId());
21253 void Player::BuildPetTalentsInfoData(WorldPacket *data)
21255 uint32 unspentTalentPoints = 0;
21256 size_t pointsPos = data->wpos();
21257 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
21259 uint8 talentIdCount = 0;
21260 size_t countPos = data->wpos();
21261 *data << uint8(talentIdCount); // [PH], talentIdCount
21263 Pet *pet = GetPet();
21264 if(!pet)
21265 return;
21267 unspentTalentPoints = pet->GetFreeTalentPoints();
21269 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
21271 CreatureInfo const *ci = pet->GetCreatureInfo();
21272 if(!ci)
21273 return;
21275 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
21276 if(!pet_family || pet_family->petTalentType < 0)
21277 return;
21279 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
21281 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
21282 if(!talentTabInfo)
21283 continue;
21285 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
21286 continue;
21288 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
21290 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
21291 if(!talentInfo)
21292 continue;
21294 // skip another tab talents
21295 if(talentInfo->TalentTab != talentTabId)
21296 continue;
21298 // find max talent rank
21299 int32 curtalent_maxrank = -1;
21300 for(int32 k = 4; k > -1; --k)
21302 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
21304 curtalent_maxrank = k;
21305 break;
21309 // not learned talent
21310 if(curtalent_maxrank < 0)
21311 continue;
21313 *data << uint32(talentInfo->TalentID); // Talent.dbc
21314 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
21316 ++talentIdCount;
21319 data->put<uint8>(countPos, talentIdCount); // put real count
21321 break;
21325 void Player::SendTalentsInfoData(bool pet)
21327 WorldPacket data(SMSG_TALENTS_INFO, 50);
21328 data << uint8(pet ? 1 : 0);
21329 if(pet)
21330 BuildPetTalentsInfoData(&data);
21331 else
21332 BuildPlayerTalentsInfoData(&data);
21333 GetSession()->SendPacket(&data);
21336 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
21338 uint32 slotUsedMask = 0;
21339 size_t slotUsedMaskPos = data->wpos();
21340 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
21342 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21344 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
21346 if(!item)
21347 continue;
21349 slotUsedMask |= (1 << i);
21351 *data << uint32(item->GetEntry()); // item entry
21353 uint16 enchantmentMask = 0;
21354 size_t enchantmentMaskPos = data->wpos();
21355 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
21357 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
21359 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
21361 if(!enchId)
21362 continue;
21364 enchantmentMask |= (1 << j);
21366 *data << uint16(enchId); // enchantmentId?
21369 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
21371 *data << uint16(0); // ?
21372 *data << uint8(0); // PGUID!
21373 *data << uint32(0); // seed?
21376 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
21379 void Player::SendEquipmentSetList()
21381 uint32 count = 0;
21382 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
21383 size_t count_pos = data.wpos();
21384 data << uint32(count); // count placeholder
21385 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21387 if(itr->second.state==EQUIPMENT_SET_DELETED)
21388 continue;
21389 data.appendPackGUID(itr->second.Guid);
21390 data << uint32(itr->first);
21391 data << itr->second.Name;
21392 data << itr->second.IconName;
21393 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21394 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
21396 ++count; // client have limit but it checked at loading and set
21398 data.put<uint32>(count_pos, count);
21399 GetSession()->SendPacket(&data);
21402 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
21404 if(eqset.Guid != 0)
21406 bool found = false;
21408 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21410 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
21412 found = true;
21413 break;
21417 if(!found) // something wrong...
21419 sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
21420 return;
21424 EquipmentSet& eqslot = m_EquipmentSets[index];
21426 EquipmentSetUpdateState old_state = eqslot.state;
21428 eqslot = eqset;
21430 if(eqset.Guid == 0)
21432 eqslot.Guid = sObjectMgr.GenerateEquipmentSetGuid();
21434 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
21435 data << uint32(index);
21436 data.appendPackGUID(eqslot.Guid);
21437 GetSession()->SendPacket(&data);
21440 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
21443 void Player::_SaveEquipmentSets()
21445 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
21447 uint32 index = itr->first;
21448 EquipmentSet& eqset = itr->second;
21449 switch(eqset.state)
21451 case EQUIPMENT_SET_UNCHANGED:
21452 ++itr;
21453 break; // nothing do
21454 case EQUIPMENT_SET_CHANGED:
21455 CharacterDatabase.PExecute("UPDATE character_equipmentsets SET name='%s', iconname='%s', item0='%u', item1='%u', item2='%u', item3='%u', item4='%u', item5='%u', item6='%u', item7='%u', item8='%u', item9='%u', item10='%u', item11='%u', item12='%u', item13='%u', item14='%u', item15='%u', item16='%u', item17='%u', item18='%u' WHERE guid='%u' AND setguid='"UI64FMTD"' AND setindex='%u'",
21456 eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
21457 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18], GetGUIDLow(), eqset.Guid, index);
21458 eqset.state = EQUIPMENT_SET_UNCHANGED;
21459 ++itr;
21460 break;
21461 case EQUIPMENT_SET_NEW:
21462 CharacterDatabase.PExecute("INSERT INTO character_equipmentsets VALUES ('%u', '"UI64FMTD"', '%u', '%s', '%s', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
21463 GetGUIDLow(), eqset.Guid, index, eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
21464 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18]);
21465 eqset.state = EQUIPMENT_SET_UNCHANGED;
21466 ++itr;
21467 break;
21468 case EQUIPMENT_SET_DELETED:
21469 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
21470 m_EquipmentSets.erase(itr++);
21471 break;
21476 void Player::_SaveBGData()
21478 CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
21479 if (m_bgData.bgInstanceID)
21481 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
21482 CharacterDatabase.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
21483 GetGUIDLow(), m_bgData.bgInstanceID, m_bgData.bgTeam, m_bgData.joinPos.coord_x, m_bgData.joinPos.coord_y, m_bgData.joinPos.coord_z,
21484 m_bgData.joinPos.orientation, m_bgData.joinPos.mapid, m_bgData.taxiPath[0], m_bgData.taxiPath[1], m_bgData.mountSpell);
21488 void Player::DeleteEquipmentSet(uint64 setGuid)
21490 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21492 if(itr->second.Guid == setGuid)
21494 if(itr->second.state == EQUIPMENT_SET_NEW)
21495 m_EquipmentSets.erase(itr);
21496 else
21497 itr->second.state = EQUIPMENT_SET_DELETED;
21498 break;
21503 void Player::ActivateSpec(uint8 specNum)
21505 if(GetActiveSpec() == specNum)
21506 return;
21508 if(specNum >= GetSpecsCount())
21509 return;
21511 // unlearn GetActiveSpec() talents (not learned in specNum);
21512 // learn specNum talents
21514 ApplyGlyphs(false);
21516 SetActiveSpec(specNum);
21518 // recheck action buttons (not checked at loading/spec copy)
21519 ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
21520 for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); ++itr)
21521 if (itr->second.uState != ACTIONBUTTON_DELETED)
21522 // remove broken without any output (it can be not correct because talents not copied at spec creating)
21523 if (!IsActionButtonDataValid(itr->first,itr->second.GetAction(),itr->second.GetType(), this, false))
21524 removeActionButton(m_activeSpec,itr->first);
21526 ApplyGlyphs(true);
21528 SendInitialActionButtons();
21530 InitTalentForLevel();
21533 void Player::UpdateSpecCount(uint8 count)
21535 uint8 curCount = GetSpecsCount();
21536 if (curCount == count)
21537 return;
21539 // maybe current spec data must be copied to 0 spec?
21540 if (m_activeSpec >= count)
21541 ActivateSpec(0);
21543 // copy spec data from new specs
21544 if (count > curCount)
21546 // copy action buttons from active spec (more easy in this case iterate first by button)
21547 ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
21549 for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); ++itr)
21551 if (itr->second.uState != ACTIONBUTTON_DELETED)
21553 for(uint8 spec = curCount; spec < count; ++spec)
21554 addActionButton(spec,itr->first,itr->second.GetAction(),itr->second.GetType());
21558 // delete spec data for removed specs
21559 else if (count < curCount)
21561 // delete action buttons for removed spec
21562 for(uint8 spec = count; spec < curCount; ++spec)
21564 // delete action buttons for removed spec
21565 for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button)
21566 removeActionButton(spec,button);
21570 SetSpecsCount(count);
21572 SendTalentsInfoData(false);
21575 void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
21577 m_atLoginFlags &= ~f;
21579 if(in_db_also)
21580 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
21583 void Player::SendClearCooldown( uint32 spell_id, Unit* target )
21585 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
21586 data << uint32(spell_id);
21587 data << uint64(target->GetGUID());
21588 SendDirectMessage(&data);
21591 void Player::BuildTeleportAckMsg( WorldPacket *data, float x, float y, float z, float ang ) const
21593 data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
21594 *data << GetPackGUID();
21595 *data << uint32(0); // this value increments every time
21596 *data << uint32(m_movementInfo.GetMovementFlags()); // movement flags
21597 *data << uint16(0); // 2.3.0
21598 *data << uint32(getMSTime()); // time
21599 *data << x;
21600 *data << y;
21601 *data << z;
21602 *data << ang;
21603 *data << uint32(0);
21606 bool Player::HasMovementFlag( MovementFlags f ) const
21608 return m_movementInfo.HasMovementFlag(f);
21611 void Player::SetFarSightGUID( uint64 guid )
21613 if(GetFarSight() == guid)
21614 return;
21616 SetUInt64Value(PLAYER_FARSIGHT, guid);
21618 // need triggering load grids around new view point
21619 UpdateVisibilityForPlayer();
21622 void Player::UpdateVisibilityForPlayer()
21624 WorldObject const* viewPoint = GetViewPoint();
21625 Map* m = GetMap();
21627 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
21628 Cell cell(p);
21630 m->UpdatePlayerVisibility(this, cell, p);
21632 if (this != viewPoint)
21634 CellPair pView(MaNGOS::ComputeCellPair(viewPoint->GetPositionX(), viewPoint->GetPositionY()));
21635 Cell cellView(pView);
21637 m->UpdateObjectsVisibilityFor(this, cellView, pView);
21639 else
21640 m->UpdateObjectsVisibilityFor(this, cell, p);
21643 void Player::SendDuelCountdown(uint32 counter)
21645 WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
21646 data << uint32(counter); // seconds
21647 GetSession()->SendPacket(&data);
21650 bool Player::IsImmunedToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const
21652 switch(spellInfo->Effect[index])
21654 case SPELL_EFFECT_ATTACK_ME:
21655 return true;
21656 default:
21657 break;
21659 switch(spellInfo->EffectApplyAuraName[index])
21661 case SPELL_AURA_MOD_TAUNT:
21662 return true;
21663 default:
21664 break;
21666 return Unit::IsImmunedToSpellEffect(spellInfo, index);
21669 void Player::SetHomebindToLocation(WorldLocation const& loc, uint32 area_id)
21671 m_homebindMapId = loc.mapid;
21672 m_homebindAreaId = area_id;
21673 m_homebindX = loc.coord_x;
21674 m_homebindY = loc.coord_y;
21675 m_homebindZ = loc.coord_z;
21677 // update sql homebind
21678 CharacterDatabase.PExecute("UPDATE character_homebind SET map = '%u', zone = '%u', position_x = '%f', position_y = '%f', position_z = '%f' WHERE guid = '%u'",
21679 m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ, GetGUIDLow());
21682 Object* Player::GetObjectByTypeMask(ObjectGuid guid, TypeMask typemask)
21684 switch(guid.GetHigh())
21686 case HIGHGUID_ITEM:
21687 if (typemask & TYPEMASK_ITEM)
21688 return GetItemByGuid(guid);
21689 break;
21690 case HIGHGUID_PLAYER:
21691 if (GetObjectGuid()==guid)
21692 return this;
21693 if ((typemask & TYPEMASK_PLAYER) && IsInWorld())
21694 return ObjectAccessor::FindPlayer(guid);
21695 break;
21696 case HIGHGUID_GAMEOBJECT:
21697 if ((typemask & TYPEMASK_GAMEOBJECT) && IsInWorld())
21698 return GetMap()->GetGameObject(guid);
21699 break;
21700 case HIGHGUID_UNIT:
21701 if ((typemask & TYPEMASK_UNIT) && IsInWorld())
21702 return GetMap()->GetCreature(guid);
21703 break;
21704 case HIGHGUID_PET:
21705 if ((typemask & TYPEMASK_UNIT) && IsInWorld())
21706 return GetMap()->GetPet(guid);
21707 break;
21708 case HIGHGUID_VEHICLE:
21709 if ((typemask & TYPEMASK_UNIT) && IsInWorld())
21710 return GetMap()->GetVehicle(guid);
21711 break;
21712 case HIGHGUID_DYNAMICOBJECT:
21713 if ((typemask & TYPEMASK_DYNAMICOBJECT) && IsInWorld())
21714 return GetMap()->GetDynamicObject(guid);
21715 break;
21716 case HIGHGUID_TRANSPORT:
21717 case HIGHGUID_CORPSE:
21718 case HIGHGUID_MO_TRANSPORT:
21719 break;
21722 return NULL;