[9529] Make Player::IsValidPos const
[getmangos.git] / src / game / Player.cpp
blobc871be8d708499d0e7075030d59b47561bf194a9
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 "ObjectDefines.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(uint64 guid, uint32 npcflagmask)
2129 // unit checks
2130 if (!guid || !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(uint64 guid, uint32 gameobject_type) const
2179 if (GameObject *go = GetMap()->GetGameObject(guid))
2181 if (uint32(go->GetGoType()) == gameobject_type || gameobject_type == MAX_GAMEOBJECT_TYPE)
2183 float maxdist;
2184 switch(go->GetGoType())
2186 // TODO: find out how the client calculates the maximal usage distance to spellless working
2187 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2188 case GAMEOBJECT_TYPE_GUILD_BANK:
2189 case GAMEOBJECT_TYPE_MAILBOX:
2190 maxdist = 10.0f;
2191 break;
2192 case GAMEOBJECT_TYPE_FISHINGHOLE:
2193 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2194 break;
2195 default:
2196 maxdist = INTERACTION_DISTANCE;
2197 break;
2200 if (go->IsWithinDistInMap(this, maxdist) && go->isSpawned())
2201 return go;
2203 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,
2204 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2207 return NULL;
2210 bool Player::IsUnderWater() const
2212 return IsInWater() &&
2213 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2216 void Player::SetInWater(bool apply)
2218 if(m_isInWater==apply)
2219 return;
2221 //define player in water by opcodes
2222 //move player's guid into HateOfflineList of those mobs
2223 //which can't swim and move guid back into ThreatList when
2224 //on surface.
2225 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2226 m_isInWater = apply;
2228 // remove auras that need water/land
2229 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2231 getHostileRefManager().updateThreatTables();
2234 struct SetGameMasterOnHelper
2236 explicit SetGameMasterOnHelper() {}
2237 void operator()(Unit* unit) const
2239 unit->setFaction(35);
2240 unit->getHostileRefManager().setOnlineOfflineState(false);
2244 struct SetGameMasterOffHelper
2246 explicit SetGameMasterOffHelper(uint32 _faction) : faction(_faction) {}
2247 void operator()(Unit* unit) const
2249 unit->setFaction(faction);
2250 unit->getHostileRefManager().setOnlineOfflineState(true);
2252 uint32 faction;
2255 void Player::SetGameMaster(bool on)
2257 if(on)
2259 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2260 setFaction(35);
2261 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2263 CallForAllControlledUnits(SetGameMasterOnHelper(),true,true,true,false);
2265 SetFFAPvP(false);
2266 ResetContestedPvP();
2268 getHostileRefManager().setOnlineOfflineState(false);
2269 CombatStopWithPets();
2271 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2273 else
2275 // restore phase
2276 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2277 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2279 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2280 setFactionForRace(getRace());
2281 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2283 CallForAllControlledUnits(SetGameMasterOffHelper(getFaction()),true,true,true,false);
2285 // restore FFA PvP Server state
2286 if(sWorld.IsFFAPvPRealm())
2287 SetFFAPvP(true);
2289 // restore FFA PvP area state, remove not allowed for GM mounts
2290 UpdateArea(m_areaUpdateId);
2292 getHostileRefManager().setOnlineOfflineState(true);
2295 UpdateVisibilityForPlayer();
2298 void Player::SetGMVisible(bool on)
2300 if(on)
2302 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2304 // Reapply stealth/invisibility if active or show if not any
2305 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2306 SetVisibility(VISIBILITY_GROUP_STEALTH);
2307 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2308 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2309 else
2310 SetVisibility(VISIBILITY_ON);
2312 else
2314 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2316 SetAcceptWhispers(false);
2317 SetGameMaster(true);
2319 SetVisibility(VISIBILITY_OFF);
2323 bool Player::IsGroupVisibleFor(Player* p) const
2325 switch(sWorld.getConfig(CONFIG_UINT32_GROUP_VISIBILITY))
2327 default: return IsInSameGroupWith(p);
2328 case 1: return IsInSameRaidWith(p);
2329 case 2: return GetTeam()==p->GetTeam();
2333 bool Player::IsInSameGroupWith(Player const* p) const
2335 return (p==this || (GetGroup() != NULL &&
2336 GetGroup()->SameSubGroup((Player*)this, (Player*)p)));
2339 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2340 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2341 void Player::UninviteFromGroup()
2343 Group* group = GetGroupInvite();
2344 if(!group)
2345 return;
2347 group->RemoveInvite(this);
2349 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2351 if(group->IsCreated())
2353 group->Disband(true);
2354 sObjectMgr.RemoveGroup(group);
2356 else
2357 group->RemoveAllInvites();
2359 delete group;
2363 void Player::RemoveFromGroup(Group* group, uint64 guid)
2365 if(group)
2367 if (group->RemoveMember(guid, 0) <= 1)
2369 // group->Disband(); already disbanded in RemoveMember
2370 sObjectMgr.RemoveGroup(group);
2371 delete group;
2372 // removemember sets the player's group pointer to NULL
2377 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2379 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2380 data << uint64(victim ? victim->GetGUID() : 0); // guid
2381 data << uint32(GivenXP+RestXP); // given experience
2382 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2383 if(victim)
2385 data << uint32(GivenXP); // experience without rested bonus
2386 data << float(1); // 1 - none 0 - 100% group bonus output
2388 data << uint8(0); // new 2.4.0
2389 GetSession()->SendPacket(&data);
2392 void Player::GiveXP(uint32 xp, Unit* victim)
2394 if ( xp < 1 )
2395 return;
2397 if(!isAlive())
2398 return;
2400 uint32 level = getLevel();
2402 // XP to money conversion processed in Player::RewardQuest
2403 if(level >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2404 return;
2406 if(victim)
2408 // handle SPELL_AURA_MOD_KILL_XP_PCT auras
2409 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT);
2410 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2411 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2413 else
2415 // handle SPELL_AURA_MOD_QUEST_XP_PCT auras
2416 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT);
2417 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2418 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2421 // XP resting bonus for kill
2422 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2424 SendLogXPGain(xp,victim,rested_bonus_xp);
2426 uint32 curXP = GetUInt32Value(PLAYER_XP);
2427 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2428 uint32 newXP = curXP + xp + rested_bonus_xp;
2430 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
2432 newXP -= nextLvlXP;
2434 if ( level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
2435 GiveLevel(level + 1);
2437 level = getLevel();
2438 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2441 SetUInt32Value(PLAYER_XP, newXP);
2444 // Update player to next level
2445 // Current player experience not update (must be update by caller)
2446 void Player::GiveLevel(uint32 level)
2448 if ( level == getLevel() )
2449 return;
2451 PlayerLevelInfo info;
2452 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2454 PlayerClassLevelInfo classInfo;
2455 sObjectMgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2457 // send levelup info to client
2458 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2459 data << uint32(level);
2460 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2461 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2462 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2463 data << uint32(0);
2464 data << uint32(0);
2465 data << uint32(0);
2466 data << uint32(0);
2467 data << uint32(0);
2468 data << uint32(0);
2469 // end for
2470 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2471 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2473 GetSession()->SendPacket(&data);
2475 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(level));
2477 //update level, max level of skills
2478 m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
2480 _ApplyAllLevelScaleItemMods(false);
2482 SetLevel(level);
2484 UpdateSkillsForLevel ();
2486 // save base values (bonuses already included in stored stats
2487 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2488 SetCreateStat(Stats(i), info.stats[i]);
2490 SetCreateHealth(classInfo.basehealth);
2491 SetCreateMana(classInfo.basemana);
2493 InitTalentForLevel();
2494 InitTaxiNodesForLevel();
2495 InitGlyphsForLevel();
2497 UpdateAllStats();
2499 // set current level health and mana/energy to maximum after applying all mods.
2500 SetHealth(GetMaxHealth());
2501 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2502 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2503 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2504 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2505 SetPower(POWER_FOCUS, 0);
2506 SetPower(POWER_HAPPINESS, 0);
2508 _ApplyAllLevelScaleItemMods(true);
2510 // update level to hunter/summon pet
2511 if (Pet* pet = GetPet())
2512 pet->SynchronizeLevelWithOwner();
2514 if (MailLevelReward const* mailReward = sObjectMgr.GetMailLevelReward(level,getRaceMask()))
2515 MailDraft(mailReward->mailTemplateId).SendMailTo(this,MailSender(MAIL_CREATURE,mailReward->senderEntry));
2517 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2520 void Player::InitTalentForLevel()
2522 uint32 level = getLevel();
2523 // talents base at level diff ( talents = level - 9 but some can be used already)
2524 if(level < 10)
2526 // Remove all talent points
2527 if(m_usedTalentCount > 0) // Free any used talents
2529 resetTalents(true);
2530 SetFreeTalentPoints(0);
2533 else
2535 uint32 talentPointsForLevel = CalculateTalentsPoints();
2537 // if used more that have then reset
2538 if(m_usedTalentCount > talentPointsForLevel)
2540 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2541 resetTalents(true);
2542 else
2543 SetFreeTalentPoints(0);
2545 // else update amount of free points
2546 else
2547 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2550 if(!GetSession()->PlayerLoading())
2551 SendTalentsInfoData(false); // update at client
2554 void Player::InitStatsForLevel(bool reapplyMods)
2556 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2557 _RemoveAllStatBonuses();
2559 PlayerClassLevelInfo classInfo;
2560 sObjectMgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2562 PlayerLevelInfo info;
2563 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2565 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) );
2566 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(getLevel()));
2568 // reset before any aura state sources (health set/aura apply)
2569 SetUInt32Value(UNIT_FIELD_AURASTATE, 0);
2571 UpdateSkillsForLevel ();
2573 // set default cast time multiplier
2574 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2576 // reset size before reapply auras
2577 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2579 // save base values (bonuses already included in stored stats
2580 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2581 SetCreateStat(Stats(i), info.stats[i]);
2583 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2584 SetStat(Stats(i), info.stats[i]);
2586 SetCreateHealth(classInfo.basehealth);
2588 //set create powers
2589 SetCreateMana(classInfo.basemana);
2591 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2593 InitStatBuffMods();
2595 //reset rating fields values
2596 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2597 SetUInt32Value(index, 0);
2599 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2600 for (int i = 0; i < 7; ++i)
2602 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2603 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2604 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2607 //reset attack power, damage and attack speed fields
2608 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2609 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2610 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2612 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2613 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2614 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2615 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2616 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2617 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2619 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2620 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2621 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2622 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2623 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2624 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2626 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2627 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2628 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2629 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2631 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2632 for (uint8 i = 0; i < 7; ++i)
2633 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2635 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2636 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2637 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2639 // Dodge percentage
2640 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2642 // set armor (resistance 0) to original value (create_agility*2)
2643 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2644 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2645 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2646 // set other resistance to original value (0)
2647 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2649 SetResistance(SpellSchools(i), 0);
2650 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2651 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2654 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2655 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2656 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2658 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2659 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2661 // Reset no reagent cost field
2662 for(int i = 0; i < 3; ++i)
2663 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2664 // Init data for form but skip reapply item mods for form
2665 InitDataForForm(reapplyMods);
2667 // save new stats
2668 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2669 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2671 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2673 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2674 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2676 // cleanup unit flags (will be re-applied if need at aura load).
2677 RemoveFlag( UNIT_FIELD_FLAGS,
2678 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2679 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2680 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2681 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2682 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2683 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2685 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2687 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2688 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2690 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2691 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2693 // restore if need some important flags
2694 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2696 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2697 _ApplyAllStatBonuses();
2699 // set current level health and mana/energy to maximum after applying all mods.
2700 SetHealth(GetMaxHealth());
2701 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2702 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2703 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2704 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2705 SetPower(POWER_FOCUS, 0);
2706 SetPower(POWER_HAPPINESS, 0);
2707 SetPower(POWER_RUNIC_POWER, 0);
2709 // update level to hunter/summon pet
2710 if (Pet* pet = GetPet())
2711 pet->SynchronizeLevelWithOwner();
2714 void Player::SendInitialSpells()
2716 time_t curTime = time(NULL);
2717 time_t infTime = curTime + infinityCooldownDelayCheck;
2719 uint16 spellCount = 0;
2721 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2722 data << uint8(0);
2724 size_t countPos = data.wpos();
2725 data << uint16(spellCount); // spell count placeholder
2727 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2729 if(itr->second.state == PLAYERSPELL_REMOVED)
2730 continue;
2732 if(!itr->second.active || itr->second.disabled)
2733 continue;
2735 data << uint32(itr->first);
2736 data << uint16(0); // it's not slot id
2738 spellCount +=1;
2741 data.put<uint16>(countPos,spellCount); // write real count value
2743 uint16 spellCooldowns = m_spellCooldowns.size();
2744 data << uint16(spellCooldowns);
2745 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2747 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2748 if(!sEntry)
2749 continue;
2751 data << uint32(itr->first);
2753 data << uint16(itr->second.itemid); // cast item id
2754 data << uint16(sEntry->Category); // spell category
2756 // send infinity cooldown in special format
2757 if(itr->second.end >= infTime)
2759 data << uint32(1); // cooldown
2760 data << uint32(0x80000000); // category cooldown
2761 continue;
2764 time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILISECONDS : 0;
2766 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2768 data << uint32(0); // cooldown
2769 data << uint32(cooldown); // category cooldown
2771 else
2773 data << uint32(cooldown); // cooldown
2774 data << uint32(0); // category cooldown
2778 GetSession()->SendPacket(&data);
2780 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2783 void Player::RemoveMail(uint32 id)
2785 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2787 if ((*itr)->messageID == id)
2789 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2790 m_mail.erase(itr);
2791 return;
2796 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2798 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2799 data << (uint32) mailId;
2800 data << (uint32) mailAction;
2801 data << (uint32) mailError;
2802 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2803 data << (uint32) equipError;
2804 else if( mailAction == MAIL_ITEM_TAKEN )
2806 data << (uint32) item_guid; // item guid low?
2807 data << (uint32) item_count; // item count?
2809 GetSession()->SendPacket(&data);
2812 void Player::SendNewMail()
2814 // deliver undelivered mail
2815 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2816 data << (uint32) 0;
2817 GetSession()->SendPacket(&data);
2820 void Player::UpdateNextMailTimeAndUnreads()
2822 // calculate next delivery time (min. from non-delivered mails
2823 // and recalculate unReadMail
2824 time_t cTime = time(NULL);
2825 m_nextMailDelivereTime = 0;
2826 unReadMails = 0;
2827 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2829 if((*itr)->deliver_time > cTime)
2831 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2832 m_nextMailDelivereTime = (*itr)->deliver_time;
2834 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2835 ++unReadMails;
2839 void Player::AddNewMailDeliverTime(time_t deliver_time)
2841 if(deliver_time <= time(NULL)) // ready now
2843 ++unReadMails;
2844 SendNewMail();
2846 else // not ready and no have ready mails
2848 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2849 m_nextMailDelivereTime = deliver_time;
2853 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2855 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2856 if (!spellInfo)
2858 // do character spell book cleanup (all characters)
2859 if(!IsInWorld() && !learning) // spell load case
2861 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2862 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2864 else
2865 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2867 return false;
2870 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2872 // do character spell book cleanup (all characters)
2873 if(!IsInWorld() && !learning) // spell load case
2875 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2876 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2878 else
2879 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2881 return false;
2884 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2886 bool dependent_set = false;
2887 bool disabled_case = false;
2888 bool superceded_old = false;
2890 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2891 if (itr != m_spells.end())
2893 uint32 next_active_spell_id = 0;
2894 // fix activate state for non-stackable low rank (and find next spell for !active case)
2895 if(!SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
2897 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
2898 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2900 if(HasSpell(next_itr->second))
2902 // high rank already known so this must !active
2903 active = false;
2904 next_active_spell_id = next_itr->second;
2905 break;
2910 // not do anything if already known in expected state
2911 if(itr->second.state != PLAYERSPELL_REMOVED && itr->second.active == active &&
2912 itr->second.dependent == dependent && itr->second.disabled == disabled)
2914 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2915 itr->second.state = PLAYERSPELL_UNCHANGED;
2917 return false;
2920 // dependent spell known as not dependent, overwrite state
2921 if (itr->second.state != PLAYERSPELL_REMOVED && !itr->second.dependent && dependent)
2923 itr->second.dependent = dependent;
2924 if (itr->second.state != PLAYERSPELL_NEW)
2925 itr->second.state = PLAYERSPELL_CHANGED;
2926 dependent_set = true;
2929 // update active state for known spell
2930 if(itr->second.active != active && itr->second.state != PLAYERSPELL_REMOVED && !itr->second.disabled)
2932 itr->second.active = active;
2934 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2935 itr->second.state = PLAYERSPELL_UNCHANGED;
2936 else if(itr->second.state != PLAYERSPELL_NEW)
2937 itr->second.state = PLAYERSPELL_CHANGED;
2939 if(active)
2941 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2942 CastSpell (this,spell_id,true);
2944 else if(IsInWorld())
2946 if(next_active_spell_id)
2948 // update spell ranks in spellbook and action bar
2949 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2950 data << uint32(spell_id);
2951 data << uint32(next_active_spell_id);
2952 GetSession()->SendPacket( &data );
2954 else
2956 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2957 data << uint32(spell_id);
2958 GetSession()->SendPacket(&data);
2962 return active; // learn (show in spell book if active now)
2965 if(itr->second.disabled != disabled && itr->second.state != PLAYERSPELL_REMOVED)
2967 if(itr->second.state != PLAYERSPELL_NEW)
2968 itr->second.state = PLAYERSPELL_CHANGED;
2969 itr->second.disabled = disabled;
2971 if(disabled)
2972 return false;
2974 disabled_case = true;
2976 else switch(itr->second.state)
2978 case PLAYERSPELL_UNCHANGED: // known saved spell
2979 return false;
2980 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2982 m_spells.erase(itr);
2983 state = PLAYERSPELL_CHANGED;
2984 break; // need re-add
2986 default: // known not saved yet spell (new or modified)
2988 // can be in case spell loading but learned at some previous spell loading
2989 if(!IsInWorld() && !learning && !dependent_set)
2990 itr->second.state = PLAYERSPELL_UNCHANGED;
2992 return false;
2997 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2999 // talent: unlearn all other talent ranks (high and low)
3000 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
3002 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
3004 for(int i=0; i < MAX_TALENT_RANK; ++i)
3006 // skip learning spell and no rank spell case
3007 uint32 rankSpellId = talentInfo->RankID[i];
3008 if(!rankSpellId || rankSpellId==spell_id)
3009 continue;
3011 removeSpell(rankSpellId,false,false);
3015 // non talent spell: learn low ranks (recursive call)
3016 else if(uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id))
3018 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
3019 addSpell(prev_spell,active,true,true,disabled);
3020 else // at normal learning
3021 learnSpell(prev_spell,true);
3024 PlayerSpell newspell;
3025 newspell.state = state;
3026 newspell.active = active;
3027 newspell.dependent = dependent;
3028 newspell.disabled = disabled;
3030 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
3031 if(newspell.active && !newspell.disabled && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
3033 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
3035 if(itr2->second.state == PLAYERSPELL_REMOVED) continue;
3036 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
3037 if(!i_spellInfo) continue;
3039 if( sSpellMgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
3041 if(itr2->second.active)
3043 if(sSpellMgr.IsHighRankOfSpell(spell_id,itr2->first))
3045 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3047 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3048 data << uint32(itr2->first);
3049 data << uint32(spell_id);
3050 GetSession()->SendPacket( &data );
3053 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
3054 itr2->second.active = false;
3055 if(itr2->second.state != PLAYERSPELL_NEW)
3056 itr2->second.state = PLAYERSPELL_CHANGED;
3057 superceded_old = true; // new spell replace old in action bars and spell book.
3059 else if(sSpellMgr.IsHighRankOfSpell(itr2->first,spell_id))
3061 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3063 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3064 data << uint32(spell_id);
3065 data << uint32(itr2->first);
3066 GetSession()->SendPacket( &data );
3069 // mark new spell as disable (not learned yet for client and will not learned)
3070 newspell.active = false;
3071 if(newspell.state != PLAYERSPELL_NEW)
3072 newspell.state = PLAYERSPELL_CHANGED;
3079 m_spells[spell_id] = newspell;
3081 // return false if spell disabled
3082 if (newspell.disabled)
3083 return false;
3086 uint32 talentCost = GetTalentSpellCost(spell_id);
3088 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3089 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3090 if (talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
3092 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3093 CastSpell(this, spell_id, true);
3095 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3096 else if (IsPassiveSpell(spell_id))
3098 if (IsNeedCastPassiveSpellAtLearn(spellInfo))
3099 CastSpell(this, spell_id, true);
3101 else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
3103 CastSpell(this, spell_id, true);
3104 return false;
3107 // update used talent points count
3108 m_usedTalentCount += talentCost;
3110 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3111 if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
3113 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3114 SetFreePrimaryProfessions(freeProfs-1);
3117 // add dependent skills
3118 uint16 maxskill = GetMaxSkillValueForLevel();
3120 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3122 SkillLineAbilityMapBounds skill_bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3124 if (spellLearnSkill)
3126 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
3127 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
3129 if (skill_value < spellLearnSkill->value)
3130 skill_value = spellLearnSkill->value;
3132 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
3134 if (skill_max_value < new_skill_max_value)
3135 skill_max_value = new_skill_max_value;
3137 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
3139 else
3141 // not ranked skills
3142 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3144 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3145 if (!pSkill)
3146 continue;
3148 if (HasSkill(pSkill->id))
3149 continue;
3151 if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3152 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3153 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3155 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
3157 case SKILL_RANGE_LANGUAGE:
3158 SetSkill(pSkill->id, 300, 300 );
3159 break;
3160 case SKILL_RANGE_LEVEL:
3161 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
3162 break;
3163 case SKILL_RANGE_MONO:
3164 SetSkill(pSkill->id, 1, 1 );
3165 break;
3166 default:
3167 break;
3173 // learn dependent spells
3174 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3176 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3178 if (!itr2->second.autoLearned)
3180 if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
3181 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
3182 else // at normal learning
3183 learnSpell(itr2->second.spell,true);
3187 if (!GetSession()->PlayerLoading())
3189 // not ranked skills
3190 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3192 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3193 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3196 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3199 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3200 return active && !disabled && !superceded_old;
3203 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3205 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3206 // talent dependent passives activated at form apply have proper stance data
3207 bool need_cast = (!spellInfo->Stances || (m_form != 0 && (spellInfo->Stances & (1<<(m_form-1)))));
3209 //Check CasterAuraStates
3210 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3213 void Player::learnSpell(uint32 spell_id, bool dependent)
3215 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3217 bool disabled = (itr != m_spells.end()) ? itr->second.disabled : false;
3218 bool active = disabled ? itr->second.active : true;
3220 bool learning = addSpell(spell_id,active,true,dependent,false);
3222 // learn all disabled higher ranks (recursive)
3223 if(disabled)
3225 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3226 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3228 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3229 if (iter != m_spells.end() && iter->second.disabled)
3230 learnSpell(i->second,false);
3234 // prevent duplicated entires in spell book, also not send if not in world (loading)
3235 if(!learning || !IsInWorld ())
3236 return;
3238 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3239 data << uint32(spell_id);
3240 GetSession()->SendPacket(&data);
3243 void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bool sendUpdate)
3245 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3246 if (itr == m_spells.end())
3247 return;
3249 if (itr->second.state == PLAYERSPELL_REMOVED || (disabled && itr->second.disabled))
3250 return;
3252 // unlearn non talent higher ranks (recursive)
3253 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3254 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3255 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3256 removeSpell(itr2->second,disabled,false);
3258 // re-search, it can be corrupted in prev loop
3259 itr = m_spells.find(spell_id);
3260 if (itr == m_spells.end())
3261 return; // already unleared
3263 bool cur_active = itr->second.active;
3264 bool cur_dependent = itr->second.dependent;
3266 if (disabled)
3268 itr->second.disabled = disabled;
3269 if(itr->second.state != PLAYERSPELL_NEW)
3270 itr->second.state = PLAYERSPELL_CHANGED;
3272 else
3274 if(itr->second.state == PLAYERSPELL_NEW)
3275 m_spells.erase(itr);
3276 else
3277 itr->second.state = PLAYERSPELL_REMOVED;
3280 RemoveAurasDueToSpell(spell_id);
3282 // remove pet auras
3283 for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
3284 if(PetAura const* petSpell = sSpellMgr.GetPetAura(spell_id, SpellEffectIndex(i)))
3285 RemovePetAura(petSpell);
3287 // free talent points
3288 uint32 talentCosts = GetTalentSpellCost(spell_id);
3289 if(talentCosts > 0)
3291 if(talentCosts < m_usedTalentCount)
3292 m_usedTalentCount -= talentCosts;
3293 else
3294 m_usedTalentCount = 0;
3297 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3298 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3300 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3301 if(freeProfs <= sWorld.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL))
3302 SetFreePrimaryProfessions(freeProfs);
3305 // remove dependent skill
3306 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3307 if(spellLearnSkill)
3309 uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id);
3310 if(!prev_spell) // first rank, remove skill
3311 SetSkill(spellLearnSkill->skill,0,0);
3312 else
3314 // search prev. skill setting by spell ranks chain
3315 SpellLearnSkillNode const* prevSkill = sSpellMgr.GetSpellLearnSkill(prev_spell);
3316 while(!prevSkill && prev_spell)
3318 prev_spell = sSpellMgr.GetPrevSpellInChain(prev_spell);
3319 prevSkill = sSpellMgr.GetSpellLearnSkill(sSpellMgr.GetFirstSpellInChain(prev_spell));
3322 if (!prevSkill) // not found prev skill setting, remove skill
3323 SetSkill(spellLearnSkill->skill,0,0);
3324 else // set to prev. skill setting values
3326 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3327 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3329 if (skill_value > prevSkill->value)
3330 skill_value = prevSkill->value;
3332 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3334 if (skill_max_value > new_skill_max_value)
3335 skill_max_value = new_skill_max_value;
3337 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3342 else
3344 // not ranked skills
3345 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3347 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
3349 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3350 if (!pSkill)
3351 continue;
3353 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
3354 pSkill->categoryId != SKILL_CATEGORY_CLASS ||// not unlearn class skills (spellbook/talent pages)
3355 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3356 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3358 // not reset skills for professions and racial abilities
3359 if ((pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3360 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0))
3361 continue;
3363 SetSkill(pSkill->id, 0, 0 );
3368 // remove dependent spells
3369 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3371 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3372 removeSpell(itr2->second.spell, disabled);
3374 // activate lesser rank in spellbook/action bar, and cast it if need
3375 bool prev_activate = false;
3377 if (uint32 prev_id = sSpellMgr.GetPrevSpellInChain (spell_id))
3379 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3381 // if talent then lesser rank also talent and need learn
3382 if (talentCosts)
3384 if(learn_low_rank)
3385 learnSpell (prev_id,false);
3387 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3388 else if (cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
3390 // need manually update dependence state (learn spell ignore like attempts)
3391 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3392 if (prev_itr != m_spells.end())
3394 if (prev_itr->second.dependent != cur_dependent)
3396 prev_itr->second.dependent = cur_dependent;
3397 if (prev_itr->second.state != PLAYERSPELL_NEW)
3398 prev_itr->second.state = PLAYERSPELL_CHANGED;
3401 // now re-learn if need re-activate
3402 if (cur_active && !prev_itr->second.active && learn_low_rank)
3404 if (addSpell(prev_id,true,false,prev_itr->second.dependent,prev_itr->second.disabled))
3406 // downgrade spell ranks in spellbook and action bar
3407 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3408 data << uint32(spell_id);
3409 data << uint32(prev_id);
3410 GetSession()->SendPacket( &data );
3411 prev_activate = true;
3418 // remove from spell book if not replaced by lesser rank
3419 if (!prev_activate && sendUpdate)
3421 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3422 data << uint32(spell_id);
3423 GetSession()->SendPacket(&data);
3427 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3429 m_spellCooldowns.erase(spell_id);
3431 if(update)
3432 SendClearCooldown(spell_id, this);
3435 void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
3437 SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
3438 if (ct == sSpellCategoryStore.end())
3439 return;
3441 const SpellCategorySet& ct_set = ct->second;
3442 for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
3444 if (ct_set.find(i->first) != ct_set.end())
3445 RemoveSpellCooldown((i++)->first, update);
3446 else
3447 ++i;
3451 void Player::RemoveArenaSpellCooldowns()
3453 // remove cooldowns on spells that has < 15 min CD
3454 SpellCooldowns::iterator itr, next;
3455 // iterate spell cooldowns
3456 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3458 next = itr;
3459 ++next;
3460 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3461 // check if spellentry is present and if the cooldown is less than 15 mins
3462 if( entry &&
3463 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3464 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3466 // remove & notify
3467 RemoveSpellCooldown(itr->first, true);
3472 void Player::RemoveAllSpellCooldown()
3474 if(!m_spellCooldowns.empty())
3476 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3477 SendClearCooldown(itr->first, this);
3479 m_spellCooldowns.clear();
3483 void Player::_LoadSpellCooldowns(QueryResult *result)
3485 // some cooldowns can be already set at aura loading...
3487 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3489 if(result)
3491 time_t curTime = time(NULL);
3495 Field *fields = result->Fetch();
3497 uint32 spell_id = fields[0].GetUInt32();
3498 uint32 item_id = fields[1].GetUInt32();
3499 time_t db_time = (time_t)fields[2].GetUInt64();
3501 if(!sSpellStore.LookupEntry(spell_id))
3503 sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3504 continue;
3507 // skip outdated cooldown
3508 if(db_time <= curTime)
3509 continue;
3511 AddSpellCooldown(spell_id, item_id, db_time);
3513 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3515 while( result->NextRow() );
3517 delete result;
3521 void Player::_SaveSpellCooldowns()
3523 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3525 time_t curTime = time(NULL);
3526 time_t infTime = curTime + infinityCooldownDelayCheck;
3528 /* copied following sql-code partly from achievementmgr */
3529 bool first_round = true;
3530 std::ostringstream ss;
3532 // remove outdated and save active
3533 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3535 if(itr->second.end <= curTime)
3536 m_spellCooldowns.erase(itr++);
3537 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3539 if (first_round)
3541 ss << "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ";
3542 first_round = false;
3544 // next new/changed record prefix
3545 else
3546 ss << ", ";
3547 ss << "(" << GetGUIDLow() << "," << itr->first << "," << itr->second.itemid << "," << uint64(itr->second.end) << ")";
3548 ++itr;
3550 else
3551 ++itr;
3554 // if something changed execute
3555 if (!first_round)
3556 CharacterDatabase.Execute( ss.str().c_str() );
3559 uint32 Player::resetTalentsCost() const
3561 // The first time reset costs 1 gold
3562 if(m_resetTalentsCost < 1*GOLD)
3563 return 1*GOLD;
3564 // then 5 gold
3565 else if(m_resetTalentsCost < 5*GOLD)
3566 return 5*GOLD;
3567 // After that it increases in increments of 5 gold
3568 else if(m_resetTalentsCost < 10*GOLD)
3569 return 10*GOLD;
3570 else
3572 time_t months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3573 if(months > 0)
3575 // This cost will be reduced by a rate of 5 gold per month
3576 int32 new_cost = int32((m_resetTalentsCost) - 5*GOLD*months);
3577 // to a minimum of 10 gold.
3578 return uint32(new_cost < 10*GOLD ? 10*GOLD : new_cost);
3580 else
3582 // After that it increases in increments of 5 gold
3583 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3584 // until it hits a cap of 50 gold.
3585 if(new_cost > 50*GOLD)
3586 new_cost = 50*GOLD;
3587 return new_cost;
3592 bool Player::resetTalents(bool no_cost)
3594 // not need after this call
3595 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3596 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
3598 uint32 talentPointsForLevel = CalculateTalentsPoints();
3600 if (m_usedTalentCount == 0)
3602 SetFreeTalentPoints(talentPointsForLevel);
3603 return false;
3606 uint32 cost = 0;
3608 if(!no_cost)
3610 cost = resetTalentsCost();
3612 if (GetMoney() < cost)
3614 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3615 return false;
3619 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3621 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3623 if (!talentInfo) continue;
3625 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3627 if(!talentTabInfo)
3628 continue;
3630 // unlearn only talents for character class
3631 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3632 // to prevent unexpected lost normal learned spell skip another class talents
3633 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3634 continue;
3636 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3638 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3640 if(itr->second.state == PLAYERSPELL_REMOVED || itr->second.disabled)
3642 ++itr;
3643 continue;
3646 // remove learned spells (all ranks)
3647 uint32 itrFirstId = sSpellMgr.GetFirstSpellInChain(itr->first);
3649 // unlearn if first rank is talent or learned by talent
3650 if (itrFirstId == talentInfo->RankID[j])
3652 removeSpell(itr->first,!IsPassiveSpell(itr->first),false);
3653 itr = GetSpellMap().begin();
3654 continue;
3656 else if (sSpellMgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3658 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3659 itr = GetSpellMap().begin();
3660 continue;
3662 else
3663 ++itr;
3668 SetFreeTalentPoints(talentPointsForLevel);
3670 if(!no_cost)
3672 ModifyMoney(-(int32)cost);
3673 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3674 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3676 m_resetTalentsCost = cost;
3677 m_resetTalentsTime = time(NULL);
3680 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3681 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3682 /* when prev line will dropped use next line
3683 if(Pet* pet = GetPet())
3685 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3686 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3691 if(m_canTitanGrip)
3693 m_canTitanGrip = false;
3694 if(sWorld.getConfig(CONFIG_BOOL_OFFHAND_CHECK_AT_TALENTS_RESET))
3695 AutoUnequipOffhandIfNeed();
3698 return true;
3701 Mail* Player::GetMail(uint32 id)
3703 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3705 if ((*itr)->messageID == id)
3707 return (*itr);
3710 return NULL;
3713 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3715 if(target == this)
3717 Object::_SetCreateBits(updateMask, target);
3719 else
3721 for(uint16 index = 0; index < m_valuesCount; index++)
3723 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3724 updateMask->SetBit(index);
3729 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3731 if(target == this)
3733 Object::_SetUpdateBits(updateMask, target);
3735 else
3737 Object::_SetUpdateBits(updateMask, target);
3738 *updateMask &= updateVisualBits;
3742 void Player::InitVisibleBits()
3744 updateVisualBits.SetCount(PLAYER_END);
3746 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3747 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3748 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3749 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3750 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3751 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3752 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3753 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3754 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3755 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3756 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3757 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3758 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3759 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3760 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3761 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3762 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3763 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3764 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3765 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3766 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3767 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3768 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3769 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3770 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3771 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3772 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3773 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3774 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3775 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3776 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3777 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3778 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3779 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3780 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3781 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3782 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3783 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3784 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3785 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3786 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3787 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3788 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3789 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3790 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3791 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3792 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3793 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3794 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3795 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3796 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3797 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3798 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3799 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3800 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3802 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3803 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3804 updateVisualBits.SetBit(PLAYER_FLAGS);
3805 updateVisualBits.SetBit(PLAYER_GUILDID);
3806 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3807 updateVisualBits.SetBit(PLAYER_BYTES);
3808 updateVisualBits.SetBit(PLAYER_BYTES_2);
3809 updateVisualBits.SetBit(PLAYER_BYTES_3);
3810 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3811 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3813 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3814 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += MAX_QUEST_OFFSET)
3815 updateVisualBits.SetBit(i);
3817 // Players visible items are not inventory stuff
3818 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3820 uint32 offset = i * 2;
3822 // item entry
3823 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3824 // enchant
3825 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3828 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3831 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3833 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3835 if(m_items[i] == NULL)
3836 continue;
3838 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3841 if(target == this)
3843 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3845 if(m_items[i] == NULL)
3846 continue;
3848 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3850 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3852 if(m_items[i] == NULL)
3853 continue;
3855 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3859 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3862 void Player::DestroyForPlayer( Player *target, bool anim ) const
3864 Unit::DestroyForPlayer( target, anim );
3866 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3868 if(m_items[i] == NULL)
3869 continue;
3871 m_items[i]->DestroyForPlayer( target );
3874 if(target == this)
3876 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3878 if(m_items[i] == NULL)
3879 continue;
3881 m_items[i]->DestroyForPlayer( target );
3883 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3885 if(m_items[i] == NULL)
3886 continue;
3888 m_items[i]->DestroyForPlayer( target );
3893 bool Player::HasSpell(uint32 spell) const
3895 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3896 return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED &&
3897 !itr->second.disabled);
3900 bool Player::HasActiveSpell(uint32 spell) const
3902 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3903 return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED &&
3904 itr->second.active && !itr->second.disabled);
3907 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3909 if (!trainer_spell)
3910 return TRAINER_SPELL_RED;
3912 if (!trainer_spell->learnedSpell)
3913 return TRAINER_SPELL_RED;
3915 // known spell
3916 if(HasSpell(trainer_spell->learnedSpell))
3917 return TRAINER_SPELL_GRAY;
3919 // check race/class requirement
3920 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3921 return TRAINER_SPELL_RED;
3923 // check level requirement
3924 if(getLevel() < trainer_spell->reqLevel)
3925 return TRAINER_SPELL_RED;
3927 if(SpellChainNode const* spell_chain = sSpellMgr.GetSpellChainNode(trainer_spell->learnedSpell))
3929 // check prev.rank requirement
3930 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3931 return TRAINER_SPELL_RED;
3933 // check additional spell requirement
3934 if(spell_chain->req && !HasSpell(spell_chain->req))
3935 return TRAINER_SPELL_RED;
3938 // check skill requirement
3939 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3940 return TRAINER_SPELL_RED;
3942 // exist, already checked at loading
3943 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3945 // secondary prof. or not prof. spell
3946 uint32 skill = spell->EffectMiscValue[1];
3948 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3949 return TRAINER_SPELL_GREEN;
3951 // check primary prof. limit
3952 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
3953 return TRAINER_SPELL_GREEN_DISABLED;
3955 return TRAINER_SPELL_GREEN;
3958 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3960 uint32 guid = GUID_LOPART(playerguid);
3962 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3963 // bones will be deleted by corpse/bones deleting thread shortly
3964 sObjectAccessor.ConvertCorpseForPlayer(playerguid);
3966 // remove from guild
3967 uint32 guildId = GetGuildIdFromDB(playerguid);
3968 if(guildId != 0)
3970 Guild* guild = sObjectMgr.GetGuildById(guildId);
3971 if(guild)
3972 guild->DelMember(guid);
3975 // remove from arena teams
3976 LeaveAllArenaTeams(playerguid);
3978 // the player was uninvited already on logout so just remove from group
3979 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", guid);
3980 if(resultGroup)
3982 uint32 groupId = (*resultGroup)[0].GetUInt32();
3983 delete resultGroup;
3984 if (Group* group = sObjectMgr.GetGroupById(groupId))
3985 RemoveFromGroup(group, playerguid);
3988 // remove signs from petitions (also remove petitions if owner);
3989 RemovePetitionsAndSigns(playerguid, 10);
3991 // return back all mails with COD and Item 0 1 2 3 4 5 6 7
3992 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);
3993 if(resultMail)
3997 Field *fields = resultMail->Fetch();
3999 uint32 mail_id = fields[0].GetUInt32();
4000 uint16 mailType = fields[1].GetUInt16();
4001 uint16 mailTemplateId= fields[2].GetUInt16();
4002 uint32 sender = fields[3].GetUInt32();
4003 std::string subject = fields[4].GetCppString();
4004 uint32 itemTextId = fields[5].GetUInt32();
4005 uint32 money = fields[6].GetUInt32();
4006 bool has_items = fields[7].GetBool();
4008 //we can return mail now
4009 //so firstly delete the old one
4010 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
4012 // mail not from player
4013 if (mailType != MAIL_NORMAL)
4015 if(has_items)
4016 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
4017 continue;
4020 MailDraft draft(subject, itemTextId);
4021 if (mailTemplateId)
4022 draft = MailDraft(mailTemplateId,false); // itesm already included
4024 if(has_items)
4026 // data needs to be at first place for Item::LoadFromDB
4027 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);
4028 if(resultItems)
4032 Field *fields2 = resultItems->Fetch();
4034 uint32 item_guidlow = fields2[1].GetUInt32();
4035 uint32 item_template = fields2[2].GetUInt32();
4037 ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_template);
4038 if(!itemProto)
4040 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
4041 continue;
4044 Item *pItem = NewItemOrBag(itemProto);
4045 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
4047 pItem->FSetState(ITEM_REMOVED);
4048 pItem->SaveToDB(); // it also deletes item object !
4049 continue;
4052 draft.AddItem(pItem);
4054 while (resultItems->NextRow());
4056 delete resultItems;
4060 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
4062 uint32 pl_account = sObjectMgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
4064 draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender);
4066 while (resultMail->NextRow());
4068 delete resultMail;
4071 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
4072 // Get guids of character's pets, will deleted in transaction
4073 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
4075 // NOW we can finally clear other DB data related to character
4076 CharacterDatabase.BeginTransaction();
4077 if (resultPets)
4081 Field *fields3 = resultPets->Fetch();
4082 uint32 petguidlow = fields3[0].GetUInt32();
4083 Pet::DeleteFromDB(petguidlow);
4084 } while (resultPets->NextRow());
4085 delete resultPets;
4088 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
4089 CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid);
4090 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
4091 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
4092 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
4093 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
4094 CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid = '%u'",guid);
4095 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
4096 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
4097 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
4098 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
4099 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
4100 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",guid);
4101 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
4102 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u'",guid);
4103 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
4104 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
4105 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
4106 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
4107 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
4108 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
4109 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
4110 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
4111 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
4112 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
4113 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
4114 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
4115 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u'",guid);
4116 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid);
4117 CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid);
4118 CharacterDatabase.CommitTransaction();
4120 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4121 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
4124 void Player::SetMovement(PlayerMovementType pType)
4126 WorldPacket data;
4127 switch(pType)
4129 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
4130 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
4131 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
4132 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
4133 default:
4134 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
4135 return;
4137 data.append(GetPackGUID());
4138 data << uint32(0);
4139 GetSession()->SendPacket( &data );
4142 /* Preconditions:
4143 - a resurrectable corpse must not be loaded for the player (only bones)
4144 - the player must be in world
4146 void Player::BuildPlayerRepop()
4148 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
4149 data.append(GetPackGUID());
4150 GetSession()->SendPacket(&data);
4152 if(getRace() == RACE_NIGHTELF)
4153 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)
4154 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4156 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4157 // there must be SMSG.STOP_MIRROR_TIMER
4158 // there we must send 888 opcode
4160 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4161 if(GetCorpse())
4163 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4164 assert(false);
4167 // create a corpse and place it at the player's location
4168 CreateCorpse();
4169 Corpse *corpse = GetCorpse();
4170 if(!corpse)
4172 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4173 return;
4175 GetMap()->Add(corpse);
4177 // convert player body to ghost
4178 SetHealth( 1 );
4180 SetMovement(MOVE_WATER_WALK);
4181 if(!GetSession()->isLogingOut())
4182 SetMovement(MOVE_UNROOT);
4184 // BG - remove insignia related
4185 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
4187 SendCorpseReclaimDelay();
4189 // to prevent cheating
4190 corpse->ResetGhostTime();
4192 StopMirrorTimers(); //disable timers(bars)
4194 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
4196 // set and clear other
4197 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
4200 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
4202 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
4203 data << uint32(-1);
4204 data << float(0);
4205 data << float(0);
4206 data << float(0);
4207 GetSession()->SendPacket(&data);
4209 // speed change, land walk
4211 // remove death flag + set aura
4212 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4213 if(getRace() == RACE_NIGHTELF)
4214 RemoveAurasDueToSpell(20584); // speed bonuses
4215 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4217 setDeathState(ALIVE);
4219 SetMovement(MOVE_LAND_WALK);
4220 SetMovement(MOVE_UNROOT);
4222 m_deathTimer = 0;
4224 // set health/powers (0- will be set in caller)
4225 if(restore_percent>0.0f)
4227 SetHealth(uint32(GetMaxHealth()*restore_percent));
4228 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4229 SetPower(POWER_RAGE, 0);
4230 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4233 // trigger update zone for alive state zone updates
4234 uint32 newzone, newarea;
4235 GetZoneAndAreaId(newzone,newarea);
4236 UpdateZone(newzone,newarea);
4238 // update visibility
4239 UpdateVisibilityForPlayer();
4241 if(!applySickness)
4242 return;
4244 //Characters from level 1-10 are not affected by resurrection sickness.
4245 //Characters from level 11-19 will suffer from one minute of sickness
4246 //for each level they are above 10.
4247 //Characters level 20 and up suffer from ten minutes of sickness.
4248 int32 startLevel = sWorld.getConfig(CONFIG_INT32_DEATH_SICKNESS_LEVEL);
4250 if(int32(getLevel()) >= startLevel)
4252 // set resurrection sickness
4253 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4255 // not full duration
4256 if(int32(getLevel()) < startLevel+9)
4258 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4260 for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
4262 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,SpellEffectIndex(i)))
4264 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4265 Aur->SendAuraUpdate(false);
4272 void Player::KillPlayer()
4274 SetMovement(MOVE_ROOT);
4276 StopMirrorTimers(); //disable timers(bars)
4278 setDeathState(CORPSE);
4279 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4281 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4282 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4284 // 6 minutes until repop at graveyard
4285 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4287 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4289 // don't create corpse at this moment, player might be falling
4291 // update visibility
4292 UpdateObjectVisibility();
4295 void Player::CreateCorpse()
4297 // prevent existence 2 corpse for player
4298 SpawnCorpseBones();
4300 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4302 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4303 SetPvPDeath(false);
4305 if(!corpse->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4307 delete corpse;
4308 return;
4311 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4312 _pb = GetUInt32Value(PLAYER_BYTES);
4313 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4315 uint8 race = (uint8)(_uf);
4316 uint8 skin = (uint8)(_pb);
4317 uint8 face = (uint8)(_pb >> 8);
4318 uint8 hairstyle = (uint8)(_pb >> 16);
4319 uint8 haircolor = (uint8)(_pb >> 24);
4320 uint8 facialhair = (uint8)(_pb2);
4322 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4323 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4325 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4326 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4328 uint32 flags = CORPSE_FLAG_UNK2;
4329 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4330 flags |= CORPSE_FLAG_HIDE_HELM;
4331 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4332 flags |= CORPSE_FLAG_HIDE_CLOAK;
4333 if(InBattleGround() && !InArena())
4334 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4335 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4337 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4339 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4341 uint32 iDisplayID;
4342 uint32 iIventoryType;
4343 uint32 _cfi;
4344 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4346 if(m_items[i])
4348 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4349 iIventoryType = m_items[i]->GetProto()->InventoryType;
4351 _cfi = iDisplayID | (iIventoryType << 24);
4352 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi);
4356 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4357 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4358 assert(entry);
4359 if(entry->map_type != MAP_BATTLEGROUND)
4360 corpse->SaveToDB();
4362 // register for player, but not show
4363 sObjectAccessor.AddCorpse(corpse);
4366 void Player::SpawnCorpseBones()
4368 if(sObjectAccessor.ConvertCorpseForPlayer(GetGUID()))
4369 if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
4370 SaveToDB(); // prevent loading as ghost without corpse
4373 Corpse* Player::GetCorpse() const
4375 return sObjectAccessor.GetCorpseForPlayerGUID(GetGUID());
4378 void Player::DurabilityLossAll(double percent, bool inventory)
4380 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4381 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4382 DurabilityLoss(pItem,percent);
4384 if(inventory)
4386 // bags not have durability
4387 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4389 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4390 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4391 DurabilityLoss(pItem,percent);
4393 // keys not have durability
4394 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4396 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4397 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4398 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4399 if(Item* pItem = GetItemByPos( i, j ))
4400 DurabilityLoss(pItem,percent);
4404 void Player::DurabilityLoss(Item* item, double percent)
4406 if(!item )
4407 return;
4409 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4411 if(!pMaxDurability)
4412 return;
4414 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4416 if(pDurabilityLoss < 1 )
4417 pDurabilityLoss = 1;
4419 DurabilityPointsLoss(item,pDurabilityLoss);
4422 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4424 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4425 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4426 DurabilityPointsLoss(pItem,points);
4428 if(inventory)
4430 // bags not have durability
4431 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4433 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4434 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4435 DurabilityPointsLoss(pItem,points);
4437 // keys not have durability
4438 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4440 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4441 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4442 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4443 if(Item* pItem = GetItemByPos( i, j ))
4444 DurabilityPointsLoss(pItem,points);
4448 void Player::DurabilityPointsLoss(Item* item, int32 points)
4450 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4451 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4452 int32 pNewDurability = pOldDurability - points;
4454 if (pNewDurability < 0)
4455 pNewDurability = 0;
4456 else if (pNewDurability > pMaxDurability)
4457 pNewDurability = pMaxDurability;
4459 if (pOldDurability != pNewDurability)
4461 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4462 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4463 _ApplyItemMods(item,item->GetSlot(), false);
4465 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4467 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4468 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4469 _ApplyItemMods(item,item->GetSlot(), true);
4471 item->SetState(ITEM_CHANGED, this);
4475 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4477 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4478 DurabilityPointsLoss(pItem,1);
4481 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4483 uint32 TotalCost = 0;
4484 // equipped, backpack, bags itself
4485 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4486 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4488 // bank, buyback and keys not repaired
4490 // items in inventory bags
4491 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4492 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4493 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4494 return TotalCost;
4497 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4499 Item* item = GetItemByPos(pos);
4501 uint32 TotalCost = 0;
4502 if(!item)
4503 return TotalCost;
4505 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4506 if(!maxDurability)
4507 return TotalCost;
4509 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4511 if(cost)
4513 uint32 LostDurability = maxDurability - curDurability;
4514 if(LostDurability>0)
4516 ItemPrototype const *ditemProto = item->GetProto();
4518 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4519 if(!dcost)
4521 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4522 return TotalCost;
4525 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4526 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4527 if(!dQualitymodEntry)
4529 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4530 return TotalCost;
4533 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4534 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4536 costs = uint32(costs * discountMod);
4538 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4539 costs = 1;
4541 if (guildBank)
4543 if (GetGuildId()==0)
4545 DEBUG_LOG("You are not member of a guild");
4546 return TotalCost;
4549 Guild *pGuild = sObjectMgr.GetGuildById(GetGuildId());
4550 if (!pGuild)
4551 return TotalCost;
4553 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4555 DEBUG_LOG("You do not have rights to withdraw for repairs");
4556 return TotalCost;
4559 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4561 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4562 return TotalCost;
4565 if (pGuild->GetGuildBankMoney() < costs)
4567 DEBUG_LOG("There is not enough money in bank");
4568 return TotalCost;
4571 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4572 TotalCost = costs;
4574 else if (GetMoney() < costs)
4576 DEBUG_LOG("You do not have enough money");
4577 return TotalCost;
4579 else
4580 ModifyMoney( -int32(costs) );
4584 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4585 item->SetState(ITEM_CHANGED, this);
4587 // reapply mods for total broken and repaired item if equipped
4588 if(IsEquipmentPos(pos) && !curDurability)
4589 _ApplyItemMods(item,pos & 255, true);
4590 return TotalCost;
4593 void Player::RepopAtGraveyard()
4595 // note: this can be called also when the player is alive
4596 // for example from WorldSession::HandleMovementOpcodes
4598 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4600 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4601 if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport())
4603 ResurrectPlayer(0.5f);
4604 SpawnCorpseBones();
4607 WorldSafeLocsEntry const *ClosestGrave = NULL;
4609 // Special handle for battleground maps
4610 if( BattleGround *bg = GetBattleGround() )
4611 ClosestGrave = bg->GetClosestGraveYard(this);
4612 else
4613 ClosestGrave = sObjectMgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4615 // stop countdown until repop
4616 m_deathTimer = 0;
4618 // if no grave found, stay at the current location
4619 // and don't show spirit healer location
4620 if(ClosestGrave)
4622 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4623 if(isDead()) // not send if alive, because it used in TeleportTo()
4625 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4626 data << ClosestGrave->map_id;
4627 data << ClosestGrave->x;
4628 data << ClosestGrave->y;
4629 data << ClosestGrave->z;
4630 GetSession()->SendPacket(&data);
4635 void Player::JoinedChannel(Channel *c)
4637 m_channels.push_back(c);
4640 void Player::LeftChannel(Channel *c)
4642 m_channels.remove(c);
4645 void Player::CleanupChannels()
4647 while(!m_channels.empty())
4649 Channel* ch = *m_channels.begin();
4650 m_channels.erase(m_channels.begin()); // remove from player's channel list
4651 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4652 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4653 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4656 sLog.outDebug("Player: channels cleaned up!");
4659 void Player::UpdateLocalChannels(uint32 newZone )
4661 if(m_channels.empty())
4662 return;
4664 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4665 if(!current_zone)
4666 return;
4668 ChannelMgr* cMgr = channelMgr(GetTeam());
4669 if(!cMgr)
4670 return;
4672 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4674 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4676 next = i; ++next;
4678 // skip non built-in channels
4679 if(!(*i)->IsConstant())
4680 continue;
4682 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4683 if(!ch)
4684 continue;
4686 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4687 continue;
4689 // new channel
4690 char new_channel_name_buf[100];
4691 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4692 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4694 if((*i)!=new_channel)
4696 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4698 // leave old channel
4699 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4700 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4701 LeftChannel(*i); // remove from player's channel list
4702 cMgr->LeftChannel(name); // delete if empty
4705 sLog.outDebug("Player: channels cleaned up!");
4708 void Player::LeaveLFGChannel()
4710 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4712 if((*i)->IsLFG())
4714 (*i)->Leave(GetGUID());
4715 break;
4720 void Player::UpdateDefense()
4722 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_DEFENSE);
4724 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4726 // update dependent from defense skill part
4727 UpdateDefenseBonusesMod();
4731 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4733 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4735 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4736 return;
4739 float val = 1.0f;
4741 switch(modType)
4743 case FLAT_MOD:
4744 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4745 break;
4746 case PCT_MOD:
4747 if(amount <= -100.0f)
4748 amount = -200.0f;
4750 val = (100.0f + amount) / 100.0f;
4751 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4752 break;
4755 if(!CanModifyStats())
4756 return;
4758 switch(modGroup)
4760 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4761 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4762 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4763 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4764 default: break;
4768 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4770 if(modGroup >= BASEMOD_END || modType > MOD_END)
4772 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4773 return 0.0f;
4776 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4777 return 0.0f;
4779 return m_auraBaseMod[modGroup][modType];
4782 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4784 if(modGroup >= BASEMOD_END)
4786 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4787 return 0.0f;
4790 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4791 return 0.0f;
4793 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4796 uint32 Player::GetShieldBlockValue() const
4798 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4800 value = (value < 0) ? 0 : value;
4802 return uint32(value);
4805 float Player::GetMeleeCritFromAgility()
4807 uint32 level = getLevel();
4808 uint32 pclass = getClass();
4810 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4812 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4813 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4814 if (critBase==NULL || critRatio==NULL)
4815 return 0.0f;
4817 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4818 return crit*100.0f;
4821 float Player::GetDodgeFromAgility()
4823 // Table for base dodge values
4824 float dodge_base[MAX_CLASSES] = {
4825 0.0075f, // Warrior
4826 0.00652f, // Paladin
4827 -0.0545f, // Hunter
4828 -0.0059f, // Rogue
4829 0.03183f, // Priest
4830 0.0114f, // DK
4831 0.0167f, // Shaman
4832 0.034575f, // Mage
4833 0.02011f, // Warlock
4834 0.0f, // ??
4835 -0.0187f // Druid
4837 // Crit/agility to dodge/agility coefficient multipliers
4838 float crit_to_dodge[MAX_CLASSES] = {
4839 1.1f, // Warrior
4840 1.0f, // Paladin
4841 1.6f, // Hunter
4842 2.0f, // Rogue
4843 1.0f, // Priest
4844 1.0f, // DK?
4845 1.0f, // Shaman
4846 1.0f, // Mage
4847 1.0f, // Warlock
4848 0.0f, // ??
4849 1.7f // Druid
4852 uint32 level = getLevel();
4853 uint32 pclass = getClass();
4855 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4857 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4858 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4859 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4860 return 0.0f;
4862 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4863 return dodge*100.0f;
4866 float Player::GetSpellCritFromIntellect()
4868 uint32 level = getLevel();
4869 uint32 pclass = getClass();
4871 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4873 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4874 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4875 if (critBase==NULL || critRatio==NULL)
4876 return 0.0f;
4878 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4879 return crit*100.0f;
4882 float Player::GetRatingCoefficient(CombatRating cr) const
4884 uint32 level = getLevel();
4886 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4888 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4889 if (Rating == NULL)
4890 return 1.0f; // By default use minimum coefficient (not must be called)
4892 return Rating->ratio;
4895 float Player::GetRatingBonusValue(CombatRating cr) const
4897 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4900 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4902 switch (attType)
4904 case BASE_ATTACK:
4905 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4906 case OFF_ATTACK:
4907 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4908 default:
4909 break;
4911 return 0.0f;
4914 float Player::OCTRegenHPPerSpirit()
4916 uint32 level = getLevel();
4917 uint32 pclass = getClass();
4919 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4921 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4922 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4923 if (baseRatio==NULL || moreRatio==NULL)
4924 return 0.0f;
4926 // Formula from PaperDollFrame script
4927 float spirit = GetStat(STAT_SPIRIT);
4928 float baseSpirit = spirit;
4929 if (baseSpirit>50) baseSpirit = 50;
4930 float moreSpirit = spirit - baseSpirit;
4931 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4932 return regen;
4935 float Player::OCTRegenMPPerSpirit()
4937 uint32 level = getLevel();
4938 uint32 pclass = getClass();
4940 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4942 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4943 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4944 if (moreRatio==NULL)
4945 return 0.0f;
4947 // Formula get from PaperDollFrame script
4948 float spirit = GetStat(STAT_SPIRIT);
4949 float regen = spirit * moreRatio->ratio;
4950 return regen;
4953 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4955 m_baseRatingValue[cr]+=(apply ? value : -value);
4957 // explicit affected values
4958 switch (cr)
4960 case CR_HASTE_MELEE:
4962 float RatingChange = value / GetRatingCoefficient(cr);
4963 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4964 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4965 break;
4967 case CR_HASTE_RANGED:
4969 float RatingChange = value / GetRatingCoefficient(cr);
4970 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4971 break;
4973 case CR_HASTE_SPELL:
4975 float RatingChange = value / GetRatingCoefficient(cr);
4976 ApplyCastTimePercentMod(RatingChange,apply);
4977 break;
4981 UpdateRating(cr);
4984 void Player::UpdateRating(CombatRating cr)
4986 int32 amount = m_baseRatingValue[cr];
4987 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4988 // stat used stored in miscValueB for this aura
4989 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4990 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4991 if ((*i)->GetMiscValue() & (1<<cr))
4992 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4993 if (amount < 0)
4994 amount = 0;
4995 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4997 bool affectStats = CanModifyStats();
4999 switch (cr)
5001 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
5002 case CR_DEFENSE_SKILL:
5003 UpdateDefenseBonusesMod();
5004 break;
5005 case CR_DODGE:
5006 UpdateDodgePercentage();
5007 break;
5008 case CR_PARRY:
5009 UpdateParryPercentage();
5010 break;
5011 case CR_BLOCK:
5012 UpdateBlockPercentage();
5013 break;
5014 case CR_HIT_MELEE:
5015 UpdateMeleeHitChances();
5016 break;
5017 case CR_HIT_RANGED:
5018 UpdateRangedHitChances();
5019 break;
5020 case CR_HIT_SPELL:
5021 UpdateSpellHitChances();
5022 break;
5023 case CR_CRIT_MELEE:
5024 if(affectStats)
5026 UpdateCritPercentage(BASE_ATTACK);
5027 UpdateCritPercentage(OFF_ATTACK);
5029 break;
5030 case CR_CRIT_RANGED:
5031 if(affectStats)
5032 UpdateCritPercentage(RANGED_ATTACK);
5033 break;
5034 case CR_CRIT_SPELL:
5035 if(affectStats)
5036 UpdateAllSpellCritChances();
5037 break;
5038 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
5039 case CR_HIT_TAKEN_RANGED:
5040 break;
5041 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
5042 break;
5043 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
5044 case CR_CRIT_TAKEN_RANGED:
5045 break;
5046 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
5047 break;
5048 case CR_HASTE_MELEE: // Implemented in Player::ApplyRatingMod
5049 case CR_HASTE_RANGED:
5050 case CR_HASTE_SPELL:
5051 break;
5052 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
5053 case CR_WEAPON_SKILL_OFFHAND:
5054 case CR_WEAPON_SKILL_RANGED:
5055 break;
5056 case CR_EXPERTISE:
5057 if(affectStats)
5059 UpdateExpertise(BASE_ATTACK);
5060 UpdateExpertise(OFF_ATTACK);
5062 break;
5063 case CR_ARMOR_PENETRATION:
5064 if(affectStats)
5065 UpdateArmorPenetration();
5066 break;
5070 void Player::UpdateAllRatings()
5072 for(int cr = 0; cr < MAX_COMBAT_RATING; ++cr)
5073 UpdateRating(CombatRating(cr));
5076 void Player::SetRegularAttackTime()
5078 for(int i = 0; i < MAX_ATTACK; ++i)
5080 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i),true,false);
5081 if (tmpitem)
5083 ItemPrototype const *proto = tmpitem->GetProto();
5084 if(proto->Delay)
5085 SetAttackTime(WeaponAttackType(i), proto->Delay);
5086 else
5087 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
5092 //skill+step, checking for max value
5093 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
5095 if(!skill_id)
5096 return false;
5098 SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
5099 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5100 return false;
5102 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5103 uint32 data = GetUInt32Value(valueIndex);
5104 uint32 value = SKILL_VALUE(data);
5105 uint32 max = SKILL_MAX(data);
5107 if ((!max) || (!value) || (value >= max))
5108 return false;
5110 if (value*512 < max*urand(0,512))
5112 uint32 new_value = value+step;
5113 if(new_value > max)
5114 new_value = max;
5116 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,max));
5117 if(itr->second.uState != SKILL_NEW)
5118 itr->second.uState = SKILL_CHANGED;
5119 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
5120 return true;
5123 return false;
5126 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
5128 if ( SkillValue >= GrayLevel )
5129 return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREY)*10;
5130 if ( SkillValue >= GreenLevel )
5131 return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREEN)*10;
5132 if ( SkillValue >= YellowLevel )
5133 return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_YELLOW)*10;
5134 return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_ORANGE)*10;
5137 bool Player::UpdateCraftSkill(uint32 spellid)
5139 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
5141 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spellid);
5143 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
5145 if (_spell_idx->second->skillId)
5147 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
5149 // Alchemy Discoveries here
5150 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
5151 if (spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
5153 if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
5154 learnSpell(discoveredSpell,false);
5157 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_CRAFTING);
5159 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
5160 _spell_idx->second->max_value,
5161 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
5162 _spell_idx->second->min_value),
5163 craft_skill_gain);
5166 return false;
5169 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
5171 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
5173 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING);
5175 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5176 switch (SkillId)
5178 case SKILL_HERBALISM:
5179 case SKILL_LOCKPICKING:
5180 case SKILL_JEWELCRAFTING:
5181 case SKILL_INSCRIPTION:
5182 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5183 case SKILL_SKINNING:
5184 if( sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS)==0)
5185 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5186 else
5187 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
5188 case SKILL_MINING:
5189 if (sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS)==0)
5190 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5191 else
5192 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
5194 return false;
5197 bool Player::UpdateFishingSkill()
5199 sLog.outDebug("UpdateFishingSkill");
5201 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5203 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5205 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING);
5207 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5210 // levels sync. with spell requirement for skill levels to learn
5211 // bonus abilities in sSkillLineAbilityStore
5212 // Used only to avoid scan DBC at each skill grow
5213 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5215 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5217 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5218 if ( !SkillId )
5219 return false;
5221 if(Chance <= 0) // speedup in 0 chance case
5223 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5224 return false;
5227 SkillStatusMap::iterator itr = mSkillStatus.find(SkillId);
5228 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5229 return false;
5231 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5233 uint32 data = GetUInt32Value(valueIndex);
5234 uint16 SkillValue = SKILL_VALUE(data);
5235 uint16 MaxValue = SKILL_MAX(data);
5237 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5238 return false;
5240 int32 Roll = irand(1,1000);
5242 if ( Roll <= Chance )
5244 uint32 new_value = SkillValue+step;
5245 if(new_value > MaxValue)
5246 new_value = MaxValue;
5248 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,MaxValue));
5249 if(itr->second.uState != SKILL_NEW)
5250 itr->second.uState = SKILL_CHANGED;
5251 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5253 if((SkillValue < *bsl && new_value >= *bsl))
5255 learnSkillRewardedSpells( SkillId, new_value);
5256 break;
5259 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5260 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5261 return true;
5264 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5265 return false;
5268 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5270 // no skill gain in pvp
5271 Unit *pVictim = getVictim();
5272 if(pVictim && pVictim->IsCharmerOrOwnerPlayerOrPlayerItself())
5273 return;
5275 if(IsInFeralForm())
5276 return; // always maximized SKILL_FERAL_COMBAT in fact
5278 if(m_form == FORM_TREE)
5279 return; // use weapon but not skill up
5281 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_WEAPON);
5283 switch(attType)
5285 case BASE_ATTACK:
5287 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5289 if (!tmpitem)
5290 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5291 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5292 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5293 break;
5295 case OFF_ATTACK:
5296 case RANGED_ATTACK:
5298 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5299 if (tmpitem)
5300 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5301 break;
5304 UpdateAllCritPercentages();
5307 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5309 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5310 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5311 uint32 moblevel = pVictim->getLevelForTarget(this);
5312 if(moblevel < greylevel)
5313 return;
5315 if (moblevel > plevel + 5)
5316 moblevel = plevel + 5;
5318 uint32 lvldif = moblevel - greylevel;
5319 if(lvldif < 3)
5320 lvldif = 3;
5322 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5323 if(skilldif <= 0)
5324 return;
5326 float chance = float(3 * lvldif * skilldif) / plevel;
5327 if(!defence)
5329 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5330 chance *= 0.1f * GetStat(STAT_INTELLECT);
5333 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5335 if(roll_chance_f(chance))
5337 if(defence)
5338 UpdateDefense();
5339 else
5340 UpdateWeaponSkill(attType);
5342 else
5343 return;
5346 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5348 SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid);
5349 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5350 return;
5352 uint32 bonusIndex = PLAYER_SKILL_BONUS_INDEX(itr->second.pos);
5354 uint32 bonus_val = GetUInt32Value(bonusIndex);
5355 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5356 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5358 if(talent) // permanent bonus stored in high part
5359 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5360 else // temporary/item bonus stored in low part
5361 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5364 void Player::UpdateSkillsForLevel()
5366 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5367 uint32 maxSkill = GetMaxSkillValueForLevel();
5369 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_BOOL_ALWAYS_MAX_SKILL_FOR_LEVEL);
5371 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5373 if(itr->second.uState == SKILL_DELETED)
5374 continue;
5376 uint32 pskill = itr->first;
5378 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5379 if(!pSkill)
5380 continue;
5382 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5383 continue;
5385 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5386 uint32 data = GetUInt32Value(valueIndex);
5387 uint32 max = SKILL_MAX(data);
5388 uint32 val = SKILL_VALUE(data);
5390 /// update only level dependent max skill values
5391 if(max!=1)
5393 /// maximize skill always
5394 if(alwaysMaxSkill)
5396 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(maxSkill,maxSkill));
5397 if(itr->second.uState != SKILL_NEW)
5398 itr->second.uState = SKILL_CHANGED;
5400 else if(max != maxconfskill) /// update max skill value if current max skill not maximized
5402 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(val,maxSkill));
5403 if(itr->second.uState != SKILL_NEW)
5404 itr->second.uState = SKILL_CHANGED;
5410 void Player::UpdateSkillsToMaxSkillsForLevel()
5412 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5414 if(itr->second.uState == SKILL_DELETED)
5415 continue;
5417 uint32 pskill = itr->first;
5418 if( IsProfessionOrRidingSkill(pskill))
5419 continue;
5420 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5421 uint32 data = GetUInt32Value(valueIndex);
5423 uint32 max = SKILL_MAX(data);
5425 if(max > 1)
5427 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(max,max));
5428 if(itr->second.uState != SKILL_NEW)
5429 itr->second.uState = SKILL_CHANGED;
5432 if(pskill == SKILL_DEFENSE)
5433 UpdateDefenseBonusesMod();
5437 // This functions sets a skill line value (and adds if doesn't exist yet)
5438 // To "remove" a skill line, set it's values to zero
5439 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5441 if(!id)
5442 return;
5444 SkillStatusMap::iterator itr = mSkillStatus.find(id);
5446 //has skill
5447 if(itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED)
5449 if(currVal)
5451 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),MAKE_SKILL_VALUE(currVal,maxVal));
5452 if(itr->second.uState != SKILL_NEW)
5453 itr->second.uState = SKILL_CHANGED;
5454 learnSkillRewardedSpells(id, currVal);
5455 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5456 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5458 else //remove
5460 // clear skill fields
5461 SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos),0);
5462 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),0);
5463 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos),0);
5465 // mark as deleted or simply remove from map if not saved yet
5466 if(itr->second.uState != SKILL_NEW)
5467 itr->second.uState = SKILL_DELETED;
5468 else
5469 mSkillStatus.erase(itr);
5471 // remove all spells that related to this skill
5472 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5473 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5474 if (pAbility->skillId==id)
5475 removeSpell(sSpellMgr.GetFirstSpellInChain(pAbility->spellId));
5478 else if(currVal) //add
5480 for (int i=0; i < PLAYER_MAX_SKILLS; ++i)
5481 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5483 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5484 if(!pSkill)
5486 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5487 return;
5489 // enable unlearn button for primary professions only
5490 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5491 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5492 else
5493 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5494 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5495 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5496 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5498 // insert new entry or update if not deleted old entry yet
5499 if(itr != mSkillStatus.end())
5501 itr->second.pos = i;
5502 itr->second.uState = SKILL_CHANGED;
5504 else
5505 mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW)));
5507 // apply skill bonuses
5508 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5510 // temporary bonuses
5511 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5512 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5513 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5514 (*j)->ApplyModifier(true);
5516 // permanent bonuses
5517 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5518 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5519 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5520 (*j)->ApplyModifier(true);
5522 // Learn all spells for skill
5523 learnSkillRewardedSpells(id, currVal);
5524 return;
5529 bool Player::HasSkill(uint32 skill) const
5531 if(!skill)
5532 return false;
5534 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5535 return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED);
5538 uint16 Player::GetSkillValue(uint32 skill) const
5540 if(!skill)
5541 return 0;
5543 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5544 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5545 return 0;
5547 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5549 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5550 result += SKILL_TEMP_BONUS(bonus);
5551 result += SKILL_PERM_BONUS(bonus);
5552 return result < 0 ? 0 : result;
5555 uint16 Player::GetMaxSkillValue(uint32 skill) const
5557 if(!skill)
5558 return 0;
5560 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5561 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5562 return 0;
5564 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5566 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5567 result += SKILL_TEMP_BONUS(bonus);
5568 result += SKILL_PERM_BONUS(bonus);
5569 return result < 0 ? 0 : result;
5572 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5574 if(!skill)
5575 return 0;
5577 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5578 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5579 return 0;
5581 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5584 uint16 Player::GetBaseSkillValue(uint32 skill) const
5586 if(!skill)
5587 return 0;
5589 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5590 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5591 return 0;
5593 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5594 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5595 return result < 0 ? 0 : result;
5598 uint16 Player::GetPureSkillValue(uint32 skill) const
5600 if(!skill)
5601 return 0;
5603 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5604 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5605 return 0;
5607 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5610 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5612 if(!skill)
5613 return 0;
5615 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5616 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5617 return 0;
5619 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5622 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5624 if(!skill)
5625 return 0;
5627 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5628 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5629 return 0;
5631 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5634 void Player::SendInitialActionButtons() const
5636 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5638 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5639 data << uint8(1); // can be 0, 1, 2 (talent spec)
5640 ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
5641 for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button)
5643 ActionButtonList::const_iterator itr = currentActionButtonList.find(button);
5644 if(itr != currentActionButtonList.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5645 data << uint32(itr->second.packedData);
5646 else
5647 data << uint32(0);
5650 GetSession()->SendPacket( &data );
5651 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5654 bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Player* player, bool msg)
5656 if(button >= MAX_ACTION_BUTTONS)
5658 if (msg)
5660 if (player)
5661 sLog.outError( "Action %u not added into button %u for player %s: button must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTONS );
5662 else
5663 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action, button, MAX_ACTION_BUTTONS );
5666 return false;
5669 if(action >= MAX_ACTION_BUTTON_ACTION_VALUE)
5671 if (msg)
5673 if (player)
5674 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 );
5675 else
5676 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action, button, MAX_ACTION_BUTTON_ACTION_VALUE );
5678 return false;
5681 switch(type)
5683 case ACTION_BUTTON_SPELL:
5684 if(!sSpellStore.LookupEntry(action))
5686 if (msg)
5688 if (player)
5689 sLog.outError( "Spell action %u not added into button %u for player %s: spell not exist", action, button, player->GetName() );
5690 else
5691 sLog.outError( "Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action, button );
5693 return false;
5696 if(player && !player->HasSpell(action))
5698 if (msg)
5699 sLog.outError( "Spell action %u not added into button %u for player %s: player don't known this spell", action, button, player->GetName() );
5700 return false;
5702 break;
5703 case ACTION_BUTTON_ITEM:
5704 if(!ObjectMgr::GetItemPrototype(action))
5706 if (msg)
5708 if (player)
5709 sLog.outError( "Item action %u not added into button %u for player %s: item not exist", action, button, player->GetName() );
5710 else
5711 sLog.outError( "Table `playercreateinfo_action` have item action %u into button %u: item not exist", action, button );
5713 return false;
5715 break;
5716 default:
5717 break; // other cases not checked at this moment
5720 return true;
5723 ActionButton* Player::addActionButton(uint8 spec, uint8 button, uint32 action, uint8 type)
5725 // check action only for active spec (so not check at copy/load passive spec)
5726 if (spec == GetActiveSpec() && !IsActionButtonDataValid(button,action,type,this))
5727 return NULL;
5729 // it create new button (NEW state) if need or return existed
5730 ActionButton& ab = m_actionButtons[spec][button];
5732 // set data and update to CHANGED if not NEW
5733 ab.SetActionAndType(action,ActionButtonType(type));
5735 sLog.outDetail("Player '%u' Added Action '%u' (type %u) to Button '%u' for spec %u", GetGUIDLow(), action, uint32(type), button, spec);
5736 return &ab;
5739 void Player::removeActionButton(uint8 spec, uint8 button)
5741 ActionButtonList& currentActionButtonList = m_actionButtons[spec];
5742 ActionButtonList::iterator buttonItr = currentActionButtonList.find(button);
5743 if (buttonItr == currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
5744 return;
5746 if (buttonItr->second.uState == ACTIONBUTTON_NEW)
5747 currentActionButtonList.erase(buttonItr); // new and not saved
5748 else
5749 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5751 sLog.outDetail("Action Button '%u' Removed from Player '%u' for spec %u", button, GetGUIDLow(), spec);
5754 ActionButton const* Player::GetActionButton(uint8 button)
5756 ActionButtonList& currentActionButtonList = m_actionButtons[m_activeSpec];
5757 ActionButtonList::iterator buttonItr = currentActionButtonList.find(button);
5758 if (buttonItr==currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
5759 return NULL;
5761 return &buttonItr->second;
5764 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5766 // prevent crash when a bad coord is sent by the client
5767 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5769 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5770 return false;
5773 Map *m = GetMap();
5775 const float old_x = GetPositionX();
5776 const float old_y = GetPositionY();
5777 const float old_z = GetPositionZ();
5778 const float old_r = GetOrientation();
5780 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5782 if (teleport || old_x != x || old_y != y || old_z != z)
5783 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5784 else
5785 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5787 // move and update visible state if need
5788 m->PlayerRelocation(this, x, y, z, orientation);
5790 // reread after Map::Relocation
5791 m = GetMap();
5792 x = GetPositionX();
5793 y = GetPositionY();
5794 z = GetPositionZ();
5796 // group update
5797 if(GetGroup() && (old_x != x || old_y != y))
5798 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5801 // code block for underwater state update
5802 UpdateUnderwaterState(m, x, y, z);
5804 CheckExploreSystem();
5806 return true;
5809 void Player::SaveRecallPosition()
5811 m_recallMap = GetMapId();
5812 m_recallX = GetPositionX();
5813 m_recallY = GetPositionY();
5814 m_recallZ = GetPositionZ();
5815 m_recallO = GetOrientation();
5818 void Player::SendMessageToSet(WorldPacket *data, bool self)
5820 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5821 if(_map)
5823 _map->MessageBroadcast(this, data, self);
5824 return;
5827 //if player is not in world and map in not created/already destroyed
5828 //no need to create one, just send packet for itself!
5829 if(self)
5830 GetSession()->SendPacket(data);
5833 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5835 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5836 if(_map)
5838 _map->MessageDistBroadcast(this, data, dist, self);
5839 return;
5842 if(self)
5843 GetSession()->SendPacket(data);
5846 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5848 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5849 if(_map)
5851 _map->MessageDistBroadcast(this, data, dist, self, own_team_only);
5852 return;
5855 if(self)
5856 GetSession()->SendPacket(data);
5859 void Player::SendDirectMessage(WorldPacket *data)
5861 GetSession()->SendPacket(data);
5864 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5866 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5867 data << uint32(CinematicSequenceId);
5868 SendDirectMessage(&data);
5871 void Player::SendMovieStart(uint32 MovieId)
5873 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5874 data << uint32(MovieId);
5875 SendDirectMessage(&data);
5878 void Player::CheckExploreSystem()
5880 if (!isAlive())
5881 return;
5883 if (isInFlight())
5884 return;
5886 uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5887 if(areaFlag==0xffff)
5888 return;
5889 int offset = areaFlag / 32;
5891 if(offset >= 128)
5893 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);
5894 return;
5897 uint32 val = (uint32)(1 << (areaFlag % 32));
5898 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5900 if( !(currFields & val) )
5902 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5904 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5906 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5907 if(!p)
5909 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5911 else if(p->area_level > 0)
5913 uint32 area = p->ID;
5914 if (getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
5916 SendExplorationExperience(area,0);
5918 else
5920 int32 diff = int32(getLevel()) - p->area_level;
5921 uint32 XP = 0;
5922 if (diff < -5)
5924 XP = uint32(sObjectMgr.GetBaseXP(getLevel()+5)*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
5926 else if (diff > 5)
5928 int32 exploration_percent = (100-((diff-5)*5));
5929 if (exploration_percent > 100)
5930 exploration_percent = 100;
5931 else if (exploration_percent < 0)
5932 exploration_percent = 0;
5934 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
5936 else
5938 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
5941 GiveXP( XP, NULL );
5942 SendExplorationExperience(area,XP);
5944 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5949 uint32 Player::TeamForRace(uint8 race)
5951 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5952 if(!rEntry)
5954 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5955 return ALLIANCE;
5958 switch(rEntry->TeamID)
5960 case 7: return ALLIANCE;
5961 case 1: return HORDE;
5964 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5965 return ALLIANCE;
5968 uint32 Player::getFactionForRace(uint8 race)
5970 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5971 if(!rEntry)
5973 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5974 return 0;
5977 return rEntry->FactionID;
5980 void Player::setFactionForRace(uint8 race)
5982 m_team = TeamForRace(race);
5983 setFaction( getFactionForRace(race) );
5986 ReputationRank Player::GetReputationRank(uint32 faction) const
5988 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5989 return GetReputationMgr().GetRank(factionEntry);
5992 //Calculate total reputation percent player gain with quest/creature level
5993 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5995 float percent = 100.0f;
5997 float rate = for_quest ? sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_KILL);
5999 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
6000 percent *= rate;
6002 float repMod = (float)GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
6004 if (!for_quest)
6005 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
6007 percent += rep > 0 ? repMod : -repMod;
6009 if (percent <= 0.0f)
6010 return 0;
6012 return int32(sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_GAIN)*rep*percent/100.0f);
6015 //Calculates how many reputation points player gains in victim's enemy factions
6016 void Player::RewardReputation(Unit *pVictim, float rate)
6018 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
6019 return;
6021 ReputationOnKillEntry const* Rep = sObjectMgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
6023 if(!Rep)
6024 return;
6026 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
6028 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
6029 donerep1 = int32(donerep1*rate);
6030 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
6031 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
6032 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
6033 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
6035 // Wiki: Team factions value divided by 2
6036 if (factionEntry1 && Rep->is_teamaward1)
6038 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
6039 if(team1_factionEntry)
6040 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
6044 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
6046 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
6047 donerep2 = int32(donerep2*rate);
6048 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
6049 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
6050 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
6051 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
6053 // Wiki: Team factions value divided by 2
6054 if (factionEntry2 && Rep->is_teamaward2)
6056 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
6057 if(team2_factionEntry)
6058 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
6063 //Calculate how many reputation points player gain with the quest
6064 void Player::RewardReputation(Quest const *pQuest)
6066 // quest reputation reward/loss
6067 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
6069 if (!pQuest->RewRepFaction[i])
6070 continue;
6072 // For future, this row should be used as "override". Example quests are 10298 and 10870.
6073 // Typically, no diplomacy mod must apply to the final value (flat). Note the formula must be (finalValue = DBvalue/100)
6074 if (pQuest->RewRepValue[i])
6076 int32 rep = CalculateReputationGain(GetQuestLevelForPlayer(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
6078 if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
6079 GetReputationMgr().ModifyReputation(factionEntry, rep);
6081 else
6083 uint32 row = ((pQuest->RewRepValueId[i] < 0) ? 1 : 0) + 1;
6084 uint32 field = abs(pQuest->RewRepValueId[i]);
6086 if (const QuestFactionRewardEntry *pRow = sQuestFactionRewardStore.LookupEntry(row))
6088 int32 repPoints = pRow->rewardValue[field];
6090 if (!repPoints)
6091 continue;
6093 repPoints = CalculateReputationGain(GetQuestLevelForPlayer(pQuest), repPoints, pQuest->RewRepFaction[i], true);
6095 if (const FactionEntry* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
6096 GetReputationMgr().ModifyReputation(factionEntry, repPoints);
6101 // TODO: implement reputation spillover
6104 void Player::UpdateArenaFields(void)
6106 /* arena calcs go here */
6109 void Player::UpdateHonorFields()
6111 /// called when rewarding honor and at each save
6112 time_t now = time(NULL);
6113 time_t today = (time(NULL) / DAY) * DAY;
6115 if(m_lastHonorUpdateTime < today)
6117 time_t yesterday = today - DAY;
6119 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
6121 // update yesterday's contribution
6122 if(m_lastHonorUpdateTime >= yesterday )
6124 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
6126 // this is the first update today, reset today's contribution
6127 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
6128 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
6130 else
6132 // no honor/kills yesterday or today, reset
6133 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
6134 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
6138 m_lastHonorUpdateTime = now;
6141 ///Calculate the amount of honor gained based on the victim
6142 ///and the size of the group for which the honor is divided
6143 ///An exact honor value can also be given (overriding the calcs)
6144 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
6146 // do not reward honor in arenas, but enable onkill spellproc
6147 if(InArena())
6149 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
6150 return false;
6152 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
6153 return false;
6155 return true;
6158 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6159 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
6160 return false;
6162 uint64 victim_guid = 0;
6163 uint32 victim_rank = 0;
6165 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6166 UpdateHonorFields();
6168 if(honor <= 0)
6170 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
6171 return false;
6173 victim_guid = uVictim->GetGUID();
6175 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6177 Player *pVictim = (Player *)uVictim;
6179 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6180 return false;
6182 float f = 1; //need for total kills (?? need more info)
6183 uint32 k_grey = 0;
6184 uint32 k_level = getLevel();
6185 uint32 v_level = pVictim->getLevel();
6188 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6189 // [0] Just name
6190 // [1..14] Alliance honor titles and player name
6191 // [15..28] Horde honor titles and player name
6192 // [29..38] Other title and player name
6193 // [39+] Nothing
6194 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6195 // Get Killer titles, CharTitlesEntry::bit_index
6196 // Ranks:
6197 // title[1..14] -> rank[5..18]
6198 // title[15..28] -> rank[5..18]
6199 // title[other] -> 0
6200 if (victim_title == 0)
6201 victim_guid = 0; // Don't show HK: <rank> message, only log.
6202 else if (victim_title < 15)
6203 victim_rank = victim_title + 4;
6204 else if (victim_title < 29)
6205 victim_rank = victim_title - 14 + 4;
6206 else
6207 victim_guid = 0; // Don't show HK: <rank> message, only log.
6210 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6212 if(v_level<=k_grey)
6213 return false;
6215 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6217 int32 v_rank =1; //need more info
6219 honor = ((f * diff_level * (190 + v_rank*10))/6);
6220 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6222 // count the number of playerkills in one day
6223 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6224 // and those in a lifetime
6225 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6226 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
6227 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
6228 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
6230 else
6232 Creature *cVictim = (Creature *)uVictim;
6234 if (!cVictim->isRacialLeader())
6235 return false;
6237 honor = 100; // ??? need more info
6238 victim_rank = 19; // HK: Leader
6242 if (uVictim != NULL)
6244 honor *= sWorld.getConfig(CONFIG_FLOAT_RATE_HONOR);
6245 honor *= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN) + 100.0f)/100.0f;
6247 if(groupsize > 1)
6248 honor /= groupsize;
6250 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6253 // honor - for show honor points in log
6254 // victim_guid - for show victim name in log
6255 // victim_rank [1..4] HK: <dishonored rank>
6256 // victim_rank [5..19] HK: <alliance\horde rank>
6257 // victim_rank [0,20+] HK: <>
6258 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6259 data << (uint32) honor;
6260 data << (uint64) victim_guid;
6261 data << (uint32) victim_rank;
6263 GetSession()->SendPacket(&data);
6265 // add honor points
6266 ModifyHonorPoints(int32(honor));
6268 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6269 return true;
6272 void Player::ModifyHonorPoints( int32 value )
6274 if(value < 0)
6276 if (GetHonorPoints() > sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS))
6277 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS) + value);
6278 else
6279 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6281 else
6282 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS));
6285 void Player::ModifyArenaPoints( int32 value )
6287 if(value < 0)
6289 if (GetArenaPoints() > sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS))
6290 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS) + value);
6291 else
6292 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6294 else
6295 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS));
6298 uint32 Player::GetGuildIdFromDB(uint64 guid)
6300 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6301 if(!result)
6302 return 0;
6304 uint32 id = result->Fetch()[0].GetUInt32();
6305 delete result;
6306 return id;
6309 uint32 Player::GetRankFromDB(uint64 guid)
6311 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6312 if( result )
6314 uint32 v = result->Fetch()[0].GetUInt32();
6315 delete result;
6316 return v;
6318 else
6319 return 0;
6322 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6324 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);
6325 if(!result)
6326 return 0;
6328 uint32 id = (*result)[0].GetUInt32();
6329 delete result;
6330 return id;
6333 uint32 Player::GetZoneIdFromDB(uint64 guid)
6335 uint32 guidLow = GUID_LOPART(guid);
6336 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6337 if (!result)
6338 return 0;
6339 Field* fields = result->Fetch();
6340 uint32 zone = fields[0].GetUInt32();
6341 delete result;
6343 if (!zone)
6345 // stored zone is zero, use generic and slow zone detection
6346 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6347 if( !result )
6348 return 0;
6349 fields = result->Fetch();
6350 uint32 map = fields[0].GetUInt32();
6351 float posx = fields[1].GetFloat();
6352 float posy = fields[2].GetFloat();
6353 float posz = fields[3].GetFloat();
6354 delete result;
6356 zone = sMapMgr.GetZoneId(map,posx,posy,posz);
6358 if (zone > 0)
6359 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6362 return zone;
6365 uint32 Player::GetLevelFromDB(uint64 guid)
6367 QueryResult *result = CharacterDatabase.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid) );
6368 if (!result)
6369 return 0;
6371 Field* fields = result->Fetch();
6372 uint32 level = fields[0].GetUInt32();
6373 delete result;
6375 return level;
6378 void Player::UpdateArea(uint32 newArea)
6380 // FFA_PVP flags are area and not zone id dependent
6381 // so apply them accordingly
6382 m_areaUpdateId = newArea;
6384 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6386 if(area && (area->flags & AREA_FLAG_ARENA))
6388 if(!isGameMaster())
6389 SetFFAPvP(true);
6391 else
6393 // remove ffa flag only if not ffapvp realm
6394 // removal in sanctuaries and capitals is handled in zone update
6395 if(IsFFAPvP() && !sWorld.IsFFAPvPRealm())
6396 SetFFAPvP(false);
6399 UpdateAreaDependentAuras(newArea);
6402 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6404 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6405 if(!zone)
6406 return;
6408 if(m_zoneUpdateId != newZone)
6410 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6412 if (sWorld.getConfig(CONFIG_BOOL_WEATHER))
6414 if(Weather *wth = sWorld.FindWeather(zone->ID))
6415 wth->SendWeatherUpdateToPlayer(this);
6416 else if(!sWorld.AddWeather(zone->ID))
6418 // send fine weather packet to remove old zone's weather
6419 Weather::SendFineWeatherUpdateToPlayer(this);
6424 m_zoneUpdateId = newZone;
6425 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6427 // zone changed, so area changed as well, update it
6428 UpdateArea(newArea);
6430 // in PvP, any not controlled zone (except zone->team == 6, default case)
6431 // in PvE, only opposition team capital
6432 switch(zone->team)
6434 case AREATEAM_ALLY:
6435 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6436 break;
6437 case AREATEAM_HORDE:
6438 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6439 break;
6440 case AREATEAM_NONE:
6441 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6442 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6443 break;
6444 default: // 6 in fact
6445 pvpInfo.inHostileArea = false;
6446 break;
6449 if(pvpInfo.inHostileArea) // in hostile area
6451 if(!IsPvP() || pvpInfo.endTimer != 0)
6452 UpdatePvP(true, true);
6454 else // in friendly area
6456 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6457 pvpInfo.endTimer = time(0); // start toggle-off
6460 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6462 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6463 if(sWorld.IsFFAPvPRealm())
6464 SetFFAPvP(false);
6466 else
6468 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6471 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6473 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6474 SetRestType(REST_TYPE_IN_CITY);
6475 InnEnter(time(0),GetMapId(),0,0,0);
6477 if(sWorld.IsFFAPvPRealm())
6478 SetFFAPvP(false);
6480 else // anywhere else
6482 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6484 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6486 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6488 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6489 SetRestType(REST_TYPE_NO);
6491 if(sWorld.IsFFAPvPRealm())
6492 SetFFAPvP(true);
6495 else // not in tavern (leave city then)
6497 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6498 SetRestType(REST_TYPE_NO);
6500 // Set player to FFA PVP when not in rested environment.
6501 if(sWorld.IsFFAPvPRealm())
6502 SetFFAPvP(true);
6507 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6508 // if player resurrected at teleport this will be applied in resurrect code
6509 if(isAlive())
6510 DestroyZoneLimitedItem( true, newZone );
6512 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6513 AutoUnequipOffhandIfNeed();
6515 // recent client version not send leave/join channel packets for built-in local channels
6516 UpdateLocalChannels( newZone );
6518 // group update
6519 if(GetGroup())
6520 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6522 UpdateZoneDependentAuras(newZone);
6525 //If players are too far way of duel flag... then player loose the duel
6526 void Player::CheckDuelDistance(time_t currTime)
6528 if(!duel)
6529 return;
6531 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6532 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6533 if(!obj)
6534 return;
6536 if(duel->outOfBound == 0)
6538 if(!IsWithinDistInMap(obj, 50))
6540 duel->outOfBound = currTime;
6542 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6543 GetSession()->SendPacket(&data);
6546 else
6548 if(IsWithinDistInMap(obj, 40))
6550 duel->outOfBound = 0;
6552 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6553 GetSession()->SendPacket(&data);
6555 else if(currTime >= (duel->outOfBound+10))
6557 DuelComplete(DUEL_FLED);
6562 void Player::DuelComplete(DuelCompleteType type)
6564 // duel not requested
6565 if(!duel)
6566 return;
6568 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6569 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6570 GetSession()->SendPacket(&data);
6571 duel->opponent->GetSession()->SendPacket(&data);
6573 if(type != DUEL_INTERUPTED)
6575 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6576 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6577 data << duel->opponent->GetName();
6578 data << GetName();
6579 SendMessageToSet(&data,true);
6582 if (type == DUEL_WON)
6584 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6585 if (duel->opponent)
6586 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6589 //Remove Duel Flag object
6590 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6591 if(obj)
6592 duel->initiator->RemoveGameObject(obj,true);
6594 /* remove auras */
6595 std::vector<uint32> auras2remove;
6596 AuraMap const& vAuras = duel->opponent->GetAuras();
6597 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6599 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6600 auras2remove.push_back(i->second->GetId());
6603 for(size_t i=0; i<auras2remove.size(); ++i)
6604 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6606 auras2remove.clear();
6607 AuraMap const& auras = GetAuras();
6608 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6610 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6611 auras2remove.push_back(i->second->GetId());
6613 for(size_t i=0; i<auras2remove.size(); ++i)
6614 RemoveAurasDueToSpell(auras2remove[i]);
6616 // cleanup combo points
6617 if(GetComboTarget()==duel->opponent->GetGUID())
6618 ClearComboPoints();
6619 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6620 ClearComboPoints();
6622 if(duel->opponent->GetComboTarget()==GetGUID())
6623 duel->opponent->ClearComboPoints();
6624 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6625 duel->opponent->ClearComboPoints();
6627 //cleanups
6628 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6629 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6630 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6631 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6633 delete duel->opponent->duel;
6634 duel->opponent->duel = NULL;
6635 delete duel;
6636 duel = NULL;
6639 //---------------------------------------------------------//
6641 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6643 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6644 return;
6646 // not apply/remove mods for broken item
6647 if(item->IsBroken())
6648 return;
6650 ItemPrototype const *proto = item->GetProto();
6652 if(!proto)
6653 return;
6655 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6657 uint32 attacktype = Player::GetAttackBySlot(slot);
6658 if(attacktype < MAX_ATTACK)
6659 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6661 _ApplyItemBonuses(proto,slot,apply);
6663 if( slot==EQUIPMENT_SLOT_RANGED )
6664 _ApplyAmmoBonuses();
6666 ApplyItemEquipSpell(item,apply);
6667 ApplyEnchantment(item, apply);
6669 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6670 CorrectMetaGemEnchants(slot, apply);
6672 sLog.outDebug("_ApplyItemMods complete.");
6675 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
6677 if (slot >= INVENTORY_SLOT_BAG_END || !proto)
6678 return;
6680 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
6681 if (only_level_scale && !ssd)
6682 return;
6684 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6685 uint32 ssd_level = getLevel();
6686 if (ssd && ssd_level > ssd->MaxLevel)
6687 ssd_level = ssd->MaxLevel;
6689 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
6690 if (only_level_scale && !ssv)
6691 return;
6693 for (uint32 i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6695 uint32 statType = 0;
6696 int32 val = 0;
6697 // If set ScalingStatDistribution need get stats and values from it
6698 if (ssd && ssv)
6700 if (ssd->StatMod[i] < 0)
6701 continue;
6702 statType = ssd->StatMod[i];
6703 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6705 else
6707 if (i >= proto->StatsCount)
6708 continue;
6709 statType = proto->ItemStat[i].ItemStatType;
6710 val = proto->ItemStat[i].ItemStatValue;
6713 if(val == 0)
6714 continue;
6716 switch (statType)
6718 case ITEM_MOD_MANA:
6719 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6720 break;
6721 case ITEM_MOD_HEALTH: // modify HP
6722 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6723 break;
6724 case ITEM_MOD_AGILITY: // modify agility
6725 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6726 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6727 break;
6728 case ITEM_MOD_STRENGTH: //modify strength
6729 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6730 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6731 break;
6732 case ITEM_MOD_INTELLECT: //modify intellect
6733 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6734 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6735 break;
6736 case ITEM_MOD_SPIRIT: //modify spirit
6737 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6738 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6739 break;
6740 case ITEM_MOD_STAMINA: //modify stamina
6741 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6742 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6743 break;
6744 case ITEM_MOD_DEFENSE_SKILL_RATING:
6745 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6746 break;
6747 case ITEM_MOD_DODGE_RATING:
6748 ApplyRatingMod(CR_DODGE, int32(val), apply);
6749 break;
6750 case ITEM_MOD_PARRY_RATING:
6751 ApplyRatingMod(CR_PARRY, int32(val), apply);
6752 break;
6753 case ITEM_MOD_BLOCK_RATING:
6754 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6755 break;
6756 case ITEM_MOD_HIT_MELEE_RATING:
6757 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6758 break;
6759 case ITEM_MOD_HIT_RANGED_RATING:
6760 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6761 break;
6762 case ITEM_MOD_HIT_SPELL_RATING:
6763 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6764 break;
6765 case ITEM_MOD_CRIT_MELEE_RATING:
6766 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6767 break;
6768 case ITEM_MOD_CRIT_RANGED_RATING:
6769 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6770 break;
6771 case ITEM_MOD_CRIT_SPELL_RATING:
6772 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6773 break;
6774 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6775 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6776 break;
6777 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6778 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6779 break;
6780 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6781 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6782 break;
6783 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6784 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6785 break;
6786 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6787 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6788 break;
6789 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6790 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6791 break;
6792 case ITEM_MOD_HASTE_MELEE_RATING:
6793 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6794 break;
6795 case ITEM_MOD_HASTE_RANGED_RATING:
6796 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6797 break;
6798 case ITEM_MOD_HASTE_SPELL_RATING:
6799 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6800 break;
6801 case ITEM_MOD_HIT_RATING:
6802 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6803 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6804 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6805 break;
6806 case ITEM_MOD_CRIT_RATING:
6807 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6808 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6809 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6810 break;
6811 case ITEM_MOD_HIT_TAKEN_RATING:
6812 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6813 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6814 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6815 break;
6816 case ITEM_MOD_CRIT_TAKEN_RATING:
6817 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6818 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6819 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6820 break;
6821 case ITEM_MOD_RESILIENCE_RATING:
6822 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6823 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6824 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6825 break;
6826 case ITEM_MOD_HASTE_RATING:
6827 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6828 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6829 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6830 break;
6831 case ITEM_MOD_EXPERTISE_RATING:
6832 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6833 break;
6834 case ITEM_MOD_ATTACK_POWER:
6835 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6836 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6837 break;
6838 case ITEM_MOD_RANGED_ATTACK_POWER:
6839 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6840 break;
6841 case ITEM_MOD_MANA_REGENERATION:
6842 ApplyManaRegenBonus(int32(val), apply);
6843 break;
6844 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6845 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6846 break;
6847 case ITEM_MOD_SPELL_POWER:
6848 ApplySpellPowerBonus(int32(val), apply);
6849 break;
6850 // depricated item mods
6851 case ITEM_MOD_FERAL_ATTACK_POWER:
6852 case ITEM_MOD_SPELL_HEALING_DONE:
6853 case ITEM_MOD_SPELL_DAMAGE_DONE:
6854 break;
6858 // Apply Spell Power from ScalingStatValue if set
6859 if(ssv)
6861 if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
6862 ApplySpellPowerBonus(spellbonus, apply);
6865 // If set ScalingStatValue armor get it or use item armor
6866 uint32 armor = proto->Armor;
6867 if (ssv)
6869 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6870 armor = ssvarmor;
6872 // Add armor bonus from ArmorDamageModifier if > 0
6873 if (proto->ArmorDamageModifier > 0)
6874 armor += uint32(proto->ArmorDamageModifier);
6876 if (armor)
6877 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6879 if (proto->Block)
6880 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6882 if (proto->HolyRes)
6883 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6885 if (proto->FireRes)
6886 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6888 if (proto->NatureRes)
6889 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6891 if (proto->FrostRes)
6892 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6894 if (proto->ShadowRes)
6895 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6897 if (proto->ArcaneRes)
6898 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6900 WeaponAttackType attType = BASE_ATTACK;
6901 float damage = 0.0f;
6903 if( slot == EQUIPMENT_SLOT_RANGED && (
6904 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6905 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6907 attType = RANGED_ATTACK;
6909 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6911 attType = OFF_ATTACK;
6914 float minDamage = proto->Damage[0].DamageMin;
6915 float maxDamage = proto->Damage[0].DamageMax;
6916 int32 extraDPS = 0;
6917 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6918 if (ssv)
6920 if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue)))
6922 float average = extraDPS * proto->Delay / 1000.0f;
6923 minDamage = 0.7f * average;
6924 maxDamage = 1.3f * average;
6927 if (minDamage > 0 )
6929 damage = apply ? minDamage : BASE_MINDAMAGE;
6930 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6931 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6934 if (maxDamage > 0 )
6936 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6937 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6940 // Apply feral bonus from ScalingStatValue if set
6941 if (ssv)
6943 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6944 ApplyFeralAPBonus(feral_bonus, apply);
6946 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6947 if(getClass() == CLASS_DRUID)
6949 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6950 if (feral_bonus > 0)
6951 ApplyFeralAPBonus(feral_bonus, apply);
6954 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6955 return;
6957 if (proto->Delay)
6959 if(slot == EQUIPMENT_SLOT_RANGED)
6960 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6961 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6962 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6963 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6964 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6967 if(CanModifyStats() && (damage || proto->Delay))
6968 UpdateDamagePhysical(attType);
6971 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6973 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6974 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6975 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6977 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6978 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6979 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6981 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6982 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6983 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6986 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6988 // generic not weapon specific case processes in aura code
6989 if(aura->GetSpellProto()->EquippedItemClass == -1)
6990 return;
6992 BaseModGroup mod = BASEMOD_END;
6993 switch(attackType)
6995 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6996 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6997 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6998 default: return;
7001 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
7003 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
7007 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
7009 // ignore spell mods for not wands
7010 Modifier const* modifier = aura->GetModifier();
7011 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
7012 return;
7014 // generic not weapon specific case processes in aura code
7015 if(aura->GetSpellProto()->EquippedItemClass == -1)
7016 return;
7018 UnitMods unitMod = UNIT_MOD_END;
7019 switch(attackType)
7021 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
7022 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
7023 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
7024 default: return;
7027 UnitModifierType unitModType = TOTAL_VALUE;
7028 switch(modifier->m_auraname)
7030 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
7031 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
7032 default: return;
7035 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
7037 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
7041 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
7043 if(!item)
7044 return;
7046 ItemPrototype const *proto = item->GetProto();
7047 if(!proto)
7048 return;
7050 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7052 _Spell const& spellData = proto->Spells[i];
7054 // no spell
7055 if(!spellData.SpellId )
7056 continue;
7058 // wrong triggering type
7059 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
7060 continue;
7062 // check if it is valid spell
7063 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
7064 if(!spellproto)
7065 continue;
7067 ApplyEquipSpell(spellproto,item,apply,form_change);
7071 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
7073 if(apply)
7075 // Cannot be used in this stance/form
7076 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
7077 return;
7079 if(form_change) // check aura active state from other form
7081 bool found = false;
7082 for (int k=0; k < MAX_EFFECT_INDEX; ++k)
7084 spellEffectPair spair = spellEffectPair(spellInfo->Id, SpellEffectIndex(k));
7085 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
7087 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
7089 found = true;
7090 break;
7093 if(found)
7094 break;
7097 if(found) // and skip re-cast already active aura at form change
7098 return;
7101 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
7103 CastSpell(this,spellInfo,true,item);
7105 else
7107 if(form_change) // check aura compatibility
7109 // Cannot be used in this stance/form
7110 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
7111 return; // and remove only not compatible at form change
7114 if(item)
7115 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
7116 else
7117 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
7121 void Player::UpdateEquipSpellsAtFormChange()
7123 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7125 if(m_items[i] && !m_items[i]->IsBroken())
7127 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
7128 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
7132 // item set bonuses not dependent from item broken state
7133 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
7135 ItemSetEffect* eff = ItemSetEff[setindex];
7136 if(!eff)
7137 continue;
7139 for(uint32 y=0;y<8; ++y)
7141 SpellEntry const* spellInfo = eff->spells[y];
7142 if(!spellInfo)
7143 continue;
7145 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
7146 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
7151 void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
7153 Item *item = GetWeaponForAttack(attType, true, false);
7154 if(!item)
7155 return;
7157 ItemPrototype const *proto = item->GetProto();
7158 if(!proto)
7159 return;
7161 if (!Target || Target == this )
7162 return;
7164 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7166 _Spell const& spellData = proto->Spells[i];
7168 // no spell
7169 if(!spellData.SpellId )
7170 continue;
7172 // wrong triggering type
7173 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7174 continue;
7176 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7177 if(!spellInfo)
7179 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7180 continue;
7183 // not allow proc extra attack spell at extra attack
7184 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7185 return;
7187 float chance = (float)spellInfo->procChance;
7189 if(spellData.SpellPPMRate)
7191 uint32 WeaponSpeed = proto->Delay;
7192 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7194 else if(chance > 100.0f)
7196 chance = GetWeaponProcChance();
7199 if (roll_chance_f(chance))
7200 CastSpell(Target, spellInfo->Id, true, item);
7203 // item combat enchantments
7204 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7206 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7207 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7208 if(!pEnchant) continue;
7209 for (int s = 0; s < 3; ++s)
7211 if (pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7212 continue;
7214 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7215 if (!spellInfo)
7217 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7218 continue;
7221 // Use first rank to access spell item enchant procs
7222 float ppmRate = sSpellMgr.GetItemEnchantProcChance(spellInfo->Id);
7224 float chance = ppmRate
7225 ? GetPPMProcChance(proto->Delay, ppmRate)
7226 : pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7229 ApplySpellMod(spellInfo->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
7230 ApplySpellMod(spellInfo->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
7232 if (roll_chance_f(chance))
7234 if(IsPositiveSpell(pEnchant->spellid[s]))
7235 CastSpell(this, pEnchant->spellid[s], true, item);
7236 else
7237 CastSpell(Target, pEnchant->spellid[s], true, item);
7243 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7245 ItemPrototype const* proto = item->GetProto();
7246 // special learning case
7247 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7249 uint32 learn_spell_id = proto->Spells[0].SpellId;
7250 uint32 learning_spell_id = proto->Spells[1].SpellId;
7252 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7253 if (!spellInfo)
7255 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7256 SendEquipError(EQUIP_ERR_NONE, item);
7257 return;
7260 Spell *spell = new Spell(this, spellInfo, false);
7261 spell->m_CastItem = item;
7262 spell->m_cast_count = cast_count; //set count of casts
7263 spell->m_currentBasePoints[0] = learning_spell_id;
7264 spell->prepare(&targets);
7265 return;
7268 // use triggered flag only for items with many spell casts and for not first cast
7269 int count = 0;
7271 // item spells casted at use
7272 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7274 _Spell const& spellData = proto->Spells[i];
7276 // no spell
7277 if(!spellData.SpellId)
7278 continue;
7280 // wrong triggering type
7281 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7282 continue;
7284 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7285 if(!spellInfo)
7287 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7288 continue;
7291 Spell *spell = new Spell(this, spellInfo, (count > 0));
7292 spell->m_CastItem = item;
7293 spell->m_cast_count = cast_count; // set count of casts
7294 spell->m_glyphIndex = glyphIndex; // glyph index
7295 spell->prepare(&targets);
7297 ++count;
7300 // Item enchantments spells casted at use
7301 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7303 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7304 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7305 if(!pEnchant) continue;
7306 for (int s = 0; s < 3; ++s)
7308 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7309 continue;
7311 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7312 if (!spellInfo)
7314 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7315 continue;
7318 Spell *spell = new Spell(this, spellInfo, (count > 0));
7319 spell->m_CastItem = item;
7320 spell->m_cast_count = cast_count; // set count of casts
7321 spell->m_glyphIndex = glyphIndex; // glyph index
7322 spell->prepare(&targets);
7324 ++count;
7329 void Player::_RemoveAllItemMods()
7331 sLog.outDebug("_RemoveAllItemMods start.");
7333 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7335 if(m_items[i])
7337 ItemPrototype const *proto = m_items[i]->GetProto();
7338 if(!proto)
7339 continue;
7341 // item set bonuses not dependent from item broken state
7342 if(proto->ItemSet)
7343 RemoveItemsSetItem(this,proto);
7345 if(m_items[i]->IsBroken())
7346 continue;
7348 ApplyItemEquipSpell(m_items[i],false);
7349 ApplyEnchantment(m_items[i], false);
7353 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7355 if(m_items[i])
7357 if(m_items[i]->IsBroken())
7358 continue;
7359 ItemPrototype const *proto = m_items[i]->GetProto();
7360 if(!proto)
7361 continue;
7363 uint32 attacktype = Player::GetAttackBySlot(i);
7364 if(attacktype < MAX_ATTACK)
7365 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7367 _ApplyItemBonuses(proto,i, false);
7369 if( i == EQUIPMENT_SLOT_RANGED )
7370 _ApplyAmmoBonuses();
7374 sLog.outDebug("_RemoveAllItemMods complete.");
7377 void Player::_ApplyAllItemMods()
7379 sLog.outDebug("_ApplyAllItemMods start.");
7381 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7383 if(m_items[i])
7385 if(m_items[i]->IsBroken())
7386 continue;
7388 ItemPrototype const *proto = m_items[i]->GetProto();
7389 if(!proto)
7390 continue;
7392 uint32 attacktype = Player::GetAttackBySlot(i);
7393 if(attacktype < MAX_ATTACK)
7394 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7396 _ApplyItemBonuses(proto,i, true);
7398 if( i == EQUIPMENT_SLOT_RANGED )
7399 _ApplyAmmoBonuses();
7403 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7405 if(m_items[i])
7407 ItemPrototype const *proto = m_items[i]->GetProto();
7408 if(!proto)
7409 continue;
7411 // item set bonuses not dependent from item broken state
7412 if(proto->ItemSet)
7413 AddItemsSetItem(this,m_items[i]);
7415 if(m_items[i]->IsBroken())
7416 continue;
7418 ApplyItemEquipSpell(m_items[i],true);
7419 ApplyEnchantment(m_items[i], true);
7423 sLog.outDebug("_ApplyAllItemMods complete.");
7426 void Player::_ApplyAllLevelScaleItemMods(bool apply)
7428 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7430 if(m_items[i])
7432 if(m_items[i]->IsBroken())
7433 continue;
7435 ItemPrototype const *proto = m_items[i]->GetProto();
7436 if(!proto)
7437 continue;
7439 _ApplyItemBonuses(proto,i, apply, true);
7444 void Player::_ApplyAmmoBonuses()
7446 // check ammo
7447 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7448 if(!ammo_id)
7449 return;
7451 float currentAmmoDPS;
7453 ItemPrototype const *ammo_proto = ObjectMgr::GetItemPrototype( ammo_id );
7454 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7455 currentAmmoDPS = 0.0f;
7456 else
7457 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7459 if(currentAmmoDPS == GetAmmoDPS())
7460 return;
7462 m_ammoDPS = currentAmmoDPS;
7464 if(CanModifyStats())
7465 UpdateDamagePhysical(RANGED_ATTACK);
7468 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7470 if(!ammo_proto)
7471 return false;
7473 // check ranged weapon
7474 Item *weapon = GetWeaponForAttack( RANGED_ATTACK, true, false );
7475 if (!weapon)
7476 return false;
7478 ItemPrototype const* weapon_proto = weapon->GetProto();
7479 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7480 return false;
7482 // check ammo ws. weapon compatibility
7483 switch(weapon_proto->SubClass)
7485 case ITEM_SUBCLASS_WEAPON_BOW:
7486 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7487 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7488 return false;
7489 break;
7490 case ITEM_SUBCLASS_WEAPON_GUN:
7491 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7492 return false;
7493 break;
7494 default:
7495 return false;
7498 return true;
7501 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7502 Called by remove insignia spell effect */
7503 void Player::RemovedInsignia(Player* looterPlr)
7505 if (!GetBattleGroundId())
7506 return;
7508 // If not released spirit, do it !
7509 if(m_deathTimer > 0)
7511 m_deathTimer = 0;
7512 BuildPlayerRepop();
7513 RepopAtGraveyard();
7516 Corpse *corpse = GetCorpse();
7517 if (!corpse)
7518 return;
7520 // We have to convert player corpse to bones, not to be able to resurrect there
7521 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7522 Corpse *bones = sObjectAccessor.ConvertCorpseForPlayer(GetGUID(),true);
7523 if (!bones)
7524 return;
7526 // Now we must make bones lootable, and send player loot
7527 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7529 // We store the level of our player in the gold field
7530 // We retrieve this information at Player::SendLoot()
7531 bones->loot.gold = getLevel();
7532 bones->lootRecipient = looterPlr;
7533 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7536 void Player::SendLootRelease( uint64 guid )
7538 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7539 data << uint64(guid) << uint8(1);
7540 SendDirectMessage( &data );
7543 void Player::SendLoot(uint64 guid, LootType loot_type)
7545 if (uint64 lguid = GetLootGUID())
7546 m_session->DoLootRelease(lguid);
7548 Loot *loot = 0;
7549 PermissionTypes permission = ALL_PERMISSION;
7551 sLog.outDebug("Player::SendLoot");
7552 if (IS_GAMEOBJECT_GUID(guid))
7554 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7555 GameObject *go = GetMap()->GetGameObject(guid);
7557 // not check distance for GO in case owned GO (fishing bobber case, for example)
7558 // And permit out of range GO with no owner in case fishing hole
7559 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7561 SendLootRelease(guid);
7562 return;
7565 loot = &go->loot;
7567 if (go->getLootState() == GO_READY)
7569 uint32 lootid = go->GetGOInfo()->GetLootId();
7570 if ((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S))
7571 if (BattleGround *bg = GetBattleGround())
7572 if (bg->GetTypeID() == BATTLEGROUND_AV)
7573 if (!(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(go->GetEntry(), GetTeam())))
7575 SendLootRelease(guid);
7576 return;
7579 if (lootid)
7581 sLog.outDebug(" if(lootid)");
7582 loot->clear();
7583 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7586 if (loot_type == LOOT_FISHING)
7587 go->getFishLoot(loot,this);
7589 go->SetLootState(GO_ACTIVATED);
7592 else if (IS_ITEM_GUID(guid))
7594 Item *item = GetItemByGuid( guid );
7596 if (!item)
7598 SendLootRelease(guid);
7599 return;
7602 loot = &item->loot;
7604 if (!item->m_lootGenerated)
7606 item->m_lootGenerated = true;
7607 loot->clear();
7609 switch(loot_type)
7611 case LOOT_DISENCHANTING:
7612 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7613 break;
7614 case LOOT_PROSPECTING:
7615 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7616 break;
7617 case LOOT_MILLING:
7618 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7619 break;
7620 default:
7621 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7622 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7623 break;
7627 else if (IS_CORPSE_GUID(guid)) // remove insignia
7629 Corpse *bones = GetMap()->GetCorpse(guid);
7631 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7633 SendLootRelease(guid);
7634 return;
7637 loot = &bones->loot;
7639 if (!bones->lootForBody)
7641 bones->lootForBody = true;
7642 uint32 pLevel = bones->loot.gold;
7643 bones->loot.clear();
7644 if (GetBattleGround()->GetTypeID() == BATTLEGROUND_AV)
7645 loot->FillLoot(0, LootTemplates_Creature, this, false);
7646 // It may need a better formula
7647 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7648 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY) );
7651 if (bones->lootRecipient != this)
7652 permission = NONE_PERMISSION;
7654 else
7656 Creature *creature = GetMap()->GetCreature(guid);
7658 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7659 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7661 SendLootRelease(guid);
7662 return;
7665 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7667 SendLootRelease(guid);
7668 return;
7671 loot = &creature->loot;
7673 if (loot_type == LOOT_PICKPOCKETING)
7675 if (!creature->lootForPickPocketed)
7677 creature->lootForPickPocketed = true;
7678 loot->clear();
7680 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7681 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7683 // Generate extra money for pick pocket loot
7684 const uint32 a = urand(0, creature->getLevel()/2);
7685 const uint32 b = urand(0, getLevel()/2);
7686 loot->gold = uint32(10 * (a + b) * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY));
7689 else
7691 // the player whose group may loot the corpse
7692 Player *recipient = creature->GetLootRecipient();
7693 if (!recipient)
7695 creature->SetLootRecipient(this);
7696 recipient = this;
7699 if (creature->lootForPickPocketed)
7701 creature->lootForPickPocketed = false;
7702 loot->clear();
7705 if (!creature->lootForBody)
7707 creature->lootForBody = true;
7708 loot->clear();
7710 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7711 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7713 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7715 if (Group* group = recipient->GetGroup())
7717 group->UpdateLooterGuid(creature,true);
7719 switch (group->GetLootMethod())
7721 case GROUP_LOOT:
7722 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7723 group->GroupLoot(recipient->GetGUID(), loot, creature);
7724 break;
7725 case NEED_BEFORE_GREED:
7726 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7727 break;
7728 case MASTER_LOOT:
7729 group->MasterLoot(recipient->GetGUID(), loot, creature);
7730 break;
7731 default:
7732 break;
7737 // possible only if creature->lootForBody && loot->empty() at spell cast check
7738 if (loot_type == LOOT_SKINNING)
7740 loot->clear();
7741 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7743 // set group rights only for loot_type != LOOT_SKINNING
7744 else
7746 if(Group* group = GetGroup())
7748 if (group == recipient->GetGroup())
7750 if (group->GetLootMethod() == FREE_FOR_ALL)
7751 permission = ALL_PERMISSION;
7752 else if (group->GetLooterGuid() == GetGUID())
7754 if (group->GetLootMethod() == MASTER_LOOT)
7755 permission = MASTER_PERMISSION;
7756 else
7757 permission = ALL_PERMISSION;
7759 else
7760 permission = GROUP_PERMISSION;
7762 else
7763 permission = NONE_PERMISSION;
7765 else if (recipient == this)
7766 permission = ALL_PERMISSION;
7767 else
7768 permission = NONE_PERMISSION;
7773 SetLootGUID(guid);
7775 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7776 switch(loot_type)
7778 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7779 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7780 default: break;
7783 // need know merged fishing/corpse loot type for achievements
7784 loot->loot_type = loot_type;
7786 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7788 data << uint64(guid);
7789 data << uint8(loot_type);
7790 data << LootView(*loot, this, permission);
7792 SendDirectMessage(&data);
7794 // add 'this' player as one of the players that are looting 'loot'
7795 if (permission != NONE_PERMISSION)
7796 loot->AddLooter(GetGUID());
7798 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7799 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7802 void Player::SendNotifyLootMoneyRemoved()
7804 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7805 GetSession()->SendPacket( &data );
7808 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7810 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7811 data << uint8(lootSlot);
7812 GetSession()->SendPacket( &data );
7815 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7817 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7818 data << Field;
7819 data << Value;
7820 GetSession()->SendPacket(&data);
7823 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7825 // data depends on zoneid/mapid...
7826 BattleGround* bg = GetBattleGround();
7827 uint16 NumberOfFields = 0;
7828 uint32 mapid = GetMapId();
7830 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7832 // may be exist better way to do this...
7833 switch(zoneid)
7835 case 0:
7836 case 1:
7837 case 4:
7838 case 8:
7839 case 10:
7840 case 11:
7841 case 12:
7842 case 36:
7843 case 38:
7844 case 40:
7845 case 41:
7846 case 51:
7847 case 267:
7848 case 1519:
7849 case 1537:
7850 case 2257:
7851 case 2918:
7852 NumberOfFields = 8;
7853 break;
7854 case 139:
7855 NumberOfFields = 41;
7856 break;
7857 case 1377:
7858 NumberOfFields = 15;
7859 break;
7860 case 2597:
7861 NumberOfFields = 83;
7862 break;
7863 case 3277:
7864 NumberOfFields = 16;
7865 break;
7866 case 3358:
7867 case 3820:
7868 NumberOfFields = 40;
7869 break;
7870 case 3483:
7871 NumberOfFields = 27;
7872 break;
7873 case 3518:
7874 NumberOfFields = 39;
7875 break;
7876 case 3519:
7877 NumberOfFields = 38;
7878 break;
7879 case 3521:
7880 NumberOfFields = 37;
7881 break;
7882 case 3698:
7883 case 3702:
7884 case 3968:
7885 NumberOfFields = 11;
7886 break;
7887 case 3703:
7888 NumberOfFields = 11;
7889 break;
7890 default:
7891 NumberOfFields = 12;
7892 break;
7895 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7896 data << uint32(mapid); // mapid
7897 data << uint32(zoneid); // zone id
7898 data << uint32(areaid); // area id, new 2.1.0
7899 data << uint16(NumberOfFields); // count of uint64 blocks
7900 data << uint32(0x8d8) << uint32(0x0); // 1
7901 data << uint32(0x8d7) << uint32(0x0); // 2
7902 data << uint32(0x8d6) << uint32(0x0); // 3
7903 data << uint32(0x8d5) << uint32(0x0); // 4
7904 data << uint32(0x8d4) << uint32(0x0); // 5
7905 data << uint32(0x8d3) << uint32(0x0); // 6
7906 // 7 1 - Arena season in progress, 0 - end of season
7907 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_BOOL_ARENA_SEASON_IN_PROGRESS));
7908 // 8 Arena season id
7909 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID));
7910 if(mapid == 530) // Outland
7912 data << uint32(0x9bf) << uint32(0x0); // 7
7913 data << uint32(0x9bd) << uint32(0xF); // 8
7914 data << uint32(0x9bb) << uint32(0xF); // 9
7916 switch(zoneid)
7918 case 1:
7919 case 11:
7920 case 12:
7921 case 38:
7922 case 40:
7923 case 51:
7924 case 1519:
7925 case 1537:
7926 case 2257:
7927 break;
7928 case 2597: // AV
7929 if (bg && bg->GetTypeID() == BATTLEGROUND_AV)
7930 bg->FillInitialWorldStates(data);
7931 else
7933 data << uint32(0x7ae) << uint32(0x1); // 7 snowfall n
7934 data << uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
7935 data << uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
7936 data << uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
7937 data << uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
7938 data << uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
7939 data << uint32(0x567) << uint32(0x1); // 13 frostwolfe c
7940 data << uint32(0x566) << uint32(0x1); // 14 frostwolfw c
7941 data << uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
7942 data << uint32(0x544) << uint32(0x0); // 16 ice grave a_a
7943 data << uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
7944 data << uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
7945 data << uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
7946 data << uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
7947 data << uint32(0x574) << uint32(0x0); // 21 1396 unk
7948 data << uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
7949 data << uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
7950 data << uint32(0x56f) << uint32(0x0); // 24 1391 unk
7951 data << uint32(0x56e) << uint32(0x0); // 25 iceblood a
7952 data << uint32(0x56d) << uint32(0x0); // 26 towerp a
7953 data << uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
7954 data << uint32(0x56b) << uint32(0x0); // 28 froswolfw a
7955 data << uint32(0x56a) << uint32(0x1); // 29 1386 unk
7956 data << uint32(0x569) << uint32(0x1); // 30 iceblood c
7957 data << uint32(0x568) << uint32(0x1); // 31 towerp c
7958 data << uint32(0x565) << uint32(0x0); // 32 stoneh tower a
7959 data << uint32(0x564) << uint32(0x0); // 33 icewing tower a
7960 data << uint32(0x563) << uint32(0x0); // 34 dunn a
7961 data << uint32(0x562) << uint32(0x0); // 35 duns a
7962 data << uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
7963 data << uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
7964 data << uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
7965 data << uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
7966 data << uint32(0x55d) << uint32(0x0); // 40 stone tower d
7967 data << uint32(0x3c6) << uint32(0x0); // 41 966 unk
7968 data << uint32(0x3c4) << uint32(0x0); // 42 964 unk
7969 data << uint32(0x3c2) << uint32(0x0); // 43 962 unk
7970 data << uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
7971 data << uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
7972 data << uint32(0x3b6) << uint32(0x0); // 46 950 unk
7973 data << uint32(0x55c) << uint32(0x0); // 47 icewing tower d
7974 data << uint32(0x55b) << uint32(0x0); // 48 dunn d
7975 data << uint32(0x55a) << uint32(0x0); // 49 duns d
7976 data << uint32(0x559) << uint32(0x0); // 50 1369 unk
7977 data << uint32(0x558) << uint32(0x0); // 51 iceblood d
7978 data << uint32(0x557) << uint32(0x0); // 52 towerp d
7979 data << uint32(0x556) << uint32(0x0); // 53 frostwolfe d
7980 data << uint32(0x555) << uint32(0x0); // 54 frostwolfw d
7981 data << uint32(0x554) << uint32(0x1); // 55 stoneh tower c
7982 data << uint32(0x553) << uint32(0x1); // 56 icewing tower c
7983 data << uint32(0x552) << uint32(0x1); // 57 dunn c
7984 data << uint32(0x551) << uint32(0x1); // 58 duns c
7985 data << uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
7986 data << uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
7987 data << uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
7988 data << uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
7989 data << uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
7990 data << uint32(0x545) << uint32(0x0); // 64 iceblood h_a
7991 data << uint32(0x543) << uint32(0x1); // 65 iceblod h_c
7992 data << uint32(0x542) << uint32(0x0); // 66 iceblood a_c
7993 data << uint32(0x540) << uint32(0x0); // 67 snowfall h_a
7994 data << uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
7995 data << uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
7996 data << uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
7997 data << uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
7998 data << uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
7999 data << uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
8000 data << uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
8001 data << uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
8002 data << uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
8003 data << uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
8004 data << uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
8005 data << uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
8006 data << uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
8007 data << uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
8009 break;
8010 case 3277: // WS
8011 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
8012 bg->FillInitialWorldStates(data);
8013 else
8015 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
8016 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
8017 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
8018 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
8019 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
8020 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
8021 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8022 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8024 break;
8025 case 3358: // AB
8026 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
8027 bg->FillInitialWorldStates(data);
8028 else
8030 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
8031 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
8032 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
8033 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
8034 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
8035 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
8036 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
8037 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
8038 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
8039 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
8040 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
8041 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
8042 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
8043 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
8044 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
8045 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
8046 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
8047 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
8048 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
8049 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
8050 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
8051 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
8052 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
8053 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
8054 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
8055 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
8056 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
8057 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
8058 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
8059 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
8060 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
8061 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
8063 break;
8064 case 3820: // EY
8065 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
8066 bg->FillInitialWorldStates(data);
8067 else
8069 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
8070 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
8071 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
8072 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
8073 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
8074 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
8075 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
8076 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
8077 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
8078 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
8079 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
8080 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
8081 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
8082 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
8083 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
8084 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
8085 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
8086 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
8087 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
8088 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
8089 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
8090 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
8091 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
8092 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
8093 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
8094 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
8095 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
8096 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
8097 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
8098 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
8099 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
8100 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
8101 // and some more ... unknown
8103 break;
8104 case 3483: // Hellfire Peninsula
8105 data << uint32(0x9ba) << uint32(0x1); // 10
8106 data << uint32(0x9b9) << uint32(0x1); // 11
8107 data << uint32(0x9b5) << uint32(0x0); // 12
8108 data << uint32(0x9b4) << uint32(0x1); // 13
8109 data << uint32(0x9b3) << uint32(0x0); // 14
8110 data << uint32(0x9b2) << uint32(0x0); // 15
8111 data << uint32(0x9b1) << uint32(0x1); // 16
8112 data << uint32(0x9b0) << uint32(0x0); // 17
8113 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
8114 data << uint32(0x9ac) << uint32(0x0); // 19
8115 data << uint32(0x9a8) << uint32(0x0); // 20
8116 data << uint32(0x9a7) << uint32(0x0); // 21
8117 data << uint32(0x9a6) << uint32(0x1); // 22
8118 break;
8119 case 3519: // Terokkar Forest
8120 data << uint32(0xa41) << uint32(0x0); // 10
8121 data << uint32(0xa40) << uint32(0x14); // 11
8122 data << uint32(0xa3f) << uint32(0x0); // 12
8123 data << uint32(0xa3e) << uint32(0x0); // 13
8124 data << uint32(0xa3d) << uint32(0x5); // 14
8125 data << uint32(0xa3c) << uint32(0x0); // 15
8126 data << uint32(0xa87) << uint32(0x0); // 16
8127 data << uint32(0xa86) << uint32(0x0); // 17
8128 data << uint32(0xa85) << uint32(0x0); // 18
8129 data << uint32(0xa84) << uint32(0x0); // 19
8130 data << uint32(0xa83) << uint32(0x0); // 20
8131 data << uint32(0xa82) << uint32(0x0); // 21
8132 data << uint32(0xa81) << uint32(0x0); // 22
8133 data << uint32(0xa80) << uint32(0x0); // 23
8134 data << uint32(0xa7e) << uint32(0x0); // 24
8135 data << uint32(0xa7d) << uint32(0x0); // 25
8136 data << uint32(0xa7c) << uint32(0x0); // 26
8137 data << uint32(0xa7b) << uint32(0x0); // 27
8138 data << uint32(0xa7a) << uint32(0x0); // 28
8139 data << uint32(0xa79) << uint32(0x0); // 29
8140 data << uint32(0x9d0) << uint32(0x5); // 30
8141 data << uint32(0x9ce) << uint32(0x0); // 31
8142 data << uint32(0x9cd) << uint32(0x0); // 32
8143 data << uint32(0x9cc) << uint32(0x0); // 33
8144 data << uint32(0xa88) << uint32(0x0); // 34
8145 data << uint32(0xad0) << uint32(0x0); // 35
8146 data << uint32(0xacf) << uint32(0x1); // 36
8147 break;
8148 case 3521: // Zangarmarsh
8149 data << uint32(0x9e1) << uint32(0x0); // 10
8150 data << uint32(0x9e0) << uint32(0x0); // 11
8151 data << uint32(0x9df) << uint32(0x0); // 12
8152 data << uint32(0xa5d) << uint32(0x1); // 13
8153 data << uint32(0xa5c) << uint32(0x0); // 14
8154 data << uint32(0xa5b) << uint32(0x1); // 15
8155 data << uint32(0xa5a) << uint32(0x0); // 16
8156 data << uint32(0xa59) << uint32(0x1); // 17
8157 data << uint32(0xa58) << uint32(0x0); // 18
8158 data << uint32(0xa57) << uint32(0x0); // 19
8159 data << uint32(0xa56) << uint32(0x0); // 20
8160 data << uint32(0xa55) << uint32(0x1); // 21
8161 data << uint32(0xa54) << uint32(0x0); // 22
8162 data << uint32(0x9e7) << uint32(0x0); // 23
8163 data << uint32(0x9e6) << uint32(0x0); // 24
8164 data << uint32(0x9e5) << uint32(0x0); // 25
8165 data << uint32(0xa00) << uint32(0x0); // 26
8166 data << uint32(0x9ff) << uint32(0x1); // 27
8167 data << uint32(0x9fe) << uint32(0x0); // 28
8168 data << uint32(0x9fd) << uint32(0x0); // 29
8169 data << uint32(0x9fc) << uint32(0x1); // 30
8170 data << uint32(0x9fb) << uint32(0x0); // 31
8171 data << uint32(0xa62) << uint32(0x0); // 32
8172 data << uint32(0xa61) << uint32(0x1); // 33
8173 data << uint32(0xa60) << uint32(0x1); // 34
8174 data << uint32(0xa5f) << uint32(0x0); // 35
8175 break;
8176 case 3698: // Nagrand Arena
8177 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
8178 bg->FillInitialWorldStates(data);
8179 else
8181 data << uint32(0xa0f) << uint32(0x0); // 7
8182 data << uint32(0xa10) << uint32(0x0); // 8
8183 data << uint32(0xa11) << uint32(0x0); // 9 show
8185 break;
8186 case 3702: // Blade's Edge Arena
8187 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8188 bg->FillInitialWorldStates(data);
8189 else
8191 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8192 data << uint32(0x9f1) << uint32(0x0); // 8 green
8193 data << uint32(0x9f3) << uint32(0x0); // 9 show
8195 break;
8196 case 3968: // Ruins of Lordaeron
8197 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8198 bg->FillInitialWorldStates(data);
8199 else
8201 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8202 data << uint32(0xbb9) << uint32(0x0); // 8 green
8203 data << uint32(0xbba) << uint32(0x0); // 9 show
8205 break;
8206 case 3703: // Shattrath City
8207 break;
8208 default:
8209 data << uint32(0x914) << uint32(0x0); // 7
8210 data << uint32(0x913) << uint32(0x0); // 8
8211 data << uint32(0x912) << uint32(0x0); // 9
8212 data << uint32(0x915) << uint32(0x0); // 10
8213 break;
8215 GetSession()->SendPacket(&data);
8218 uint32 Player::GetXPRestBonus(uint32 xp)
8220 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8222 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8223 rested_bonus = xp;
8225 SetRestBonus( GetRestBonus() - rested_bonus);
8227 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8228 return rested_bonus;
8231 void Player::SetBindPoint(uint64 guid)
8233 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8234 data << uint64(guid);
8235 GetSession()->SendPacket( &data );
8238 void Player::SendTalentWipeConfirm(uint64 guid)
8240 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8241 data << uint64(guid);
8242 data << uint32(resetTalentsCost());
8243 GetSession()->SendPacket( &data );
8246 void Player::SendPetSkillWipeConfirm()
8248 Pet* pet = GetPet();
8249 if(!pet)
8250 return;
8251 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8252 data << pet->GetGUID();
8253 data << uint32(pet->resetTalentsCost());
8254 GetSession()->SendPacket( &data );
8257 /*********************************************************/
8258 /*** STORAGE SYSTEM ***/
8259 /*********************************************************/
8261 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8263 assert(i < 3);
8264 if(i < 2 && item)
8266 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8267 return;
8268 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8269 if(charges == 0)
8270 return;
8271 if(charges > 1)
8272 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8273 else if(charges <= 1)
8275 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8276 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8281 void Player::SetSheath( SheathState sheathed )
8283 switch (sheathed)
8285 case SHEATH_STATE_UNARMED: // no prepared weapon
8286 SetVirtualItemSlot(0,NULL);
8287 SetVirtualItemSlot(1,NULL);
8288 SetVirtualItemSlot(2,NULL);
8289 break;
8290 case SHEATH_STATE_MELEE: // prepared melee weapon
8292 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true,true));
8293 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true,true));
8294 SetVirtualItemSlot(2,NULL);
8295 }; break;
8296 case SHEATH_STATE_RANGED: // prepared ranged weapon
8297 SetVirtualItemSlot(0,NULL);
8298 SetVirtualItemSlot(1,NULL);
8299 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true,true));
8300 break;
8301 default:
8302 SetVirtualItemSlot(0,NULL);
8303 SetVirtualItemSlot(1,NULL);
8304 SetVirtualItemSlot(2,NULL);
8305 break;
8307 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
8310 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8312 uint8 pClass = getClass();
8314 uint8 slots[4];
8315 slots[0] = NULL_SLOT;
8316 slots[1] = NULL_SLOT;
8317 slots[2] = NULL_SLOT;
8318 slots[3] = NULL_SLOT;
8319 switch( proto->InventoryType )
8321 case INVTYPE_HEAD:
8322 slots[0] = EQUIPMENT_SLOT_HEAD;
8323 break;
8324 case INVTYPE_NECK:
8325 slots[0] = EQUIPMENT_SLOT_NECK;
8326 break;
8327 case INVTYPE_SHOULDERS:
8328 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8329 break;
8330 case INVTYPE_BODY:
8331 slots[0] = EQUIPMENT_SLOT_BODY;
8332 break;
8333 case INVTYPE_CHEST:
8334 slots[0] = EQUIPMENT_SLOT_CHEST;
8335 break;
8336 case INVTYPE_ROBE:
8337 slots[0] = EQUIPMENT_SLOT_CHEST;
8338 break;
8339 case INVTYPE_WAIST:
8340 slots[0] = EQUIPMENT_SLOT_WAIST;
8341 break;
8342 case INVTYPE_LEGS:
8343 slots[0] = EQUIPMENT_SLOT_LEGS;
8344 break;
8345 case INVTYPE_FEET:
8346 slots[0] = EQUIPMENT_SLOT_FEET;
8347 break;
8348 case INVTYPE_WRISTS:
8349 slots[0] = EQUIPMENT_SLOT_WRISTS;
8350 break;
8351 case INVTYPE_HANDS:
8352 slots[0] = EQUIPMENT_SLOT_HANDS;
8353 break;
8354 case INVTYPE_FINGER:
8355 slots[0] = EQUIPMENT_SLOT_FINGER1;
8356 slots[1] = EQUIPMENT_SLOT_FINGER2;
8357 break;
8358 case INVTYPE_TRINKET:
8359 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8360 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8361 break;
8362 case INVTYPE_CLOAK:
8363 slots[0] = EQUIPMENT_SLOT_BACK;
8364 break;
8365 case INVTYPE_WEAPON:
8367 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8369 // suggest offhand slot only if know dual wielding
8370 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8371 if(CanDualWield())
8372 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8373 break;
8375 case INVTYPE_SHIELD:
8376 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8377 break;
8378 case INVTYPE_RANGED:
8379 slots[0] = EQUIPMENT_SLOT_RANGED;
8380 break;
8381 case INVTYPE_2HWEAPON:
8382 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8383 if (CanDualWield() && CanTitanGrip())
8384 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8385 break;
8386 case INVTYPE_TABARD:
8387 slots[0] = EQUIPMENT_SLOT_TABARD;
8388 break;
8389 case INVTYPE_WEAPONMAINHAND:
8390 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8391 break;
8392 case INVTYPE_WEAPONOFFHAND:
8393 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8394 break;
8395 case INVTYPE_HOLDABLE:
8396 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8397 break;
8398 case INVTYPE_THROWN:
8399 slots[0] = EQUIPMENT_SLOT_RANGED;
8400 break;
8401 case INVTYPE_RANGEDRIGHT:
8402 slots[0] = EQUIPMENT_SLOT_RANGED;
8403 break;
8404 case INVTYPE_BAG:
8405 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8406 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8407 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8408 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8409 break;
8410 case INVTYPE_RELIC:
8412 switch(proto->SubClass)
8414 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8415 if (pClass == CLASS_PALADIN)
8416 slots[0] = EQUIPMENT_SLOT_RANGED;
8417 break;
8418 case ITEM_SUBCLASS_ARMOR_IDOL:
8419 if (pClass == CLASS_DRUID)
8420 slots[0] = EQUIPMENT_SLOT_RANGED;
8421 break;
8422 case ITEM_SUBCLASS_ARMOR_TOTEM:
8423 if (pClass == CLASS_SHAMAN)
8424 slots[0] = EQUIPMENT_SLOT_RANGED;
8425 break;
8426 case ITEM_SUBCLASS_ARMOR_MISC:
8427 if (pClass == CLASS_WARLOCK)
8428 slots[0] = EQUIPMENT_SLOT_RANGED;
8429 break;
8430 case ITEM_SUBCLASS_ARMOR_SIGIL:
8431 if (pClass == CLASS_DEATH_KNIGHT)
8432 slots[0] = EQUIPMENT_SLOT_RANGED;
8433 break;
8435 break;
8437 default :
8438 return NULL_SLOT;
8441 if( slot != NULL_SLOT )
8443 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8445 for (int i = 0; i < 4; ++i)
8447 if ( slots[i] == slot )
8448 return slot;
8452 else
8454 // search free slot at first
8455 for (int i = 0; i < 4; ++i)
8457 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8459 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8460 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8461 return slots[i];
8465 // if not found free and can swap return first appropriate from used
8466 for (int i = 0; i < 4; ++i)
8468 if ( slots[i] != NULL_SLOT && swap )
8469 return slots[i];
8473 // no free position
8474 return NULL_SLOT;
8477 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8479 Item *pItem;
8480 uint32 tempcount = 0;
8482 uint8 res = EQUIP_ERR_OK;
8484 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8486 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8487 if( pItem && pItem->GetEntry() == item )
8489 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8490 if(ires==EQUIP_ERR_OK)
8492 tempcount += pItem->GetCount();
8493 if( tempcount >= count )
8494 return EQUIP_ERR_OK;
8496 else
8497 res = ires;
8500 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8502 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8503 if( pItem && pItem->GetEntry() == item )
8505 tempcount += pItem->GetCount();
8506 if( tempcount >= count )
8507 return EQUIP_ERR_OK;
8510 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8512 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8513 if( pItem && pItem->GetEntry() == item )
8515 tempcount += pItem->GetCount();
8516 if( tempcount >= count )
8517 return EQUIP_ERR_OK;
8520 Bag *pBag;
8521 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8523 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8524 if( pBag )
8526 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8528 pItem = GetItemByPos( i, j );
8529 if( pItem && pItem->GetEntry() == item )
8531 tempcount += pItem->GetCount();
8532 if( tempcount >= count )
8533 return EQUIP_ERR_OK;
8539 // not found req. item count and have unequippable items
8540 return res;
8543 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8545 uint32 count = 0;
8546 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8548 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8549 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8550 count += pItem->GetCount();
8552 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8554 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8555 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8556 count += pItem->GetCount();
8558 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8560 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8561 if( pBag )
8562 count += pBag->GetItemCount(item,skipItem);
8565 if(skipItem && skipItem->GetProto()->GemProperties)
8567 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8569 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8570 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8571 count += pItem->GetGemCountWithID(item);
8575 if(inBankAlso)
8577 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8579 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8580 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8581 count += pItem->GetCount();
8583 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8585 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8586 if( pBag )
8587 count += pBag->GetItemCount(item,skipItem);
8590 if(skipItem && skipItem->GetProto()->GemProperties)
8592 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8594 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8595 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8596 count += pItem->GetGemCountWithID(item);
8601 return count;
8604 uint32 Player::GetItemCountWithLimitCategory( uint32 limitCategory ) const
8606 uint32 count = 0;
8607 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8608 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8609 if (pItem->GetProto()->ItemLimitCategory == limitCategory)
8610 count += pItem->GetCount();
8612 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8613 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8614 if (pItem->GetProto()->ItemLimitCategory == limitCategory)
8615 count += pItem->GetCount();
8617 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8618 if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8619 count += pBag->GetItemCountWithLimitCategory(limitCategory);
8621 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8622 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8623 if (pItem->GetProto()->ItemLimitCategory == limitCategory)
8624 count += pItem->GetCount();
8626 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8627 if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8628 count += pBag->GetItemCountWithLimitCategory(limitCategory);
8630 return count;
8633 Item* Player::GetItemByEntry( uint32 item ) const
8635 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8636 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8637 if (pItem->GetEntry() == item)
8638 return pItem;
8640 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8641 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8642 if (pItem->GetEntry() == item)
8643 return pItem;
8645 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8646 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
8647 if (Item* itemPtr = pBag->GetItemByEntry(item))
8648 return itemPtr;
8650 return NULL;
8653 Item* Player::GetItemByLimitedCategory(uint32 limitedCategory) const
8655 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8656 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8657 if (pItem->GetProto()->ItemLimitCategory == limitedCategory)
8658 return pItem;
8660 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8661 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8662 if (pItem->GetProto()->ItemLimitCategory == limitedCategory)
8663 return pItem;
8665 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8666 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
8667 if (Item* itemPtr = pBag->GetItemByLimitedCategory(limitedCategory))
8668 return itemPtr;
8670 return NULL;
8673 Item* Player::GetItemByGuid( uint64 guid ) const
8675 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8677 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8678 if( pItem && pItem->GetGUID() == guid )
8679 return pItem;
8681 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8683 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8684 if( pItem && pItem->GetGUID() == guid )
8685 return pItem;
8688 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8690 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8691 if( pBag )
8693 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8695 Item* pItem = pBag->GetItemByPos( j );
8696 if( pItem && pItem->GetGUID() == guid )
8697 return pItem;
8701 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8703 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8704 if( pBag )
8706 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8708 Item* pItem = pBag->GetItemByPos( j );
8709 if( pItem && pItem->GetGUID() == guid )
8710 return pItem;
8715 return NULL;
8718 Item* Player::GetItemByPos( uint16 pos ) const
8720 uint8 bag = pos >> 8;
8721 uint8 slot = pos & 255;
8722 return GetItemByPos( bag, slot );
8725 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8727 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END )) )
8728 return m_items[slot];
8729 else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8730 || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END) )
8732 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8733 if ( pBag )
8734 return pBag->GetItemByPos(slot);
8736 return NULL;
8739 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool nonbroken, bool useable) const
8741 uint8 slot;
8742 switch (attackType)
8744 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8745 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8746 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8747 default: return NULL;
8750 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8751 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8752 return NULL;
8754 if (useable && !IsUseEquipedWeapon(attackType==BASE_ATTACK))
8755 return NULL;
8757 if (nonbroken && item->IsBroken())
8758 return NULL;
8760 return item;
8763 Item* Player::GetShield(bool useable) const
8765 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8766 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8767 return NULL;
8769 if(!useable)
8770 return item;
8772 if( item->IsBroken())
8773 return NULL;
8775 return item;
8778 uint32 Player::GetAttackBySlot( uint8 slot )
8780 switch(slot)
8782 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8783 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8784 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8785 default: return MAX_ATTACK;
8789 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8791 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8792 return true;
8793 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8794 return true;
8795 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8796 return true;
8797 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8798 return true;
8799 return false;
8802 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8804 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8805 return true;
8806 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8807 return true;
8808 return false;
8811 bool Player::IsBankPos( uint8 bag, uint8 slot )
8813 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8814 return true;
8815 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8816 return true;
8817 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8818 return true;
8819 return false;
8822 bool Player::IsBagPos( uint16 pos )
8824 uint8 bag = pos >> 8;
8825 uint8 slot = pos & 255;
8826 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8827 return true;
8828 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8829 return true;
8830 return false;
8833 bool Player::IsValidPos( uint8 bag, uint8 slot, bool explicit_pos ) const
8835 // post selected
8836 if(bag == NULL_BAG && !explicit_pos)
8837 return true;
8839 if (bag == INVENTORY_SLOT_BAG_0)
8841 // any post selected
8842 if (slot == NULL_SLOT && !explicit_pos)
8843 return true;
8845 // equipment
8846 if (slot < EQUIPMENT_SLOT_END)
8847 return true;
8849 // bag equip slots
8850 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8851 return true;
8853 // backpack slots
8854 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8855 return true;
8857 // keyring slots
8858 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8859 return true;
8861 // bank main slots
8862 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8863 return true;
8865 // bank bag slots
8866 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8867 return true;
8869 return false;
8872 // bag content slots
8873 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8875 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8876 if(!pBag)
8877 return false;
8879 // any post selected
8880 if (slot == NULL_SLOT && !explicit_pos)
8881 return true;
8883 return slot < pBag->GetBagSize();
8886 // bank bag content slots
8887 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8889 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8890 if(!pBag)
8891 return false;
8893 // any post selected
8894 if (slot == NULL_SLOT && !explicit_pos)
8895 return true;
8897 return slot < pBag->GetBagSize();
8900 // where this?
8901 return false;
8905 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8907 uint32 tempcount = 0;
8908 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8910 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8911 if( pItem && pItem->GetEntry() == item )
8913 tempcount += pItem->GetCount();
8914 if( tempcount >= count )
8915 return true;
8918 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8920 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8921 if( pItem && pItem->GetEntry() == item )
8923 tempcount += pItem->GetCount();
8924 if( tempcount >= count )
8925 return true;
8928 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8930 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8932 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8934 Item* pItem = GetItemByPos( i, j );
8935 if( pItem && pItem->GetEntry() == item )
8937 tempcount += pItem->GetCount();
8938 if( tempcount >= count )
8939 return true;
8945 if(inBankAlso)
8947 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8949 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8950 if( pItem && pItem->GetEntry() == item )
8952 tempcount += pItem->GetCount();
8953 if( tempcount >= count )
8954 return true;
8957 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8959 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8961 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8963 Item* pItem = GetItemByPos( i, j );
8964 if( pItem && pItem->GetEntry() == item )
8966 tempcount += pItem->GetCount();
8967 if( tempcount >= count )
8968 return true;
8975 return false;
8978 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8980 uint32 tempcount = 0;
8981 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8983 if(i==int(except_slot))
8984 continue;
8986 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8987 if( pItem && pItem->GetEntry() == item)
8989 tempcount += pItem->GetCount();
8990 if( tempcount >= count )
8991 return true;
8995 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item);
8996 if (pProto && pProto->GemProperties)
8998 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
9000 if(i==int(except_slot))
9001 continue;
9003 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9004 if( pItem && pItem->GetProto()->Socket[0].Color)
9006 tempcount += pItem->GetGemCountWithID(item);
9007 if( tempcount >= count )
9008 return true;
9013 return false;
9016 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
9018 uint32 tempcount = 0;
9019 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
9021 if(i==int(except_slot))
9022 continue;
9024 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9025 if (!pItem)
9026 continue;
9028 ItemPrototype const *pProto = pItem->GetProto();
9029 if (!pProto)
9030 continue;
9032 if (pProto->ItemLimitCategory == limitCategory)
9034 tempcount += pItem->GetCount();
9035 if( tempcount >= count )
9036 return true;
9039 if( pProto->Socket[0].Color)
9041 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
9042 if( tempcount >= count )
9043 return true;
9047 return false;
9050 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
9052 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
9053 if( !pProto )
9055 if(no_space_count)
9056 *no_space_count = count;
9057 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9060 // no maximum
9061 if(pProto->MaxCount > 0)
9063 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
9065 if (curcount + count > uint32(pProto->MaxCount))
9067 if(no_space_count)
9068 *no_space_count = count +curcount - pProto->MaxCount;
9069 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9073 // check unique-equipped limit
9074 if (pProto->ItemLimitCategory)
9076 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(pProto->ItemLimitCategory);
9077 if (!limitEntry)
9079 if(no_space_count)
9080 *no_space_count = count;
9081 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9084 if (limitEntry->mode == ITEM_LIMIT_CATEGORY_MODE_HAVE)
9086 uint32 curcount = GetItemCountWithLimitCategory(pProto->ItemLimitCategory);
9088 if (curcount + count > uint32(limitEntry->maxCount))
9090 if(no_space_count)
9091 *no_space_count = count + curcount - limitEntry->maxCount;
9092 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS;
9097 return EQUIP_ERR_OK;
9100 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
9102 Item *pItem;
9103 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9105 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9106 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
9107 return true;
9109 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9111 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9112 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
9113 return true;
9115 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9117 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9119 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9121 pItem = GetItemByPos( i, j );
9122 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
9123 return true;
9127 return false;
9130 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
9132 Item* pItem2 = GetItemByPos( bag, slot );
9134 // ignore move item (this slot will be empty at move)
9135 if (pItem2==pSrcItem)
9136 pItem2 = NULL;
9138 uint32 need_space;
9140 // empty specific slot - check item fit to slot
9141 if (!pItem2 || swap)
9143 if (bag == INVENTORY_SLOT_BAG_0)
9145 // keyring case
9146 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
9147 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9149 // currencytoken case
9150 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
9151 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9153 // prevent cheating
9154 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
9155 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9157 else
9159 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9160 if (!pBag)
9161 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9163 ItemPrototype const* pBagProto = pBag->GetProto();
9164 if (!pBagProto)
9165 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9167 if (slot >= pBagProto->ContainerSlots)
9168 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9170 if (!ItemCanGoIntoBag(pProto,pBagProto))
9171 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9174 // non empty stack with space
9175 need_space = pProto->GetMaxStackSize();
9177 // non empty slot, check item type
9178 else
9180 // can be merged at least partly
9181 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9182 if (res != EQUIP_ERR_OK)
9183 return res;
9185 // free stack space or infinity
9186 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9189 if (need_space > count)
9190 need_space = count;
9192 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
9193 if (!newPosition.isContainedIn(dest))
9195 dest.push_back(newPosition);
9196 count -= need_space;
9198 return EQUIP_ERR_OK;
9201 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
9203 // skip specific bag already processed in first called _CanStoreItem_InBag
9204 if (bag==skip_bag)
9205 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9207 // skip not existed bag or self targeted bag
9208 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9209 if (!pBag || pBag==pSrcItem)
9210 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9212 ItemPrototype const* pBagProto = pBag->GetProto();
9213 if (!pBagProto)
9214 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9216 // specialized bag mode or non-specilized
9217 if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
9218 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9220 if (!ItemCanGoIntoBag(pProto,pBagProto))
9221 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9223 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9225 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9226 if (j==skip_slot)
9227 continue;
9229 Item* pItem2 = GetItemByPos( bag, j );
9231 // ignore move item (this slot will be empty at move)
9232 if (pItem2 == pSrcItem)
9233 pItem2 = NULL;
9235 // if merge skip empty, if !merge skip non-empty
9236 if ((pItem2 != NULL) != merge)
9237 continue;
9239 uint32 need_space = pProto->GetMaxStackSize();
9241 if (pItem2)
9243 // can be merged at least partly
9244 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9245 if (res != EQUIP_ERR_OK)
9246 continue;
9248 // descrease at current stacksize
9249 need_space -= pItem2->GetCount();
9252 if (need_space > count)
9253 need_space = count;
9255 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9256 if (!newPosition.isContainedIn(dest))
9258 dest.push_back(newPosition);
9259 count -= need_space;
9261 if (count==0)
9262 return EQUIP_ERR_OK;
9265 return EQUIP_ERR_OK;
9268 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
9270 for(uint32 j = slot_begin; j < slot_end; ++j)
9272 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9273 if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
9274 continue;
9276 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
9278 // ignore move item (this slot will be empty at move)
9279 if (pItem2==pSrcItem)
9280 pItem2 = NULL;
9282 // if merge skip empty, if !merge skip non-empty
9283 if ((pItem2 != NULL) != merge)
9284 continue;
9286 uint32 need_space = pProto->GetMaxStackSize();
9288 if (pItem2)
9290 // can be merged at least partly
9291 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9292 if (res != EQUIP_ERR_OK)
9293 continue;
9295 // descrease at current stacksize
9296 need_space -= pItem2->GetCount();
9299 if (need_space > count)
9300 need_space = count;
9302 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9303 if (!newPosition.isContainedIn(dest))
9305 dest.push_back(newPosition);
9306 count -= need_space;
9308 if (count==0)
9309 return EQUIP_ERR_OK;
9312 return EQUIP_ERR_OK;
9315 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9317 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9319 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
9320 if (!pProto)
9322 if (no_space_count)
9323 *no_space_count = count;
9324 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9327 if (pItem)
9329 // item used
9330 if(pItem->m_lootGenerated)
9332 if (no_space_count)
9333 *no_space_count = count;
9334 return EQUIP_ERR_ALREADY_LOOTED;
9337 if (pItem->IsBindedNotWith(this))
9339 if (no_space_count)
9340 *no_space_count = count;
9341 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9345 // check count of items (skip for auto move for same player from bank)
9346 uint32 no_similar_count = 0; // can't store this amount similar items
9347 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9348 if (res!=EQUIP_ERR_OK)
9350 if (count==no_similar_count)
9352 if (no_space_count)
9353 *no_space_count = no_similar_count;
9354 return res;
9356 count -= no_similar_count;
9359 // in specific slot
9360 if (bag != NULL_BAG && slot != NULL_SLOT)
9362 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9363 if (res!=EQUIP_ERR_OK)
9365 if (no_space_count)
9366 *no_space_count = count + no_similar_count;
9367 return res;
9370 if (count==0)
9372 if (no_similar_count==0)
9373 return EQUIP_ERR_OK;
9375 if (no_space_count)
9376 *no_space_count = count + no_similar_count;
9377 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9381 // not specific slot or have space for partly store only in specific slot
9383 // in specific bag
9384 if (bag != NULL_BAG)
9386 // search stack in bag for merge to
9387 if (pProto->Stackable != 1)
9389 if (bag == INVENTORY_SLOT_BAG_0) // inventory
9391 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9392 if (res!=EQUIP_ERR_OK)
9394 if (no_space_count)
9395 *no_space_count = count + no_similar_count;
9396 return res;
9399 if (count==0)
9401 if (no_similar_count==0)
9402 return EQUIP_ERR_OK;
9404 if (no_space_count)
9405 *no_space_count = count + no_similar_count;
9406 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9409 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9410 if (res!=EQUIP_ERR_OK)
9412 if (no_space_count)
9413 *no_space_count = count + no_similar_count;
9414 return res;
9417 if (count==0)
9419 if (no_similar_count==0)
9420 return EQUIP_ERR_OK;
9422 if (no_space_count)
9423 *no_space_count = count + no_similar_count;
9424 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9427 else // equipped bag
9429 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9430 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9431 if (res!=EQUIP_ERR_OK)
9432 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9434 if (res!=EQUIP_ERR_OK)
9436 if (no_space_count)
9437 *no_space_count = count + no_similar_count;
9438 return res;
9441 if (count==0)
9443 if (no_similar_count==0)
9444 return EQUIP_ERR_OK;
9446 if (no_space_count)
9447 *no_space_count = count + no_similar_count;
9448 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9453 // search free slot in bag for place to
9454 if(bag == INVENTORY_SLOT_BAG_0) // inventory
9456 // search free slot - keyring case
9457 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9459 uint32 keyringSize = GetMaxKeyringSize();
9460 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9461 if (res!=EQUIP_ERR_OK)
9463 if (no_space_count)
9464 *no_space_count = count + no_similar_count;
9465 return res;
9468 if (count==0)
9470 if (no_similar_count==0)
9471 return EQUIP_ERR_OK;
9473 if (no_space_count)
9474 *no_space_count = count + no_similar_count;
9475 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9478 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9479 if (res!=EQUIP_ERR_OK)
9481 if (no_space_count)
9482 *no_space_count = count + no_similar_count;
9483 return res;
9486 if (count==0)
9488 if (no_similar_count==0)
9489 return EQUIP_ERR_OK;
9491 if (no_space_count)
9492 *no_space_count = count + no_similar_count;
9493 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9496 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9498 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9499 if (res!=EQUIP_ERR_OK)
9501 if (no_space_count)
9502 *no_space_count = count + no_similar_count;
9503 return res;
9506 if (count==0)
9508 if (no_similar_count==0)
9509 return EQUIP_ERR_OK;
9511 if (no_space_count)
9512 *no_space_count = count + no_similar_count;
9513 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9517 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9518 if (res!=EQUIP_ERR_OK)
9520 if (no_space_count)
9521 *no_space_count = count + no_similar_count;
9522 return res;
9525 if (count==0)
9527 if (no_similar_count==0)
9528 return EQUIP_ERR_OK;
9530 if (no_space_count)
9531 *no_space_count = count + no_similar_count;
9532 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9535 else // equipped bag
9537 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9538 if (res!=EQUIP_ERR_OK)
9539 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9541 if (res!=EQUIP_ERR_OK)
9543 if (no_space_count)
9544 *no_space_count = count + no_similar_count;
9545 return res;
9548 if (count==0)
9550 if (no_similar_count==0)
9551 return EQUIP_ERR_OK;
9553 if (no_space_count)
9554 *no_space_count = count + no_similar_count;
9555 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9560 // not specific bag or have space for partly store only in specific bag
9562 // search stack for merge to
9563 if (pProto->Stackable != 1)
9565 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9566 if (res!=EQUIP_ERR_OK)
9568 if (no_space_count)
9569 *no_space_count = count + no_similar_count;
9570 return res;
9573 if (count==0)
9575 if (no_similar_count==0)
9576 return EQUIP_ERR_OK;
9578 if (no_space_count)
9579 *no_space_count = count + no_similar_count;
9580 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9583 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9584 if (res!=EQUIP_ERR_OK)
9586 if (no_space_count)
9587 *no_space_count = count + no_similar_count;
9588 return res;
9591 if (count==0)
9593 if (no_similar_count==0)
9594 return EQUIP_ERR_OK;
9596 if (no_space_count)
9597 *no_space_count = count + no_similar_count;
9598 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9601 if (pProto->BagFamily)
9603 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9605 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9606 if (res!=EQUIP_ERR_OK)
9607 continue;
9609 if (count==0)
9611 if (no_similar_count==0)
9612 return EQUIP_ERR_OK;
9614 if (no_space_count)
9615 *no_space_count = count + no_similar_count;
9616 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9621 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9623 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9624 if (res!=EQUIP_ERR_OK)
9625 continue;
9627 if (count==0)
9629 if (no_similar_count==0)
9630 return EQUIP_ERR_OK;
9632 if (no_space_count)
9633 *no_space_count = count + no_similar_count;
9634 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9639 // search free slot - special bag case
9640 if (pProto->BagFamily)
9642 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9644 uint32 keyringSize = GetMaxKeyringSize();
9645 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9646 if (res!=EQUIP_ERR_OK)
9648 if (no_space_count)
9649 *no_space_count = count + no_similar_count;
9650 return res;
9653 if (count==0)
9655 if (no_similar_count==0)
9656 return EQUIP_ERR_OK;
9658 if (no_space_count)
9659 *no_space_count = count + no_similar_count;
9660 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9663 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9665 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9666 if (res!=EQUIP_ERR_OK)
9668 if (no_space_count)
9669 *no_space_count = count + no_similar_count;
9670 return res;
9673 if (count==0)
9675 if (no_similar_count==0)
9676 return EQUIP_ERR_OK;
9678 if (no_space_count)
9679 *no_space_count = count + no_similar_count;
9680 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9684 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9686 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9687 if (res!=EQUIP_ERR_OK)
9688 continue;
9690 if (count==0)
9692 if (no_similar_count==0)
9693 return EQUIP_ERR_OK;
9695 if (no_space_count)
9696 *no_space_count = count + no_similar_count;
9697 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9702 // search free slot
9703 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9704 if (res!=EQUIP_ERR_OK)
9706 if (no_space_count)
9707 *no_space_count = count + no_similar_count;
9708 return res;
9711 if (count==0)
9713 if (no_similar_count==0)
9714 return EQUIP_ERR_OK;
9716 if (no_space_count)
9717 *no_space_count = count + no_similar_count;
9718 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9721 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9723 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9724 if (res!=EQUIP_ERR_OK)
9725 continue;
9727 if (count==0)
9729 if (no_similar_count==0)
9730 return EQUIP_ERR_OK;
9732 if (no_space_count)
9733 *no_space_count = count + no_similar_count;
9734 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9738 if (no_space_count)
9739 *no_space_count = count + no_similar_count;
9741 return EQUIP_ERR_INVENTORY_FULL;
9744 //////////////////////////////////////////////////////////////////////////
9745 uint8 Player::CanStoreItems( Item **pItems,int count) const
9747 Item *pItem2;
9749 // fill space table
9750 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9751 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9752 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9753 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9755 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9756 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9757 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9758 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9760 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9762 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9764 if (pItem2 && !pItem2->IsInTrade())
9766 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9770 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9772 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9774 if (pItem2 && !pItem2->IsInTrade())
9776 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9780 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9782 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9784 if (pItem2 && !pItem2->IsInTrade())
9786 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9790 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9792 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9794 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9796 pItem2 = GetItemByPos( i, j );
9797 if (pItem2 && !pItem2->IsInTrade())
9799 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9805 // check free space for all items
9806 for (int k = 0; k < count; ++k)
9808 Item *pItem = pItems[k];
9810 // no item
9811 if (!pItem) continue;
9813 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9814 ItemPrototype const *pProto = pItem->GetProto();
9816 // strange item
9817 if( !pProto )
9818 return EQUIP_ERR_ITEM_NOT_FOUND;
9820 // item used
9821 if(pItem->m_lootGenerated)
9822 return EQUIP_ERR_ALREADY_LOOTED;
9824 // item it 'bind'
9825 if(pItem->IsBindedNotWith(this))
9826 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9828 Bag *pBag;
9829 ItemPrototype const *pBagProto;
9831 // item is 'one item only'
9832 uint8 res = CanTakeMoreSimilarItems(pItem);
9833 if(res != EQUIP_ERR_OK)
9834 return res;
9836 // search stack for merge to
9837 if( pProto->Stackable != 1 )
9839 bool b_found = false;
9841 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9843 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9844 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9846 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9847 b_found = true;
9848 break;
9851 if (b_found) continue;
9853 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9855 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9856 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9858 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9859 b_found = true;
9860 break;
9863 if (b_found) continue;
9865 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9867 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9868 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9870 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9871 b_found = true;
9872 break;
9875 if (b_found) continue;
9877 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9879 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9880 if( pBag )
9882 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9884 pItem2 = GetItemByPos( t, j );
9885 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9887 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9888 b_found = true;
9889 break;
9894 if (b_found) continue;
9897 // special bag case
9898 if( pProto->BagFamily )
9900 bool b_found = false;
9901 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9903 uint32 keyringSize = GetMaxKeyringSize();
9904 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9906 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9908 inv_keys[t-KEYRING_SLOT_START] = 1;
9909 b_found = true;
9910 break;
9915 if (b_found) continue;
9917 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9919 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9921 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9923 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9924 b_found = true;
9925 break;
9930 if (b_found) continue;
9932 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9934 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9935 if( pBag )
9937 pBagProto = pBag->GetProto();
9939 // not plain container check
9940 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9941 ItemCanGoIntoBag(pProto,pBagProto) )
9943 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9945 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9947 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9948 b_found = true;
9949 break;
9955 if (b_found) continue;
9958 // search free slot
9959 bool b_found = false;
9960 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9962 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9964 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9965 b_found = true;
9966 break;
9969 if (b_found) continue;
9971 // search free slot in bags
9972 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9974 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9975 if( pBag )
9977 pBagProto = pBag->GetProto();
9979 // special bag already checked
9980 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9981 continue;
9983 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9985 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9987 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9988 b_found = true;
9989 break;
9995 // no free slot found?
9996 if (!b_found)
9997 return EQUIP_ERR_INVENTORY_FULL;
10000 return EQUIP_ERR_OK;
10003 //////////////////////////////////////////////////////////////////////////
10004 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
10006 dest = 0;
10007 Item *pItem = Item::CreateItem( item, 1, this );
10008 if( pItem )
10010 uint8 result = CanEquipItem(slot, dest, pItem, swap );
10011 delete pItem;
10012 return result;
10015 return EQUIP_ERR_ITEM_NOT_FOUND;
10018 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
10020 dest = 0;
10021 if( pItem )
10023 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
10024 ItemPrototype const *pProto = pItem->GetProto();
10025 if( pProto )
10027 // item used
10028 if(pItem->m_lootGenerated)
10029 return EQUIP_ERR_ALREADY_LOOTED;
10031 if(pItem->IsBindedNotWith(this))
10032 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10034 // check count of items (skip for auto move for same player from bank)
10035 uint8 res = CanTakeMoreSimilarItems(pItem);
10036 if(res != EQUIP_ERR_OK)
10037 return res;
10039 // check this only in game
10040 if(not_loading)
10042 // May be here should be more stronger checks; STUNNED checked
10043 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
10044 if (hasUnitState(UNIT_STAT_STUNNED))
10045 return EQUIP_ERR_YOU_ARE_STUNNED;
10047 // do not allow equipping gear except weapons, offhands, projectiles, relics in
10048 // - combat
10049 // - in-progress arenas
10050 if( !pProto->CanChangeEquipStateInCombat() )
10052 if( isInCombat() )
10053 return EQUIP_ERR_NOT_IN_COMBAT;
10055 if(BattleGround* bg = GetBattleGround())
10056 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
10057 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
10060 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
10061 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
10063 if(IsNonMeleeSpellCasted(false))
10064 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
10067 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
10068 // 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)
10069 if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
10070 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10072 uint8 eslot = FindEquipSlot( pProto, slot, swap );
10073 if (eslot == NULL_SLOT)
10074 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10076 uint8 msg = CanUseItem(pItem , not_loading);
10077 if (msg != EQUIP_ERR_OK)
10078 return msg;
10079 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
10080 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
10082 // if swap ignore item (equipped also)
10083 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
10084 return res2;
10086 // check unique-equipped special item classes
10087 if (pProto->Class == ITEM_CLASS_QUIVER)
10089 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10091 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
10093 if (pBag != pItem)
10095 if (ItemPrototype const* pBagProto = pBag->GetProto())
10097 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
10098 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
10099 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
10100 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
10107 uint32 type = pProto->InventoryType;
10109 if (eslot == EQUIPMENT_SLOT_OFFHAND)
10111 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
10113 if (!CanDualWield())
10114 return EQUIP_ERR_CANT_DUAL_WIELD;
10116 else if (type == INVTYPE_2HWEAPON)
10118 if (!CanDualWield() || !CanTitanGrip())
10119 return EQUIP_ERR_CANT_DUAL_WIELD;
10122 if (IsTwoHandUsed())
10123 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
10126 // equip two-hand weapon case (with possible unequip 2 items)
10127 if (type == INVTYPE_2HWEAPON)
10129 if (eslot == EQUIPMENT_SLOT_OFFHAND)
10131 if (!CanTitanGrip())
10132 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10134 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
10135 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10137 if (!CanTitanGrip())
10139 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
10140 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
10141 ItemPosCountVec off_dest;
10142 if (offItem && (!not_loading ||
10143 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
10144 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
10145 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
10148 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
10149 return EQUIP_ERR_OK;
10153 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
10156 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
10158 // Applied only to equipped items and bank bags
10159 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
10160 return EQUIP_ERR_OK;
10162 Item* pItem = GetItemByPos(pos);
10164 // Applied only to existed equipped item
10165 if( !pItem )
10166 return EQUIP_ERR_OK;
10168 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
10170 ItemPrototype const *pProto = pItem->GetProto();
10171 if( !pProto )
10172 return EQUIP_ERR_ITEM_NOT_FOUND;
10174 // item used
10175 if(pItem->m_lootGenerated)
10176 return EQUIP_ERR_ALREADY_LOOTED;
10178 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10179 // - combat
10180 // - in-progress arenas
10181 if( !pProto->CanChangeEquipStateInCombat() )
10183 if( isInCombat() )
10184 return EQUIP_ERR_NOT_IN_COMBAT;
10186 if(BattleGround* bg = GetBattleGround())
10187 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
10188 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
10191 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
10192 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
10194 return EQUIP_ERR_OK;
10197 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
10199 if (!pItem)
10200 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10202 uint32 count = pItem->GetCount();
10204 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
10205 ItemPrototype const *pProto = pItem->GetProto();
10206 if (!pProto)
10207 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10209 // item used
10210 if(pItem->m_lootGenerated)
10211 return EQUIP_ERR_ALREADY_LOOTED;
10213 if (pItem->IsBindedNotWith(this))
10214 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10216 // check count of items (skip for auto move for same player from bank)
10217 uint8 res = CanTakeMoreSimilarItems(pItem);
10218 if (res != EQUIP_ERR_OK)
10219 return res;
10221 // in specific slot
10222 if (bag != NULL_BAG && slot != NULL_SLOT)
10224 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
10226 if (!pItem->IsBag())
10227 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
10229 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
10230 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
10232 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
10233 return cantuse;
10236 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
10237 if (res!=EQUIP_ERR_OK)
10238 return res;
10240 if (count==0)
10241 return EQUIP_ERR_OK;
10244 // not specific slot or have space for partly store only in specific slot
10246 // in specific bag
10247 if( bag != NULL_BAG )
10249 if( pProto->InventoryType == INVTYPE_BAG )
10251 Bag *pBag = (Bag*)pItem;
10252 if( pBag && !pBag->IsEmpty() )
10253 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
10256 // search stack in bag for merge to
10257 if( pProto->Stackable != 1 )
10259 if( bag == INVENTORY_SLOT_BAG_0 )
10261 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10262 if(res!=EQUIP_ERR_OK)
10263 return res;
10265 if(count==0)
10266 return EQUIP_ERR_OK;
10268 else
10270 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
10271 if(res!=EQUIP_ERR_OK)
10272 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
10274 if(res!=EQUIP_ERR_OK)
10275 return res;
10277 if(count==0)
10278 return EQUIP_ERR_OK;
10282 // search free slot in bag
10283 if( bag == INVENTORY_SLOT_BAG_0 )
10285 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10286 if(res!=EQUIP_ERR_OK)
10287 return res;
10289 if(count==0)
10290 return EQUIP_ERR_OK;
10292 else
10294 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
10295 if(res != EQUIP_ERR_OK)
10296 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
10298 if(res != EQUIP_ERR_OK)
10299 return res;
10301 if(count == 0)
10302 return EQUIP_ERR_OK;
10306 // not specific bag or have space for partly store only in specific bag
10308 // search stack for merge to
10309 if( pProto->Stackable != 1 )
10311 // in slots
10312 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10313 if(res != EQUIP_ERR_OK)
10314 return res;
10316 if(count == 0)
10317 return EQUIP_ERR_OK;
10319 // in special bags
10320 if( pProto->BagFamily )
10322 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10324 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10325 if(res!=EQUIP_ERR_OK)
10326 continue;
10328 if(count==0)
10329 return EQUIP_ERR_OK;
10333 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10335 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10336 if(res!=EQUIP_ERR_OK)
10337 continue;
10339 if(count==0)
10340 return EQUIP_ERR_OK;
10344 // search free place in special bag
10345 if( pProto->BagFamily )
10347 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10349 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10350 if(res!=EQUIP_ERR_OK)
10351 continue;
10353 if(count==0)
10354 return EQUIP_ERR_OK;
10358 // search free space
10359 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10360 if(res!=EQUIP_ERR_OK)
10361 return res;
10363 if(count==0)
10364 return EQUIP_ERR_OK;
10366 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10368 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10369 if(res!=EQUIP_ERR_OK)
10370 continue;
10372 if(count==0)
10373 return EQUIP_ERR_OK;
10375 return EQUIP_ERR_BANK_FULL;
10378 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10380 if (pItem)
10382 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10384 if (!isAlive() && not_loading)
10385 return EQUIP_ERR_YOU_ARE_DEAD;
10387 //if (isStunned())
10388 // return EQUIP_ERR_YOU_ARE_STUNNED;
10390 ItemPrototype const *pProto = pItem->GetProto();
10391 if (pProto)
10393 if (pItem->IsBindedNotWith(this))
10394 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10396 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
10397 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10399 if (uint32 item_use_skill = pItem->GetSkill())
10401 if (GetSkillValue(item_use_skill) == 0)
10403 // armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
10404 if (pProto->Class != ITEM_CLASS_ARMOR)
10405 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10407 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : NULL;
10408 if (!ssd)
10409 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10411 bool allowScaleSkill = false;
10412 for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i)
10414 SkillLineAbilityEntry const *skillInfo = sSkillLineAbilityStore.LookupEntry(i);
10415 if (!skillInfo)
10416 continue;
10418 if (skillInfo->skillId != item_use_skill)
10419 continue;
10421 // can't learn
10422 if (skillInfo->classmask && (skillInfo->classmask & getClassMask()) == 0)
10423 continue;
10425 if (skillInfo->racemask && (skillInfo->racemask & getRaceMask()) == 0)
10426 continue;
10428 allowScaleSkill = true;
10429 break;
10432 if (!allowScaleSkill)
10433 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10437 if (pProto->RequiredSkill != 0)
10439 if (GetSkillValue( pProto->RequiredSkill ) == 0)
10440 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10442 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
10443 return EQUIP_ERR_CANT_EQUIP_SKILL;
10446 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
10447 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10449 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
10450 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10452 if (getLevel() < pProto->RequiredLevel)
10453 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10455 return EQUIP_ERR_OK;
10458 return EQUIP_ERR_ITEM_NOT_FOUND;
10461 bool Player::CanUseItem( ItemPrototype const *pProto )
10463 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10465 if( pProto )
10467 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10468 return false;
10469 if( pProto->RequiredSkill != 0 )
10471 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10472 return false;
10473 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10474 return false;
10476 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10477 return false;
10478 if( getLevel() < pProto->RequiredLevel )
10479 return false;
10480 return true;
10482 return false;
10485 uint8 Player::CanUseAmmo( uint32 item ) const
10487 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10488 if( !isAlive() )
10489 return EQUIP_ERR_YOU_ARE_DEAD;
10490 //if( isStunned() )
10491 // return EQUIP_ERR_YOU_ARE_STUNNED;
10492 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
10493 if( pProto )
10495 if( pProto->InventoryType!= INVTYPE_AMMO )
10496 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10497 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10498 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10499 if( pProto->RequiredSkill != 0 )
10501 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10502 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10503 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10504 return EQUIP_ERR_CANT_EQUIP_SKILL;
10506 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10507 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10508 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10509 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10511 if( getLevel() < pProto->RequiredLevel )
10512 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10514 // Requires No Ammo
10515 if(GetDummyAura(46699))
10516 return EQUIP_ERR_BAG_FULL6;
10518 return EQUIP_ERR_OK;
10520 return EQUIP_ERR_ITEM_NOT_FOUND;
10523 void Player::SetAmmo( uint32 item )
10525 if(!item)
10526 return;
10528 // already set
10529 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10530 return;
10532 // check ammo
10533 if (item)
10535 uint8 msg = CanUseAmmo( item );
10536 if (msg != EQUIP_ERR_OK)
10538 SendEquipError(msg, NULL, NULL, item);
10539 return;
10543 SetUInt32Value(PLAYER_AMMO_ID, item);
10545 _ApplyAmmoBonuses();
10548 void Player::RemoveAmmo()
10550 SetUInt32Value(PLAYER_AMMO_ID, 0);
10552 m_ammoDPS = 0.0f;
10554 if (CanModifyStats())
10555 UpdateDamagePhysical(RANGED_ATTACK);
10558 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10559 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10561 uint32 count = 0;
10562 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10563 count += itr->count;
10565 Item *pItem = Item::CreateItem( item, count, this );
10566 if( pItem )
10568 ItemAddedQuestCheck( item, count );
10569 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, count);
10570 if(randomPropertyId)
10571 pItem->SetItemRandomProperties(randomPropertyId);
10572 pItem = StoreItem( dest, pItem, update );
10574 return pItem;
10577 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10579 if( !pItem )
10580 return NULL;
10582 Item* lastItem = pItem;
10583 uint32 entry = pItem->GetEntry();
10584 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10586 uint16 pos = itr->pos;
10587 uint32 count = itr->count;
10589 ++itr;
10591 if(itr == dest.end())
10593 lastItem = _StoreItem(pos,pItem,count,false,update);
10594 break;
10597 lastItem = _StoreItem(pos,pItem,count,true,update);
10599 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10600 return lastItem;
10603 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10604 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10606 if( !pItem )
10607 return NULL;
10609 uint8 bag = pos >> 8;
10610 uint8 slot = pos & 255;
10612 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10614 Item *pItem2 = GetItemByPos( bag, slot );
10616 if (!pItem2)
10618 if (clone)
10619 pItem = pItem->CloneItem(count, this);
10620 else
10621 pItem->SetCount(count);
10623 if (!pItem)
10624 return NULL;
10626 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10627 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10628 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10629 pItem->SetBinding( true );
10631 if (bag == INVENTORY_SLOT_BAG_0)
10633 m_items[slot] = pItem;
10634 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10635 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10636 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10638 pItem->SetSlot( slot );
10639 pItem->SetContainer( NULL );
10641 // need update known currency
10642 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10643 UpdateKnownCurrencies(pItem->GetEntry(), true);
10645 if (IsInWorld() && update)
10647 pItem->AddToWorld();
10648 pItem->SendCreateUpdateToPlayer( this );
10651 pItem->SetState(ITEM_CHANGED, this);
10653 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10655 pBag->StoreItem( slot, pItem, update );
10656 if( IsInWorld() && update )
10658 pItem->AddToWorld();
10659 pItem->SendCreateUpdateToPlayer( this );
10661 pItem->SetState(ITEM_CHANGED, this);
10662 pBag->SetState(ITEM_CHANGED, this);
10665 AddEnchantmentDurations(pItem);
10666 AddItemDurations(pItem);
10668 return pItem;
10670 else
10672 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10673 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10674 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10675 pItem2->SetBinding( true );
10677 pItem2->SetCount( pItem2->GetCount() + count );
10678 if (IsInWorld() && update)
10679 pItem2->SendCreateUpdateToPlayer( this );
10681 if (!clone)
10683 // delete item (it not in any slot currently)
10684 if (IsInWorld() && update)
10686 pItem->RemoveFromWorld();
10687 pItem->DestroyForPlayer( this );
10690 RemoveEnchantmentDurations(pItem);
10691 RemoveItemDurations(pItem);
10693 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10694 pItem->SetState(ITEM_REMOVED, this);
10697 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10698 AddEnchantmentDurations(pItem2);
10700 pItem2->SetState(ITEM_CHANGED, this);
10702 return pItem2;
10706 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10708 if (Item *pItem = Item::CreateItem( item, 1, this ))
10710 ItemAddedQuestCheck( item, 1 );
10711 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, 1);
10712 return EquipItem( pos, pItem, update );
10715 return NULL;
10718 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10720 AddEnchantmentDurations(pItem);
10721 AddItemDurations(pItem);
10723 uint8 bag = pos >> 8;
10724 uint8 slot = pos & 255;
10726 Item *pItem2 = GetItemByPos( bag, slot );
10728 if( !pItem2 )
10730 VisualizeItem( slot, pItem);
10732 if(isAlive())
10734 ItemPrototype const *pProto = pItem->GetProto();
10736 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10737 if(pProto && pProto->ItemSet)
10738 AddItemsSetItem(this, pItem);
10740 _ApplyItemMods(pItem, slot, true);
10742 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10744 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10746 if (getClass() == CLASS_ROGUE)
10747 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10749 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10751 if (!spellProto)
10752 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10753 else
10755 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10757 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10758 data << uint64(GetGUID());
10759 data << uint8(1);
10760 data << uint32(cooldownSpell);
10761 data << uint32(0);
10762 GetSession()->SendPacket(&data);
10767 if( IsInWorld() && update )
10769 pItem->AddToWorld();
10770 pItem->SendCreateUpdateToPlayer( this );
10773 ApplyEquipCooldown(pItem);
10775 if( slot == EQUIPMENT_SLOT_MAINHAND )
10777 UpdateExpertise(BASE_ATTACK);
10778 UpdateArmorPenetration();
10780 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10782 UpdateExpertise(OFF_ATTACK);
10783 UpdateArmorPenetration();
10786 else
10788 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10789 if( IsInWorld() && update )
10790 pItem2->SendCreateUpdateToPlayer( this );
10792 // delete item (it not in any slot currently)
10793 //pItem->DeleteFromDB();
10794 if( IsInWorld() && update )
10796 pItem->RemoveFromWorld();
10797 pItem->DestroyForPlayer( this );
10800 RemoveEnchantmentDurations(pItem);
10801 RemoveItemDurations(pItem);
10803 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10804 pItem->SetState(ITEM_REMOVED, this);
10805 pItem2->SetState(ITEM_CHANGED, this);
10807 ApplyEquipCooldown(pItem2);
10809 return pItem2;
10812 // only for full equip instead adding to stack
10813 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10814 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot+1);
10816 return pItem;
10819 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10821 if( pItem )
10823 AddEnchantmentDurations(pItem);
10824 AddItemDurations(pItem);
10826 uint8 slot = pos & 255;
10827 VisualizeItem( slot, pItem);
10829 if( IsInWorld() )
10831 pItem->AddToWorld();
10832 pItem->SendCreateUpdateToPlayer( this );
10835 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10836 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot+1);
10840 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10842 if(pItem)
10844 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10845 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10846 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10848 else
10850 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10851 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10855 void Player::VisualizeItem( uint8 slot, Item *pItem)
10857 if(!pItem)
10858 return;
10860 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10861 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10862 pItem->SetBinding( true );
10864 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10866 m_items[slot] = pItem;
10867 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10868 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10869 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10870 pItem->SetSlot( slot );
10871 pItem->SetContainer( NULL );
10873 if( slot < EQUIPMENT_SLOT_END )
10874 SetVisibleItemSlot(slot, pItem);
10876 pItem->SetState(ITEM_CHANGED, this);
10879 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10881 // note: removeitem does not actually change the item
10882 // it only takes the item out of storage temporarily
10883 // note2: if removeitem is to be used for delinking
10884 // the item must be removed from the player's updatequeue
10886 Item *pItem = GetItemByPos( bag, slot );
10887 if( pItem )
10889 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10891 RemoveEnchantmentDurations(pItem);
10892 RemoveItemDurations(pItem);
10894 if( bag == INVENTORY_SLOT_BAG_0 )
10896 if ( slot < INVENTORY_SLOT_BAG_END )
10898 ItemPrototype const *pProto = pItem->GetProto();
10899 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10901 if(pProto && pProto->ItemSet)
10902 RemoveItemsSetItem(this, pProto);
10904 _ApplyItemMods(pItem, slot, false);
10906 // remove item dependent auras and casts (only weapon and armor slots)
10907 if(slot < EQUIPMENT_SLOT_END)
10909 RemoveItemDependentAurasAndCasts(pItem);
10911 // remove held enchantments, update expertise
10912 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10914 if (pItem->GetItemSuffixFactor())
10916 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10917 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10919 else
10921 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10922 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10925 UpdateExpertise(BASE_ATTACK);
10926 UpdateArmorPenetration();
10928 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10930 UpdateExpertise(OFF_ATTACK);
10931 UpdateArmorPenetration();
10935 // need update known currency
10936 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10937 UpdateKnownCurrencies(pItem->GetEntry(), false);
10939 m_items[slot] = NULL;
10940 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10942 if ( slot < EQUIPMENT_SLOT_END )
10943 SetVisibleItemSlot(slot, NULL);
10945 else
10947 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10948 if( pBag )
10949 pBag->RemoveItem(slot, update);
10951 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10952 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10953 pItem->SetSlot( NULL_SLOT );
10954 if( IsInWorld() && update )
10955 pItem->SendCreateUpdateToPlayer( this );
10959 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10960 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10962 if(Item* it = GetItemByPos(bag,slot))
10964 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10965 RemoveItem(bag, slot, update);
10966 it->RemoveFromUpdateQueueOf(this);
10967 if(it->IsInWorld())
10969 it->RemoveFromWorld();
10970 it->DestroyForPlayer( this );
10975 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10976 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10978 // update quest counters
10979 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10980 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, pItem->GetEntry(), pItem->GetCount());
10982 // store item
10983 Item* pLastItem = StoreItem(dest, pItem, update);
10985 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10986 if(pLastItem == pItem)
10988 // update owner for last item (this can be original item with wrong owner
10989 if(pLastItem->GetOwnerGUID() != GetGUID())
10990 pLastItem->SetOwnerGUID(GetGUID());
10992 // if this original item then it need create record in inventory
10993 // in case trade we already have item in other player inventory
10994 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10998 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
11000 Item *pItem = GetItemByPos( bag, slot );
11001 if( pItem )
11003 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
11005 // start from destroy contained items (only equipped bag can have its)
11006 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
11008 for (int i = 0; i < MAX_BAG_SIZE; ++i)
11009 DestroyItem(slot, i, update);
11012 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
11013 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
11015 RemoveEnchantmentDurations(pItem);
11016 RemoveItemDurations(pItem);
11018 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
11020 if( bag == INVENTORY_SLOT_BAG_0 )
11022 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
11024 // equipment and equipped bags can have applied bonuses
11025 if ( slot < INVENTORY_SLOT_BAG_END )
11027 ItemPrototype const *pProto = pItem->GetProto();
11029 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
11030 if(pProto && pProto->ItemSet)
11031 RemoveItemsSetItem(this, pProto);
11033 _ApplyItemMods(pItem, slot, false);
11036 if ( slot < EQUIPMENT_SLOT_END )
11038 // remove item dependent auras and casts (only weapon and armor slots)
11039 RemoveItemDependentAurasAndCasts(pItem);
11041 // update expertise
11042 if( slot == EQUIPMENT_SLOT_MAINHAND )
11044 UpdateExpertise(BASE_ATTACK);
11045 UpdateArmorPenetration();
11047 else if( slot == EQUIPMENT_SLOT_OFFHAND )
11049 UpdateExpertise(OFF_ATTACK);
11050 UpdateArmorPenetration();
11053 // equipment visual show
11054 SetVisibleItemSlot(slot, NULL);
11056 // need update known currency
11057 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
11058 UpdateKnownCurrencies(pItem->GetEntry(), false);
11060 m_items[slot] = NULL;
11062 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
11063 pBag->RemoveItem(slot, update);
11065 if( IsInWorld() && update )
11067 pItem->RemoveFromWorld();
11068 pItem->DestroyForPlayer(this);
11071 //pItem->SetOwnerGUID(0);
11072 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
11073 pItem->SetSlot( NULL_SLOT );
11074 pItem->SetState(ITEM_REMOVED, this);
11078 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
11080 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
11081 uint32 remcount = 0;
11083 // in inventory
11084 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11086 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11088 if (pItem->GetEntry() == item)
11090 if (pItem->GetCount() + remcount <= count)
11092 // all items in inventory can unequipped
11093 remcount += pItem->GetCount();
11094 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11096 if (remcount >= count)
11097 return;
11099 else
11101 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11102 pItem->SetCount( pItem->GetCount() - count + remcount );
11103 if (IsInWorld() & update)
11104 pItem->SendCreateUpdateToPlayer( this );
11105 pItem->SetState(ITEM_CHANGED, this);
11106 return;
11112 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
11114 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11116 if (pItem->GetEntry() == item)
11118 if (pItem->GetCount() + remcount <= count)
11120 // all keys can be unequipped
11121 remcount += pItem->GetCount();
11122 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11124 if (remcount >= count)
11125 return;
11127 else
11129 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11130 pItem->SetCount( pItem->GetCount() - count + remcount );
11131 if (IsInWorld() & update)
11132 pItem->SendCreateUpdateToPlayer( this );
11133 pItem->SetState(ITEM_CHANGED, this);
11134 return;
11140 // in inventory bags
11141 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11143 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11145 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11147 if(Item* pItem = pBag->GetItemByPos(j))
11149 if (pItem->GetEntry() == item)
11151 // all items in bags can be unequipped
11152 if (pItem->GetCount() + remcount <= count)
11154 remcount += pItem->GetCount();
11155 DestroyItem( i, j, update );
11157 if (remcount >= count)
11158 return;
11160 else
11162 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11163 pItem->SetCount( pItem->GetCount() - count + remcount );
11164 if (IsInWorld() && update)
11165 pItem->SendCreateUpdateToPlayer( this );
11166 pItem->SetState(ITEM_CHANGED, this);
11167 return;
11175 // in equipment and bag list
11176 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11178 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11180 if (pItem && pItem->GetEntry() == item)
11182 if (pItem->GetCount() + remcount <= count)
11184 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
11186 remcount += pItem->GetCount();
11187 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11189 if (remcount >= count)
11190 return;
11193 else
11195 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11196 pItem->SetCount( pItem->GetCount() - count + remcount );
11197 if (IsInWorld() & update)
11198 pItem->SendCreateUpdateToPlayer( this );
11199 pItem->SetState(ITEM_CHANGED, this);
11200 return;
11207 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
11209 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
11211 // in inventory
11212 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11213 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11214 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11215 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11217 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
11218 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11219 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11220 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11222 // in inventory bags
11223 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11224 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11225 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11226 if (Item* pItem = pBag->GetItemByPos(j))
11227 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11228 DestroyItem(i, j, update);
11230 // in equipment and bag list
11231 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11232 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11233 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11234 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11237 void Player::DestroyConjuredItems( bool update )
11239 // used when entering arena
11240 // destroys all conjured items
11241 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
11243 // in inventory
11244 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11245 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11246 if (pItem->IsConjuredConsumable())
11247 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11249 // in inventory bags
11250 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11251 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11252 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11253 if (Item* pItem = pBag->GetItemByPos(j))
11254 if (pItem->IsConjuredConsumable())
11255 DestroyItem( i, j, update);
11257 // in equipment and bag list
11258 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11259 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11260 if (pItem->IsConjuredConsumable())
11261 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11264 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
11266 if(!pItem)
11267 return;
11269 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
11271 if( pItem->GetCount() <= count )
11273 count -= pItem->GetCount();
11275 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
11277 else
11279 ItemRemovedQuestCheck( pItem->GetEntry(), count);
11280 pItem->SetCount( pItem->GetCount() - count );
11281 count = 0;
11282 if( IsInWorld() & update )
11283 pItem->SendCreateUpdateToPlayer( this );
11284 pItem->SetState(ITEM_CHANGED, this);
11288 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
11290 uint8 srcbag = src >> 8;
11291 uint8 srcslot = src & 255;
11293 uint8 dstbag = dst >> 8;
11294 uint8 dstslot = dst & 255;
11296 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11297 if( !pSrcItem )
11299 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11300 return;
11303 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11305 //best error message found for attempting to split while looting
11306 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11307 return;
11310 // not let split all items (can be only at cheating)
11311 if(pSrcItem->GetCount() == count)
11313 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11314 return;
11317 // not let split more existed items (can be only at cheating)
11318 if(pSrcItem->GetCount() < count)
11320 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
11321 return;
11324 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11325 Item *pNewItem = pSrcItem->CloneItem( count, this );
11326 if( !pNewItem )
11328 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11329 return;
11332 if( IsInventoryPos( dst ) )
11334 // change item amount before check (for unique max count check)
11335 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11337 ItemPosCountVec dest;
11338 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11339 if( msg != EQUIP_ERR_OK )
11341 delete pNewItem;
11342 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11343 SendEquipError( msg, pSrcItem, NULL );
11344 return;
11347 if( IsInWorld() )
11348 pSrcItem->SendCreateUpdateToPlayer( this );
11349 pSrcItem->SetState(ITEM_CHANGED, this);
11350 StoreItem( dest, pNewItem, true);
11352 else if( IsBankPos ( dst ) )
11354 // change item amount before check (for unique max count check)
11355 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11357 ItemPosCountVec dest;
11358 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11359 if( msg != EQUIP_ERR_OK )
11361 delete pNewItem;
11362 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11363 SendEquipError( msg, pSrcItem, NULL );
11364 return;
11367 if( IsInWorld() )
11368 pSrcItem->SendCreateUpdateToPlayer( this );
11369 pSrcItem->SetState(ITEM_CHANGED, this);
11370 BankItem( dest, pNewItem, true);
11372 else if( IsEquipmentPos ( dst ) )
11374 // change item amount before check (for unique max count check), provide space for splitted items
11375 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11377 uint16 dest;
11378 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11379 if( msg != EQUIP_ERR_OK )
11381 delete pNewItem;
11382 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11383 SendEquipError( msg, pSrcItem, NULL );
11384 return;
11387 if( IsInWorld() )
11388 pSrcItem->SendCreateUpdateToPlayer( this );
11389 pSrcItem->SetState(ITEM_CHANGED, this);
11390 EquipItem( dest, pNewItem, true);
11391 AutoUnequipOffhandIfNeed();
11395 void Player::SwapItem( uint16 src, uint16 dst )
11397 uint8 srcbag = src >> 8;
11398 uint8 srcslot = src & 255;
11400 uint8 dstbag = dst >> 8;
11401 uint8 dstslot = dst & 255;
11403 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11404 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11406 if (!pSrcItem)
11407 return;
11409 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11411 if (!isAlive())
11413 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11414 return;
11417 // SRC checks
11419 // check unequip potability for equipped items and bank bags
11420 if (IsEquipmentPos(src) || IsBagPos(src))
11422 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11423 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty()));
11424 if (msg != EQUIP_ERR_OK)
11426 SendEquipError( msg, pSrcItem, pDstItem );
11427 return;
11431 // prevent put equipped/bank bag in self
11432 if (IsBagPos(src) && srcslot == dstbag)
11434 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11435 return;
11438 // prevent put equipped/bank bag in self
11439 if (IsBagPos(dst) && dstslot == srcbag)
11441 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pDstItem, pSrcItem );
11442 return;
11445 // DST checks
11447 if (pDstItem)
11449 // check unequip potability for equipped items and bank bags
11450 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11452 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11453 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty()));
11454 if(msg != EQUIP_ERR_OK)
11456 SendEquipError( msg, pSrcItem, pDstItem );
11457 return;
11462 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11463 // or swap empty bag with another empty or not empty bag (with items exchange)
11465 // Move case
11466 if( !pDstItem )
11468 if( IsInventoryPos( dst ) )
11470 ItemPosCountVec dest;
11471 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11472 if( msg != EQUIP_ERR_OK )
11474 SendEquipError( msg, pSrcItem, NULL );
11475 return;
11478 RemoveItem(srcbag, srcslot, true);
11479 StoreItem( dest, pSrcItem, true);
11481 else if( IsBankPos ( dst ) )
11483 ItemPosCountVec dest;
11484 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11485 if( msg != EQUIP_ERR_OK )
11487 SendEquipError( msg, pSrcItem, NULL );
11488 return;
11491 RemoveItem(srcbag, srcslot, true);
11492 BankItem( dest, pSrcItem, true);
11494 else if( IsEquipmentPos ( dst ) )
11496 uint16 dest;
11497 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11498 if( msg != EQUIP_ERR_OK )
11500 SendEquipError( msg, pSrcItem, NULL );
11501 return;
11504 RemoveItem(srcbag, srcslot, true);
11505 EquipItem(dest, pSrcItem, true);
11506 AutoUnequipOffhandIfNeed();
11509 return;
11512 // attempt merge to / fill target item
11513 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11515 uint8 msg;
11516 ItemPosCountVec sDest;
11517 uint16 eDest;
11518 if( IsInventoryPos( dst ) )
11519 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11520 else if( IsBankPos ( dst ) )
11521 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11522 else if( IsEquipmentPos ( dst ) )
11523 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11524 else
11525 return;
11527 // can be merge/fill
11528 if(msg == EQUIP_ERR_OK)
11530 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11532 RemoveItem(srcbag, srcslot, true);
11534 if( IsInventoryPos( dst ) )
11535 StoreItem( sDest, pSrcItem, true);
11536 else if( IsBankPos ( dst ) )
11537 BankItem( sDest, pSrcItem, true);
11538 else if( IsEquipmentPos ( dst ) )
11540 EquipItem( eDest, pSrcItem, true);
11541 AutoUnequipOffhandIfNeed();
11544 else
11546 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11547 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11548 pSrcItem->SetState(ITEM_CHANGED, this);
11549 pDstItem->SetState(ITEM_CHANGED, this);
11550 if( IsInWorld() )
11552 pSrcItem->SendCreateUpdateToPlayer( this );
11553 pDstItem->SendCreateUpdateToPlayer( this );
11556 return;
11560 // impossible merge/fill, do real swap
11561 uint8 msg;
11563 // check src->dest move possibility
11564 ItemPosCountVec sDest;
11565 uint16 eDest = 0;
11566 if( IsInventoryPos( dst ) )
11567 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11568 else if( IsBankPos( dst ) )
11569 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11570 else if( IsEquipmentPos( dst ) )
11572 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11573 if( msg == EQUIP_ERR_OK )
11574 msg = CanUnequipItem( eDest, true );
11577 if( msg != EQUIP_ERR_OK )
11579 SendEquipError( msg, pSrcItem, pDstItem );
11580 return;
11583 // check dest->src move possibility
11584 ItemPosCountVec sDest2;
11585 uint16 eDest2 = 0;
11586 if( IsInventoryPos( src ) )
11587 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11588 else if( IsBankPos( src ) )
11589 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11590 else if( IsEquipmentPos( src ) )
11592 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11593 if( msg == EQUIP_ERR_OK )
11594 msg = CanUnequipItem( eDest2, true);
11597 if( msg != EQUIP_ERR_OK )
11599 SendEquipError( msg, pDstItem, pSrcItem );
11600 return;
11603 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11604 if(pSrcItem->IsBag() && pDstItem->IsBag())
11606 Bag* emptyBag = NULL;
11607 Bag* fullBag = NULL;
11608 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11610 emptyBag = (Bag*)pSrcItem;
11611 fullBag = (Bag*)pDstItem;
11613 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11615 emptyBag = (Bag*)pDstItem;
11616 fullBag = (Bag*)pSrcItem;
11619 // bag swap (with items exchange) case
11620 if(emptyBag && fullBag)
11622 ItemPrototype const* emotyProto = emptyBag->GetProto();
11624 uint32 count = 0;
11626 for(uint32 i=0; i < fullBag->GetBagSize(); ++i)
11628 Item *bagItem = fullBag->GetItemByPos(i);
11629 if (!bagItem)
11630 continue;
11632 ItemPrototype const* bagItemProto = bagItem->GetProto();
11633 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11635 // one from items not go to empty target bag
11636 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11637 return;
11640 ++count;
11644 if (count > emptyBag->GetBagSize())
11646 // too small targeted bag
11647 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11648 return;
11651 // Items swap
11652 count = 0; // will pos in new bag
11653 for(uint32 i = 0; i< fullBag->GetBagSize(); ++i)
11655 Item *bagItem = fullBag->GetItemByPos(i);
11656 if (!bagItem)
11657 continue;
11659 fullBag->RemoveItem(i, true);
11660 emptyBag->StoreItem(count, bagItem, true);
11661 bagItem->SetState(ITEM_CHANGED, this);
11663 ++count;
11668 // now do moves, remove...
11669 RemoveItem(dstbag, dstslot, false);
11670 RemoveItem(srcbag, srcslot, false);
11672 // add to dest
11673 if (IsInventoryPos(dst))
11674 StoreItem(sDest, pSrcItem, true);
11675 else if (IsBankPos(dst))
11676 BankItem(sDest, pSrcItem, true);
11677 else if (IsEquipmentPos(dst))
11678 EquipItem(eDest, pSrcItem, true);
11680 // add to src
11681 if (IsInventoryPos(src))
11682 StoreItem(sDest2, pDstItem, true);
11683 else if (IsBankPos(src))
11684 BankItem(sDest2, pDstItem, true);
11685 else if (IsEquipmentPos(src))
11686 EquipItem(eDest2, pDstItem, true);
11688 AutoUnequipOffhandIfNeed();
11691 void Player::AddItemToBuyBackSlot( Item *pItem )
11693 if (pItem)
11695 uint32 slot = m_currentBuybackSlot;
11696 // if current back slot non-empty search oldest or free
11697 if (m_items[slot])
11699 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11700 uint32 oldest_slot = BUYBACK_SLOT_START;
11702 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11704 // found empty
11705 if (!m_items[i])
11707 slot = i;
11708 break;
11711 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11713 if (oldest_time > i_time)
11715 oldest_time = i_time;
11716 oldest_slot = i;
11720 // find oldest
11721 slot = oldest_slot;
11724 RemoveItemFromBuyBackSlot( slot, true );
11725 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11727 m_items[slot] = pItem;
11728 time_t base = time(NULL);
11729 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11730 uint32 eslot = slot - BUYBACK_SLOT_START;
11732 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11733 if (ItemPrototype const *pProto = pItem->GetProto())
11734 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11735 else
11736 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11737 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11739 // move to next (for non filled list is move most optimized choice)
11740 if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11741 ++m_currentBuybackSlot;
11745 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11747 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11748 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11749 return m_items[slot];
11750 return NULL;
11753 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11755 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11756 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11758 Item *pItem = m_items[slot];
11759 if (pItem)
11761 pItem->RemoveFromWorld();
11762 if(del) pItem->SetState(ITEM_REMOVED, this);
11765 m_items[slot] = NULL;
11767 uint32 eslot = slot - BUYBACK_SLOT_START;
11768 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11769 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11770 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11772 // if current backslot is filled set to now free slot
11773 if (m_items[m_currentBuybackSlot])
11774 m_currentBuybackSlot = slot;
11778 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2, uint32 itemid /*= 0*/ )
11780 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11781 WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, 1+8+8+1);
11782 data << uint8(msg);
11784 if (msg != EQUIP_ERR_OK)
11786 data << uint64(pItem ? pItem->GetGUID() : 0);
11787 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11788 data << uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2
11790 switch(msg)
11792 case EQUIP_ERR_CANT_EQUIP_LEVEL_I:
11793 case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW:
11795 ItemPrototype const* proto = pItem ? pItem->GetProto() : sObjectMgr.GetItemPrototype(itemid);
11796 data << uint32(proto ? proto->RequiredLevel : 0);
11797 break;
11799 case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM: // no idea about this one...
11801 data << uint64(0);
11802 data << uint32(0);
11803 data << uint64(0);
11804 break;
11806 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS:
11807 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS:
11808 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS:
11810 ItemPrototype const* proto = pItem ? pItem->GetProto() : sObjectMgr.GetItemPrototype(itemid);
11811 data << uint32(proto ? proto->ItemLimitCategory : 0);
11812 break;
11814 default:
11815 break;
11818 GetSession()->SendPacket(&data);
11821 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11823 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11824 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11825 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11826 data << uint32(item);
11827 if (param > 0)
11828 data << uint32(param);
11829 data << uint8(msg);
11830 GetSession()->SendPacket(&data);
11833 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11835 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11836 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11837 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11838 data << uint64(guid);
11839 if (param > 0)
11840 data << uint32(param);
11841 data << uint8(msg);
11842 GetSession()->SendPacket(&data);
11845 void Player::ClearTrade()
11847 tradeGold = 0;
11848 acceptTrade = false;
11849 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11850 tradeItems[i] = NULL_SLOT;
11853 void Player::TradeCancel(bool sendback)
11855 if (pTrader)
11857 // send yellow "Trade canceled" message to both traders
11858 WorldSession* ws;
11859 ws = GetSession();
11860 if (sendback)
11861 ws->SendCancelTrade();
11862 ws = pTrader->GetSession();
11863 if (!ws->PlayerLogout())
11864 ws->SendCancelTrade();
11866 // cleanup
11867 ClearTrade();
11868 pTrader->ClearTrade();
11869 // prevent loss of reference
11870 pTrader->pTrader = NULL;
11871 pTrader = NULL;
11875 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11877 if (m_itemDuration.empty())
11878 return;
11880 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11882 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11884 Item* item = *itr;
11885 ++itr; // current element can be erased in UpdateDuration
11887 if ((realtimeonly && item->GetProto()->Duration < 0) || !realtimeonly)
11888 item->UpdateDuration(this,time);
11892 void Player::UpdateEnchantTime(uint32 time)
11894 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11896 assert(itr->item);
11897 next = itr;
11898 if (!itr->item->GetEnchantmentId(itr->slot))
11900 next = m_enchantDuration.erase(itr);
11902 else if (itr->leftduration <= time)
11904 ApplyEnchantment(itr->item, itr->slot, false, false);
11905 itr->item->ClearEnchantment(itr->slot);
11906 next = m_enchantDuration.erase(itr);
11908 else if (itr->leftduration > time)
11910 itr->leftduration -= time;
11911 ++next;
11916 void Player::AddEnchantmentDurations(Item *item)
11918 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11920 if (!item->GetEnchantmentId(EnchantmentSlot(x)))
11921 continue;
11923 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11924 if (duration > 0)
11925 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11929 void Player::RemoveEnchantmentDurations(Item *item)
11931 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11933 if (itr->item == item)
11935 // save duration in item
11936 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11937 itr = m_enchantDuration.erase(itr);
11939 else
11940 ++itr;
11944 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11946 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11947 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11949 next = itr;
11950 if (itr->slot == slot)
11952 if (itr->item && itr->item->GetEnchantmentId(slot))
11954 // remove from stats
11955 ApplyEnchantment(itr->item, slot, false, false);
11956 // remove visual
11957 itr->item->ClearEnchantment(slot);
11959 // remove from update list
11960 next = m_enchantDuration.erase(itr);
11962 else
11963 ++next;
11966 // remove enchants from inventory items
11967 // NOTE: no need to remove these from stats, since these aren't equipped
11968 // in inventory
11969 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11970 if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
11971 if (pItem->GetEnchantmentId(slot))
11972 pItem->ClearEnchantment(slot);
11974 // in inventory bags
11975 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11976 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11977 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11978 if (Item* pItem = pBag->GetItemByPos(j))
11979 if (pItem->GetEnchantmentId(slot))
11980 pItem->ClearEnchantment(slot);
11983 // duration == 0 will remove item enchant
11984 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11986 if (!item)
11987 return;
11989 if (slot >= MAX_ENCHANTMENT_SLOT)
11990 return;
11992 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11994 if (itr->item == item && itr->slot == slot)
11996 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11997 m_enchantDuration.erase(itr);
11998 break;
12001 if (item && duration > 0 )
12003 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
12004 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
12008 void Player::ApplyEnchantment(Item *item,bool apply)
12010 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
12011 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
12014 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
12016 if (!item)
12017 return;
12019 if (!item->IsEquipped())
12020 return;
12022 if (slot >= MAX_ENCHANTMENT_SLOT)
12023 return;
12025 uint32 enchant_id = item->GetEnchantmentId(slot);
12026 if (!enchant_id)
12027 return;
12029 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
12030 if (!pEnchant)
12031 return;
12033 if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
12034 return;
12036 if (!item->IsBroken())
12038 for (int s = 0; s < 3; ++s)
12040 uint32 enchant_display_type = pEnchant->type[s];
12041 uint32 enchant_amount = pEnchant->amount[s];
12042 uint32 enchant_spell_id = pEnchant->spellid[s];
12044 switch(enchant_display_type)
12046 case ITEM_ENCHANTMENT_TYPE_NONE:
12047 break;
12048 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
12049 // processed in Player::CastItemCombatSpell
12050 break;
12051 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
12052 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12053 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
12054 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
12055 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
12056 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
12057 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12058 break;
12059 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
12060 if (enchant_spell_id)
12062 if (apply)
12064 int32 basepoints = 0;
12065 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
12066 if (item->GetItemRandomPropertyId())
12068 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
12069 if (item_rand)
12071 // Search enchant_amount
12072 for (int k = 0; k < 3; ++k)
12074 if(item_rand->enchant_id[k] == enchant_id)
12076 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
12077 break;
12082 // Cast custom spell vs all equal basepoints getted from enchant_amount
12083 if (basepoints)
12084 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
12085 else
12086 CastSpell(this, enchant_spell_id, true, item);
12088 else
12089 RemoveAurasDueToItemSpell(item, enchant_spell_id);
12091 break;
12092 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
12093 if (!enchant_amount)
12095 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
12096 if(item_rand)
12098 for (int k = 0; k < 3; ++k)
12100 if(item_rand->enchant_id[k] == enchant_id)
12102 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
12103 break;
12109 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
12110 break;
12111 case ITEM_ENCHANTMENT_TYPE_STAT:
12113 if (!enchant_amount)
12115 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
12116 if(item_rand_suffix)
12118 for (int k = 0; k < 3; ++k)
12120 if(item_rand_suffix->enchant_id[k] == enchant_id)
12122 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
12123 break;
12129 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
12130 switch (enchant_spell_id)
12132 case ITEM_MOD_MANA:
12133 sLog.outDebug("+ %u MANA",enchant_amount);
12134 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
12135 break;
12136 case ITEM_MOD_HEALTH:
12137 sLog.outDebug("+ %u HEALTH",enchant_amount);
12138 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
12139 break;
12140 case ITEM_MOD_AGILITY:
12141 sLog.outDebug("+ %u AGILITY",enchant_amount);
12142 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
12143 ApplyStatBuffMod(STAT_AGILITY, float(enchant_amount), apply);
12144 break;
12145 case ITEM_MOD_STRENGTH:
12146 sLog.outDebug("+ %u STRENGTH",enchant_amount);
12147 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
12148 ApplyStatBuffMod(STAT_STRENGTH, float(enchant_amount), apply);
12149 break;
12150 case ITEM_MOD_INTELLECT:
12151 sLog.outDebug("+ %u INTELLECT",enchant_amount);
12152 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
12153 ApplyStatBuffMod(STAT_INTELLECT, float(enchant_amount), apply);
12154 break;
12155 case ITEM_MOD_SPIRIT:
12156 sLog.outDebug("+ %u SPIRIT",enchant_amount);
12157 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
12158 ApplyStatBuffMod(STAT_SPIRIT, float(enchant_amount), apply);
12159 break;
12160 case ITEM_MOD_STAMINA:
12161 sLog.outDebug("+ %u STAMINA",enchant_amount);
12162 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
12163 ApplyStatBuffMod(STAT_STAMINA, float(enchant_amount), apply);
12164 break;
12165 case ITEM_MOD_DEFENSE_SKILL_RATING:
12166 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
12167 sLog.outDebug("+ %u DEFENCE", enchant_amount);
12168 break;
12169 case ITEM_MOD_DODGE_RATING:
12170 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
12171 sLog.outDebug("+ %u DODGE", enchant_amount);
12172 break;
12173 case ITEM_MOD_PARRY_RATING:
12174 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
12175 sLog.outDebug("+ %u PARRY", enchant_amount);
12176 break;
12177 case ITEM_MOD_BLOCK_RATING:
12178 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
12179 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
12180 break;
12181 case ITEM_MOD_HIT_MELEE_RATING:
12182 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12183 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
12184 break;
12185 case ITEM_MOD_HIT_RANGED_RATING:
12186 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12187 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
12188 break;
12189 case ITEM_MOD_HIT_SPELL_RATING:
12190 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12191 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
12192 break;
12193 case ITEM_MOD_CRIT_MELEE_RATING:
12194 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12195 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
12196 break;
12197 case ITEM_MOD_CRIT_RANGED_RATING:
12198 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12199 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
12200 break;
12201 case ITEM_MOD_CRIT_SPELL_RATING:
12202 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12203 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
12204 break;
12205 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12206 // in Enchantments
12207 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12208 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12209 // break;
12210 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12211 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12212 // break;
12213 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12214 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12215 // break;
12216 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12217 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12218 // break;
12219 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12220 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12221 // break;
12222 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12223 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12224 // break;
12225 // case ITEM_MOD_HASTE_MELEE_RATING:
12226 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12227 // break;
12228 // case ITEM_MOD_HASTE_RANGED_RATING:
12229 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12230 // break;
12231 case ITEM_MOD_HASTE_SPELL_RATING:
12232 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12233 break;
12234 case ITEM_MOD_HIT_RATING:
12235 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12236 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12237 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12238 sLog.outDebug("+ %u HIT", enchant_amount);
12239 break;
12240 case ITEM_MOD_CRIT_RATING:
12241 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12242 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12243 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12244 sLog.outDebug("+ %u CRITICAL", enchant_amount);
12245 break;
12246 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12247 // case ITEM_MOD_HIT_TAKEN_RATING:
12248 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12249 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12250 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12251 // break;
12252 // case ITEM_MOD_CRIT_TAKEN_RATING:
12253 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12254 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12255 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12256 // break;
12257 case ITEM_MOD_RESILIENCE_RATING:
12258 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12259 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12260 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12261 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
12262 break;
12263 case ITEM_MOD_HASTE_RATING:
12264 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12265 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12266 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12267 sLog.outDebug("+ %u HASTE", enchant_amount);
12268 break;
12269 case ITEM_MOD_EXPERTISE_RATING:
12270 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
12271 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
12272 break;
12273 case ITEM_MOD_ATTACK_POWER:
12274 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
12275 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12276 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
12277 break;
12278 case ITEM_MOD_RANGED_ATTACK_POWER:
12279 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12280 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
12281 break;
12282 case ITEM_MOD_MANA_REGENERATION:
12283 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
12284 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
12285 break;
12286 case ITEM_MOD_ARMOR_PENETRATION_RATING:
12287 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
12288 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
12289 break;
12290 case ITEM_MOD_SPELL_POWER:
12291 ((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
12292 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
12293 break;
12294 case ITEM_MOD_FERAL_ATTACK_POWER:
12295 case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
12296 case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
12297 default:
12298 break;
12300 break;
12302 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
12304 if(getClass() == CLASS_SHAMAN)
12306 float addValue = 0.0f;
12307 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12309 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12310 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
12312 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
12314 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12315 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
12318 break;
12320 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
12321 // processed in Player::CastItemUseSpell
12322 break;
12323 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
12324 // nothing do..
12325 break;
12326 default:
12327 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
12328 break;
12329 } /*switch(enchant_display_type)*/
12330 } /*for*/
12333 // visualize enchantment at player and equipped items
12334 if(slot == PERM_ENCHANTMENT_SLOT)
12335 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
12337 if(slot == TEMP_ENCHANTMENT_SLOT)
12338 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
12341 if(apply_dur)
12343 if(apply)
12345 // set duration
12346 uint32 duration = item->GetEnchantmentDuration(slot);
12347 if(duration > 0)
12348 AddEnchantmentDuration(item, slot, duration);
12350 else
12352 // duration == 0 will remove EnchantDuration
12353 AddEnchantmentDuration(item, slot, 0);
12358 void Player::SendEnchantmentDurations()
12360 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
12362 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
12366 void Player::SendItemDurations()
12368 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
12370 (*itr)->SendTimeUpdate(this);
12374 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12376 if(!item) // prevent crash
12377 return;
12379 // last check 2.0.10
12380 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12381 data << uint64(GetGUID()); // player GUID
12382 data << uint32(received); // 0=looted, 1=from npc
12383 data << uint32(created); // 0=received, 1=created
12384 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12385 data << uint8(item->GetBagSlot()); // bagslot
12386 // item slot, but when added to stack: 0xFFFFFFFF
12387 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
12388 data << uint32(item->GetEntry()); // item id
12389 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12390 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12391 data << uint32(count); // count of items
12392 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
12394 if (broadcast && GetGroup())
12395 GetGroup()->BroadcastPacket(&data, true);
12396 else
12397 GetSession()->SendPacket(&data);
12400 /*********************************************************/
12401 /*** GOSSIP SYSTEM ***/
12402 /*********************************************************/
12404 void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId)
12406 PlayerMenu* pMenu = PlayerTalkClass;
12407 pMenu->ClearMenus();
12409 pMenu->GetGossipMenu().SetMenuId(menuId);
12411 GossipMenuItemsMapBounds pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(menuId);
12413 // if default menuId and no menu options exist for this, use options from default options
12414 if (pMenuItemBounds.first == pMenuItemBounds.second && menuId == GetDefaultGossipMenuForSource(pSource))
12415 pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(0);
12417 for(GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr)
12419 bool bCanTalk = true;
12421 if (itr->second.cond_1 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1))
12422 continue;
12424 if (itr->second.cond_2 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12425 continue;
12427 if (itr->second.cond_3 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_3))
12428 continue;
12430 if (pSource->GetTypeId() == TYPEID_UNIT)
12432 Creature *pCreature = (Creature*)pSource;
12434 uint32 npcflags = pCreature->GetUInt32Value(UNIT_NPC_FLAGS);
12436 if (!(itr->second.npc_option_npcflag & npcflags))
12437 continue;
12439 switch(itr->second.option_id)
12441 case GOSSIP_OPTION_QUESTGIVER:
12442 PrepareQuestMenu(pSource->GetGUID());
12443 bCanTalk = false;
12444 break;
12445 case GOSSIP_OPTION_ARMORER:
12446 bCanTalk = false; // added in special mode
12447 break;
12448 case GOSSIP_OPTION_SPIRITHEALER:
12449 if (!isDead())
12450 bCanTalk = false;
12451 break;
12452 case GOSSIP_OPTION_VENDOR:
12454 VendorItemData const* vItems = pCreature->GetVendorItems();
12455 if (!vItems || vItems->Empty())
12457 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature->GetGUIDLow(), pCreature->GetEntry());
12458 bCanTalk = false;
12460 break;
12462 case GOSSIP_OPTION_TRAINER:
12463 if (!pCreature->isCanTrainingOf(this, false))
12464 bCanTalk = false;
12465 break;
12466 case GOSSIP_OPTION_UNLEARNTALENTS:
12467 if (!pCreature->isCanTrainingAndResetTalentsOf(this))
12468 bCanTalk = false;
12469 break;
12470 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12471 if (!GetPet() || GetPet()->getPetType() != HUNTER_PET || GetPet()->m_spells.size() <= 1 || pCreature->GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || pCreature->GetCreatureInfo()->trainer_class != CLASS_HUNTER)
12472 bCanTalk = false;
12473 break;
12474 case GOSSIP_OPTION_TAXIVENDOR:
12475 if (GetSession()->SendLearnNewTaxiNode(pCreature))
12476 return;
12477 break;
12478 case GOSSIP_OPTION_BATTLEFIELD:
12479 if (!pCreature->isCanInteractWithBattleMaster(this, false))
12480 bCanTalk = false;
12481 break;
12482 case GOSSIP_OPTION_STABLEPET:
12483 if (getClass() != CLASS_HUNTER)
12484 bCanTalk = false;
12485 break;
12486 case GOSSIP_OPTION_GOSSIP:
12487 case GOSSIP_OPTION_SPIRITGUIDE:
12488 case GOSSIP_OPTION_INNKEEPER:
12489 case GOSSIP_OPTION_BANKER:
12490 case GOSSIP_OPTION_PETITIONER:
12491 case GOSSIP_OPTION_TABARDDESIGNER:
12492 case GOSSIP_OPTION_AUCTIONEER:
12493 break; // no checks
12494 default:
12495 sLog.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature->GetEntry(), itr->second.option_id, itr->second.menu_id);
12496 bCanTalk = false;
12497 break;
12500 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12502 GameObject *pGo = (GameObject*)pSource;
12504 switch(itr->second.option_id)
12506 case GOSSIP_OPTION_QUESTGIVER:
12507 if (pGo->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
12508 PrepareQuestMenu(pSource->GetGUID());
12509 bCanTalk = false;
12510 break;
12511 case GOSSIP_OPTION_GOSSIP:
12512 if (pGo->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && pGo->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
12513 bCanTalk = false;
12514 break;
12515 default:
12516 bCanTalk = false;
12517 break;
12521 if (bCanTalk)
12523 std::string strOptionText = itr->second.option_text;
12524 std::string strBoxText = itr->second.box_text;
12526 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12528 if (loc_idx >= 0)
12530 uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.id);
12532 if (GossipMenuItemsLocale const *no = sObjectMgr.GetGossipMenuItemsLocale(idxEntry))
12534 if (no->OptionText.size() > (size_t)loc_idx && !no->OptionText[loc_idx].empty())
12535 strOptionText = no->OptionText[loc_idx];
12537 if (no->BoxText.size() > (size_t)loc_idx && !no->BoxText[loc_idx].empty())
12538 strBoxText = no->BoxText[loc_idx];
12542 pMenu->GetGossipMenu().AddMenuItem(itr->second.option_icon, strOptionText, 0, itr->second.option_id, strBoxText, itr->second.box_money, itr->second.box_coded);
12543 pMenu->GetGossipMenu().AddGossipMenuItemData(itr->second.action_menu_id, itr->second.action_poi_id, itr->second.action_script_id);
12547 // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
12548 /*if (pMenu->Empty())
12550 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
12552 // output error message if need
12553 pCreature->isCanTrainingOf(this, true);
12556 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
12558 // output error message if need
12559 pCreature->isCanInteractWithBattleMaster(this, true);
12564 void Player::SendPreparedGossip(WorldObject *pSource)
12566 if (!pSource)
12567 return;
12569 if (pSource->GetTypeId() == TYPEID_UNIT)
12571 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
12572 if (!((Creature*)pSource)->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
12574 SendPreparedQuest(pSource->GetGUID());
12575 return;
12578 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12580 // probably need to find a better way here
12581 if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
12583 SendPreparedQuest(pSource->GetGUID());
12584 return;
12588 // in case non empty gossip menu (that not included quests list size) show it
12589 // (quest entries from quest menu will be included in list)
12591 uint32 textId = GetGossipTextId(pSource);
12593 if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
12594 textId = GetGossipTextId(menuId);
12596 PlayerTalkClass->SendGossipMenu(textId, pSource->GetGUID());
12599 void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 menuId)
12601 GossipMenu& gossipmenu = PlayerTalkClass->GetGossipMenu();
12603 if (gossipListId >= gossipmenu.MenuItemCount())
12604 return;
12606 // if not same, then something funky is going on
12607 if (menuId != gossipmenu.GetMenuId())
12608 return;
12610 uint32 gossipOptionId = gossipmenu.GetItem(gossipListId).m_gOptionId;
12611 uint64 guid = pSource->GetGUID();
12613 if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12615 if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
12617 sLog.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource->GetEntry());
12618 return;
12622 GossipMenuItemData pMenuData = gossipmenu.GetItemData(gossipListId);
12624 switch(gossipOptionId)
12626 case GOSSIP_OPTION_GOSSIP:
12628 if (pMenuData.m_gAction_poi)
12629 PlayerTalkClass->SendPointOfInterest(pMenuData.m_gAction_poi);
12631 if (pMenuData.m_gAction_menu)
12633 PrepareGossipMenu(pSource, pMenuData.m_gAction_menu);
12634 SendPreparedGossip(pSource);
12637 if (pMenuData.m_gAction_script)
12639 if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12640 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, this, pSource);
12641 else if (pSource->GetTypeId() == TYPEID_UNIT)
12642 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, pSource, this);
12645 break;
12647 case GOSSIP_OPTION_SPIRITHEALER:
12648 if (isDead())
12649 ((Creature*)pSource)->CastSpell(((Creature*)pSource),17251,true,NULL,NULL,GetGUID());
12650 break;
12651 case GOSSIP_OPTION_QUESTGIVER:
12652 PrepareQuestMenu(guid);
12653 SendPreparedQuest(guid);
12654 break;
12655 case GOSSIP_OPTION_VENDOR:
12656 case GOSSIP_OPTION_ARMORER:
12657 GetSession()->SendListInventory(guid);
12658 break;
12659 case GOSSIP_OPTION_STABLEPET:
12660 GetSession()->SendStablePet(guid);
12661 break;
12662 case GOSSIP_OPTION_TRAINER:
12663 GetSession()->SendTrainerList(guid);
12664 break;
12665 case GOSSIP_OPTION_UNLEARNTALENTS:
12666 PlayerTalkClass->CloseGossip();
12667 SendTalentWipeConfirm(guid);
12668 break;
12669 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12670 PlayerTalkClass->CloseGossip();
12671 SendPetSkillWipeConfirm();
12672 break;
12673 case GOSSIP_OPTION_TAXIVENDOR:
12674 GetSession()->SendTaxiMenu(((Creature*)pSource));
12675 break;
12676 case GOSSIP_OPTION_INNKEEPER:
12677 PlayerTalkClass->CloseGossip();
12678 SetBindPoint(guid);
12679 break;
12680 case GOSSIP_OPTION_BANKER:
12681 GetSession()->SendShowBank(guid);
12682 break;
12683 case GOSSIP_OPTION_PETITIONER:
12684 PlayerTalkClass->CloseGossip();
12685 GetSession()->SendPetitionShowList(guid);
12686 break;
12687 case GOSSIP_OPTION_TABARDDESIGNER:
12688 PlayerTalkClass->CloseGossip();
12689 GetSession()->SendTabardVendorActivate(guid);
12690 break;
12691 case GOSSIP_OPTION_AUCTIONEER:
12692 GetSession()->SendAuctionHello(guid, ((Creature*)pSource));
12693 break;
12694 case GOSSIP_OPTION_SPIRITGUIDE:
12695 PrepareGossipMenu(pSource);
12696 SendPreparedGossip(pSource);
12697 break;
12698 case GOSSIP_OPTION_BATTLEFIELD:
12700 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(pSource->GetEntry());
12702 if (bgTypeId == BATTLEGROUND_TYPE_NONE)
12704 sLog.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
12705 return;
12708 GetSession()->SendBattlegGroundList(guid, bgTypeId);
12709 break;
12714 uint32 Player::GetGossipTextId(WorldObject *pSource)
12716 if (!pSource || pSource->GetTypeId() != TYPEID_UNIT || !((Creature*)pSource)->GetDBTableGUIDLow())
12717 return DEFAULT_GOSSIP_MESSAGE;
12719 if (uint32 pos = sObjectMgr.GetNpcGossip(((Creature*)pSource)->GetDBTableGUIDLow()))
12720 return pos;
12722 return DEFAULT_GOSSIP_MESSAGE;
12725 uint32 Player::GetGossipTextId(uint32 menuId)
12727 uint32 textId = DEFAULT_GOSSIP_MESSAGE;
12729 if (!menuId)
12730 return textId;
12732 GossipMenusMapBounds pMenuBounds = sObjectMgr.GetGossipMenusMapBounds(menuId);
12734 for(GossipMenusMap::const_iterator itr = pMenuBounds.first; itr != pMenuBounds.second; ++itr)
12736 if (sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1) && sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12737 textId = itr->second.text_id;
12740 return textId;
12743 uint32 Player::GetDefaultGossipMenuForSource(WorldObject *pSource)
12745 if (pSource->GetTypeId() == TYPEID_UNIT)
12746 return ((Creature*)pSource)->GetCreatureInfo()->GossipMenuId;
12747 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12748 return((GameObject*)pSource)->GetGOInfo()->GetGossipMenuId();
12750 return 0;
12753 /*********************************************************/
12754 /*** QUEST SYSTEM ***/
12755 /*********************************************************/
12757 void Player::PrepareQuestMenu( uint64 guid )
12759 Object *pObject;
12760 QuestRelations* pObjectQR;
12761 QuestRelations* pObjectQIR;
12763 // pets also can have quests
12764 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12766 pObject = (Object*)pCreature;
12767 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
12768 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
12770 else
12772 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12773 //only for quests which cast teleport spells on player
12774 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
12775 ASSERT(_map);
12776 GameObject *pGameObject = _map->GetGameObject(guid);
12777 if( pGameObject )
12779 pObject = (Object*)pGameObject;
12780 pObjectQR = &sObjectMgr.mGOQuestRelations;
12781 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
12783 else
12784 return;
12787 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12788 qm.ClearMenu();
12790 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12792 uint32 quest_id = i->second;
12793 QuestStatus status = GetQuestStatus( quest_id );
12794 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12795 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12796 else if ( status == QUEST_STATUS_INCOMPLETE )
12797 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12798 else if (status == QUEST_STATUS_AVAILABLE )
12799 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12802 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12804 uint32 quest_id = i->second;
12805 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12806 if(!pQuest) continue;
12808 QuestStatus status = GetQuestStatus( quest_id );
12810 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12811 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12812 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12813 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12817 void Player::SendPreparedQuest(uint64 guid)
12819 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12821 if (questMenu.Empty())
12822 return;
12824 QuestMenuItem const& qmi0 = questMenu.GetItem(0);
12826 uint32 status = qmi0.m_qIcon;
12828 // single element case
12829 if (questMenu.MenuItemCount() == 1)
12831 // Auto open -- maybe also should verify there is no greeting
12832 uint32 quest_id = qmi0.m_qId;
12833 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12835 if (pQuest)
12837 if (status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus(quest_id))
12838 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12839 else if (status == DIALOG_STATUS_UNK2)
12840 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12841 // Send completable on repeatable and autoCompletable quest if player don't have quest
12842 // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
12843 else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDaily())
12844 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true);
12845 else
12846 PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true);
12849 // multiply entries
12850 else
12852 QEmote qe;
12853 qe._Delay = 0;
12854 qe._Emote = 0;
12855 std::string title = "";
12857 // need pet case for some quests
12858 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12860 uint32 textid = GetGossipTextId(pCreature);
12862 GossipText const* gossiptext = sObjectMgr.GetGossipText(textid);
12863 if (!gossiptext)
12865 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12866 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12867 title = "";
12869 else
12871 qe = gossiptext->Options[0].Emotes[0];
12873 if(!gossiptext->Options[0].Text_0.empty())
12875 title = gossiptext->Options[0].Text_0;
12877 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12878 if (loc_idx >= 0)
12880 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12881 if (nl)
12883 if ((int32)nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12884 title = nl->Text_0[0][loc_idx];
12888 else
12890 title = gossiptext->Options[0].Text_1;
12892 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12893 if (loc_idx >= 0)
12895 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12896 if (nl)
12898 if ((int32)nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12899 title = nl->Text_1[0][loc_idx];
12905 PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
12909 bool Player::IsActiveQuest( uint32 quest_id ) const
12911 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12913 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12916 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12918 Object *pObject;
12919 QuestRelations* pObjectQR;
12920 QuestRelations* pObjectQIR;
12922 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12924 pObject = (Object*)pCreature;
12925 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
12926 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
12928 else
12930 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12931 //only for quests which cast teleport spells on player
12932 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
12933 ASSERT(_map);
12934 GameObject *pGameObject = _map->GetGameObject(guid);
12935 if( pGameObject )
12937 pObject = (Object*)pGameObject;
12938 pObjectQR = &sObjectMgr.mGOQuestRelations;
12939 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
12941 else
12942 return NULL;
12945 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12946 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12948 if (itr->second == nextQuestID)
12949 return sObjectMgr.GetQuestTemplate(nextQuestID);
12952 return NULL;
12955 bool Player::CanSeeStartQuest( Quest const *pQuest )
12957 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12958 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12959 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12960 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12962 return getLevel() + sWorld.getConfig(CONFIG_UINT32_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12965 return false;
12968 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12970 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12971 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12972 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12973 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12974 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12975 && SatisfyQuestDay( pQuest, msg );
12978 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12980 if( !SatisfyQuestLog( msg ) )
12981 return false;
12983 uint32 srcitem = pQuest->GetSrcItemId();
12984 if( srcitem > 0 )
12986 uint32 count = pQuest->GetSrcItemCount();
12987 ItemPosCountVec dest;
12988 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12990 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12991 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12992 return true;
12993 else if( msg2 != EQUIP_ERR_OK )
12995 SendEquipError(msg2, NULL, NULL, srcitem);
12996 return false;
12999 return true;
13002 bool Player::CanCompleteQuest( uint32 quest_id )
13004 if( quest_id )
13006 QuestStatusData& q_status = mQuestStatus[quest_id];
13007 if( q_status.m_status == QUEST_STATUS_COMPLETE )
13008 return false; // not allow re-complete quest
13010 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13012 if(!qInfo)
13013 return false;
13015 // auto complete quest
13016 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
13017 return true;
13019 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13022 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13024 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13026 if( qInfo->ReqItemCount[i] != 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
13027 return false;
13031 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
13033 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13035 if( qInfo->ReqCreatureOrGOId[i] == 0 )
13036 continue;
13038 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
13039 return false;
13043 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
13044 return false;
13046 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
13047 return false;
13049 if ( qInfo->GetRewOrReqMoney() < 0 )
13051 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
13052 return false;
13055 uint32 repFacId = qInfo->GetRepObjectiveFaction();
13056 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
13057 return false;
13059 return true;
13062 return false;
13065 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
13067 // Solve problem that player don't have the quest and try complete it.
13068 // if repeatable she must be able to complete event if player don't have it.
13069 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
13070 if( !CanTakeQuest(pQuest, false) )
13071 return false;
13073 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
13074 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13075 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i], pQuest->ReqItemCount[i]) )
13076 return false;
13078 if( !CanRewardQuest(pQuest, false) )
13079 return false;
13081 return true;
13084 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
13086 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
13087 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
13088 return false;
13090 // daily quest can't be rewarded (25 daily quest already completed)
13091 if(!SatisfyQuestDay(pQuest,true))
13092 return false;
13094 // rewarded and not repeatable quest (only cheating case, then ignore without message)
13095 if(GetQuestRewardStatus(pQuest->GetQuestId()))
13096 return false;
13098 // prevent receive reward with quest items in bank
13099 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13101 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13103 if( pQuest->ReqItemCount[i] != 0 &&
13104 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
13106 if(msg)
13107 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL, pQuest->ReqItemId[i]);
13108 return false;
13113 // prevent receive reward with low money and GetRewOrReqMoney() < 0
13114 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
13115 return false;
13117 return true;
13120 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
13122 // prevent receive reward with quest items in bank or for not completed quest
13123 if(!CanRewardQuest(pQuest,msg))
13124 return false;
13126 if ( pQuest->GetRewChoiceItemsCount() > 0 )
13128 if( pQuest->RewChoiceItemId[reward] )
13130 ItemPosCountVec dest;
13131 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
13132 if( res != EQUIP_ERR_OK )
13134 SendEquipError( res, NULL, NULL, pQuest->RewChoiceItemId[reward] );
13135 return false;
13140 if ( pQuest->GetRewItemsCount() > 0 )
13142 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
13144 if( pQuest->RewItemId[i] )
13146 ItemPosCountVec dest;
13147 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
13148 if( res != EQUIP_ERR_OK )
13150 SendEquipError( res, NULL, NULL );
13151 return false;
13157 return true;
13160 void Player::SendPetTameFailure(PetTameFailureReason reason)
13162 WorldPacket data(SMSG_PET_TAME_FAILURE, 1);
13163 data << uint8(reason);
13164 GetSession()->SendPacket(&data);
13167 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
13169 uint16 log_slot = FindQuestSlot( 0 );
13170 assert(log_slot < MAX_QUEST_LOG_SIZE);
13172 uint32 quest_id = pQuest->GetQuestId();
13174 // if not exist then created with set uState==NEW and rewarded=false
13175 QuestStatusData& questStatusData = mQuestStatus[quest_id];
13177 // check for repeatable quests status reset
13178 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
13179 questStatusData.m_explored = false;
13181 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13183 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13184 questStatusData.m_itemcount[i] = 0;
13187 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
13189 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13190 questStatusData.m_creatureOrGOcount[i] = 0;
13193 GiveQuestSourceItem( pQuest );
13194 AdjustQuestReqItemCount( pQuest, questStatusData );
13196 if( pQuest->GetRepObjectiveFaction() )
13197 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
13198 GetReputationMgr().SetVisible(factionEntry);
13200 uint32 qtime = 0;
13201 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13203 uint32 limittime = pQuest->GetLimitTime();
13205 // shared timed quest
13206 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
13207 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
13209 AddTimedQuest( quest_id );
13210 questStatusData.m_timer = limittime * IN_MILISECONDS;
13211 qtime = static_cast<uint32>(time(NULL)) + limittime;
13213 else
13214 questStatusData.m_timer = 0;
13216 SetQuestSlot(log_slot, quest_id, qtime);
13218 if (questStatusData.uState != QUEST_NEW)
13219 questStatusData.uState = QUEST_CHANGED;
13221 //starting initial quest script
13222 if(questGiver && pQuest->GetQuestStartScript()!=0)
13223 GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
13225 // Some spells applied at quest activation
13226 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,true);
13227 if(saBounds.first != saBounds.second)
13229 uint32 zone, area;
13230 GetZoneAndAreaId(zone,area);
13232 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13233 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13234 if (!HasAura(itr->second->spellId, EFFECT_INDEX_0) )
13235 CastSpell(this,itr->second->spellId,true);
13238 UpdateForQuestWorldObjects();
13241 void Player::CompleteQuest( uint32 quest_id )
13243 if( quest_id )
13245 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
13247 uint16 log_slot = FindQuestSlot( quest_id );
13248 if( log_slot < MAX_QUEST_LOG_SIZE)
13249 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13251 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
13253 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
13254 RewardQuest(qInfo,0,this,false);
13255 else
13256 SendQuestComplete( quest_id );
13261 void Player::IncompleteQuest( uint32 quest_id )
13263 if( quest_id )
13265 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
13267 uint16 log_slot = FindQuestSlot( quest_id );
13268 if( log_slot < MAX_QUEST_LOG_SIZE)
13269 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13273 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
13275 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
13276 //should work fine, cause far teleport will be executed in Player::Update()
13277 SetCanDelayTeleport(true);
13279 uint32 quest_id = pQuest->GetQuestId();
13281 for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i )
13283 if (pQuest->ReqItemId[i])
13284 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
13287 RemoveTimedQuest(quest_id);
13289 if (BattleGround* bg = GetBattleGround())
13290 if (bg->GetTypeID() == BATTLEGROUND_AV)
13291 ((BattleGroundAV*)bg)->HandleQuestComplete(pQuest->GetQuestId(), this);
13293 if (pQuest->GetRewChoiceItemsCount() > 0)
13295 if (uint32 itemId = pQuest->RewChoiceItemId[reward])
13297 ItemPosCountVec dest;
13298 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK)
13300 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13301 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
13306 if (pQuest->GetRewItemsCount() > 0)
13308 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
13310 if (uint32 itemId = pQuest->RewItemId[i])
13312 ItemPosCountVec dest;
13313 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i] ) == EQUIP_ERR_OK)
13315 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13316 SendNewItem(item, pQuest->RewItemCount[i], true, false);
13322 RewardReputation( pQuest );
13324 uint16 log_slot = FindQuestSlot( quest_id );
13325 if (log_slot < MAX_QUEST_LOG_SIZE)
13326 SetQuestSlot(log_slot,0);
13328 QuestStatusData& q_status = mQuestStatus[quest_id];
13330 // Not give XP in case already completed once repeatable quest
13331 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_QUEST));
13333 if (getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
13334 GiveXP( XP , NULL );
13335 else
13337 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY));
13338 ModifyMoney( money );
13339 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
13342 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
13343 if (pQuest->GetRewOrReqMoney())
13345 ModifyMoney( pQuest->GetRewOrReqMoney() );
13347 if (pQuest->GetRewOrReqMoney() > 0)
13348 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
13351 // honor reward
13352 if (pQuest->GetRewHonorAddition())
13353 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorAddition()));
13355 // title reward
13356 if (pQuest->GetCharTitleId())
13358 if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
13359 SetTitle(titleEntry);
13362 if (pQuest->GetBonusTalents())
13364 m_questRewardTalentCount+=pQuest->GetBonusTalents();
13365 InitTalentForLevel();
13368 // Send reward mail
13369 if (uint32 mail_template_id = pQuest->GetRewMailTemplateId())
13370 MailDraft(mail_template_id).SendMailTo(this, questGiver, MAIL_CHECK_MASK_NONE, pQuest->GetRewMailDelaySecs());
13372 if (pQuest->IsDaily())
13374 SetDailyQuestStatus(quest_id);
13375 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
13378 if (!pQuest->IsRepeatable())
13379 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
13380 else
13381 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
13383 q_status.m_rewarded = true;
13384 if (q_status.uState != QUEST_NEW)
13385 q_status.uState = QUEST_CHANGED;
13387 if (announce)
13388 SendQuestReward( pQuest, XP, questGiver );
13390 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
13391 if (pQuest->GetRewSpellCast() > 0)
13392 CastSpell( this, pQuest->GetRewSpellCast(), true);
13393 else if ( pQuest->GetRewSpell() > 0)
13394 CastSpell( this, pQuest->GetRewSpell(), true);
13396 if (pQuest->GetZoneOrSort() > 0)
13397 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
13398 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
13399 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
13401 uint32 zone = 0;
13402 uint32 area = 0;
13404 // remove auras from spells with quest reward state limitations
13405 SpellAreaForQuestMapBounds saEndBounds = sSpellMgr.GetSpellAreaForQuestEndMapBounds(quest_id);
13406 if(saEndBounds.first != saEndBounds.second)
13408 GetZoneAndAreaId(zone,area);
13410 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
13411 if(!itr->second->IsFitToRequirements(this,zone,area))
13412 RemoveAurasDueToSpell(itr->second->spellId);
13415 // Some spells applied at quest reward
13416 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,false);
13417 if(saBounds.first != saBounds.second)
13419 if(!zone || !area)
13420 GetZoneAndAreaId(zone,area);
13422 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13423 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13424 if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
13425 CastSpell(this,itr->second->spellId,true);
13428 //lets remove flag for delayed teleports
13429 SetCanDelayTeleport(false);
13432 void Player::FailQuest(uint32 questId)
13434 if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(questId))
13436 SetQuestStatus(questId, QUEST_STATUS_FAILED);
13438 uint16 log_slot = FindQuestSlot(questId);
13440 if (log_slot < MAX_QUEST_LOG_SIZE)
13442 SetQuestSlotTimer(log_slot, 1);
13443 SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
13446 if (pQuest->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13448 QuestStatusData& q_status = mQuestStatus[questId];
13450 RemoveTimedQuest(questId);
13451 q_status.m_timer = 0;
13453 SendQuestTimerFailed(questId);
13455 else
13456 SendQuestFailed(questId);
13460 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
13462 int32 zoneOrSort = qInfo->GetZoneOrSort();
13463 int32 skillOrClass = qInfo->GetSkillOrClass();
13465 // skip zone zoneOrSort and 0 case skillOrClass
13466 if( zoneOrSort >= 0 && skillOrClass == 0 )
13467 return true;
13469 int32 questSort = -zoneOrSort;
13470 uint8 reqSortClass = ClassByQuestSort(questSort);
13472 // check class sort cases in zoneOrSort
13473 if( reqSortClass != 0 && getClass() != reqSortClass)
13475 if( msg )
13476 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13477 return false;
13480 // check class
13481 if( skillOrClass < 0 )
13483 uint8 reqClass = -int32(skillOrClass);
13484 if(getClass() != reqClass)
13486 if( msg )
13487 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13488 return false;
13491 // check skill
13492 else if( skillOrClass > 0 )
13494 uint32 reqSkill = skillOrClass;
13495 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
13497 if( msg )
13498 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13499 return false;
13503 return true;
13506 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
13508 if( getLevel() < qInfo->GetMinLevel() )
13510 if( msg )
13511 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13512 return false;
13514 return true;
13517 bool Player::SatisfyQuestLog( bool msg )
13519 // exist free slot
13520 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
13521 return true;
13523 if( msg )
13525 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
13526 GetSession()->SendPacket( &data );
13527 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
13529 return false;
13532 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
13534 // No previous quest (might be first quest in a series)
13535 if( qInfo->prevQuests.empty())
13536 return true;
13538 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
13540 uint32 prevId = abs(*iter);
13542 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13543 Quest const* qPrevInfo = sObjectMgr.GetQuestTemplate(prevId);
13545 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
13547 // If any of the positive previous quests completed, return true
13548 if( *iter > 0 && i_prevstatus->second.m_rewarded )
13550 // skip one-from-all exclusive group
13551 if(qPrevInfo->GetExclusiveGroup() >= 0)
13552 return true;
13554 // each-from-all exclusive group ( < 0)
13555 // can be start if only all quests in prev quest exclusive group completed and rewarded
13556 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13557 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13559 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13561 for(; iter2 != end; ++iter2)
13563 uint32 exclude_Id = iter2->second;
13565 // skip checked quest id, only state of other quests in group is interesting
13566 if(exclude_Id == prevId)
13567 continue;
13569 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13571 // alternative quest from group also must be completed and rewarded(reported)
13572 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
13574 if( msg )
13575 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13576 return false;
13579 return true;
13581 // If any of the negative previous quests active, return true
13582 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13583 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
13585 // skip one-from-all exclusive group
13586 if(qPrevInfo->GetExclusiveGroup() >= 0)
13587 return true;
13589 // each-from-all exclusive group ( < 0)
13590 // can be start if only all quests in prev quest exclusive group active
13591 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13592 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13594 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13596 for(; iter2 != end; ++iter2)
13598 uint32 exclude_Id = iter2->second;
13600 // skip checked quest id, only state of other quests in group is interesting
13601 if(exclude_Id == prevId)
13602 continue;
13604 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13606 // alternative quest from group also must be active
13607 if( i_exstatus == mQuestStatus.end() ||
13608 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
13609 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
13611 if( msg )
13612 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13613 return false;
13616 return true;
13621 // Has only positive prev. quests in non-rewarded state
13622 // and negative prev. quests in non-active state
13623 if( msg )
13624 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13626 return false;
13629 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
13631 uint32 reqraces = qInfo->GetRequiredRaces();
13632 if ( reqraces == 0 )
13633 return true;
13634 if( (reqraces & getRaceMask()) == 0 )
13636 if( msg )
13637 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13638 return false;
13640 return true;
13643 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13645 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13646 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13648 if( msg )
13649 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13650 return false;
13653 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13654 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13656 if( msg )
13657 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13658 return false;
13661 return true;
13664 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13666 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13667 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13669 if( msg )
13670 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13671 return false;
13673 return true;
13676 bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
13678 if (!m_timedquests.empty() && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13680 if (msg)
13681 SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
13683 return false;
13685 return true;
13688 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13690 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13691 if(qInfo->GetExclusiveGroup() <= 0)
13692 return true;
13694 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = sObjectMgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13695 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13697 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13699 for(; iter != end; ++iter)
13701 uint32 exclude_Id = iter->second;
13703 // skip checked quest id, only state of other quests in group is interesting
13704 if(exclude_Id == qInfo->GetQuestId())
13705 continue;
13707 // not allow have daily quest if daily quest from exclusive group already recently completed
13708 Quest const* Nquest = sObjectMgr.GetQuestTemplate(exclude_Id);
13709 if( !SatisfyQuestDay(Nquest, false) )
13711 if( msg )
13712 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13713 return false;
13716 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13718 // alternative quest already started or completed
13719 if( i_exstatus != mQuestStatus.end()
13720 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13722 if( msg )
13723 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13724 return false;
13727 return true;
13730 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13732 if(!qInfo->GetNextQuestInChain())
13733 return true;
13735 // next quest in chain already started or completed
13736 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13737 if( itr != mQuestStatus.end()
13738 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13740 if( msg )
13741 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13742 return false;
13745 // check for all quests further up the chain
13746 // only necessary if there are quest chains with more than one quest that can be skipped
13747 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13748 return true;
13751 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13753 // No previous quest in chain
13754 if( qInfo->prevChainQuests.empty())
13755 return true;
13757 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13759 uint32 prevId = *iter;
13761 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13763 if( i_prevstatus != mQuestStatus.end() )
13765 // If any of the previous quests in chain active, return false
13766 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13767 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13769 if( msg )
13770 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13771 return false;
13775 // check for all quests further down the chain
13776 // only necessary if there are quest chains with more than one quest that can be skipped
13777 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13778 // return false;
13781 // No previous quest in chain active
13782 return true;
13785 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13787 if(!qInfo->IsDaily())
13788 return true;
13790 bool have_slot = false;
13791 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13793 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13794 if(qInfo->GetQuestId()==id)
13795 return false;
13797 if(!id)
13798 have_slot = true;
13801 if(!have_slot)
13803 if( msg )
13804 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13805 return false;
13808 return true;
13811 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13813 uint32 srcitem = pQuest->GetSrcItemId();
13814 if( srcitem > 0 )
13816 uint32 count = pQuest->GetSrcItemCount();
13817 if( count <= 0 )
13818 count = 1;
13820 ItemPosCountVec dest;
13821 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13822 if( msg == EQUIP_ERR_OK )
13824 Item * item = StoreNewItem(dest, srcitem, true);
13825 SendNewItem(item, count, true, false);
13826 return true;
13828 // player already have max amount required item, just report success
13829 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13830 return true;
13831 else
13832 SendEquipError( msg, NULL, NULL, srcitem );
13833 return false;
13836 return true;
13839 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13841 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13842 if( qInfo )
13844 uint32 srcitem = qInfo->GetSrcItemId();
13845 if( srcitem > 0 )
13847 uint32 count = qInfo->GetSrcItemCount();
13848 if( count <= 0 )
13849 count = 1;
13851 // exist one case when destroy source quest item not possible:
13852 // non un-equippable item (equipped non-empty bag, for example)
13853 uint8 res = CanUnequipItems(srcitem,count);
13854 if(res != EQUIP_ERR_OK)
13856 if(msg)
13857 SendEquipError( res, NULL, NULL, srcitem );
13858 return false;
13861 DestroyItemCount(srcitem, count, true, true);
13864 return true;
13867 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13869 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13870 if( qInfo )
13872 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13873 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13874 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13875 && !qInfo->IsRepeatable() )
13876 return itr->second.m_rewarded;
13878 return false;
13880 return false;
13883 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13885 if( quest_id )
13887 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13888 if( itr != mQuestStatus.end() )
13889 return itr->second.m_status;
13891 return QUEST_STATUS_NONE;
13894 bool Player::CanShareQuest(uint32 quest_id) const
13896 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13897 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13899 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13900 if( itr != mQuestStatus.end() )
13901 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13903 return false;
13906 void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
13908 if (sObjectMgr.GetQuestTemplate(quest_id))
13910 QuestStatusData& q_status = mQuestStatus[quest_id];
13912 q_status.m_status = status;
13914 if (q_status.uState != QUEST_NEW)
13915 q_status.uState = QUEST_CHANGED;
13918 UpdateForQuestWorldObjects();
13921 // not used in MaNGOS, but used in scripting code
13922 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13924 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13925 if( !qInfo )
13926 return 0;
13928 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13929 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13930 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13932 return 0;
13935 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13937 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13939 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13941 uint32 reqitemcount = pQuest->ReqItemCount[i];
13942 if( reqitemcount != 0 )
13944 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i], true);
13946 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13947 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13953 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13955 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13956 if ( GetQuestSlotQuestId(i) == quest_id )
13957 return i;
13959 return MAX_QUEST_LOG_SIZE;
13962 void Player::AreaExploredOrEventHappens( uint32 questId )
13964 if( questId )
13966 uint16 log_slot = FindQuestSlot( questId );
13967 if( log_slot < MAX_QUEST_LOG_SIZE)
13969 QuestStatusData& q_status = mQuestStatus[questId];
13971 if(!q_status.m_explored)
13973 q_status.m_explored = true;
13974 if (q_status.uState != QUEST_NEW)
13975 q_status.uState = QUEST_CHANGED;
13978 if( CanCompleteQuest( questId ) )
13979 CompleteQuest( questId );
13983 //not used in mangosd, function for external script library
13984 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13986 if( Group *pGroup = GetGroup() )
13988 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13990 Player *pGroupGuy = itr->getSource();
13992 // for any leave or dead (with not released body) group member at appropriate distance
13993 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13994 pGroupGuy->AreaExploredOrEventHappens(questId);
13997 else
13998 AreaExploredOrEventHappens(questId);
14001 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
14003 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14005 uint32 questid = GetQuestSlotQuestId(i);
14006 if ( questid == 0 )
14007 continue;
14009 QuestStatusData& q_status = mQuestStatus[questid];
14011 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
14012 continue;
14014 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14015 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
14016 continue;
14018 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
14020 uint32 reqitem = qInfo->ReqItemId[j];
14021 if ( reqitem == entry )
14023 uint32 reqitemcount = qInfo->ReqItemCount[j];
14024 uint32 curitemcount = q_status.m_itemcount[j];
14025 if ( curitemcount < reqitemcount )
14027 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
14028 q_status.m_itemcount[j] += additemcount;
14029 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14031 SendQuestUpdateAddItem( qInfo, j, additemcount );
14033 if ( CanCompleteQuest( questid ) )
14034 CompleteQuest( questid );
14035 return;
14039 UpdateForQuestWorldObjects();
14042 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
14044 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14046 uint32 questid = GetQuestSlotQuestId(i);
14047 if(!questid)
14048 continue;
14049 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14050 if ( !qInfo )
14051 continue;
14052 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
14053 continue;
14055 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
14057 uint32 reqitem = qInfo->ReqItemId[j];
14058 if ( reqitem == entry )
14060 QuestStatusData& q_status = mQuestStatus[questid];
14062 uint32 reqitemcount = qInfo->ReqItemCount[j];
14063 uint32 curitemcount;
14064 if( q_status.m_status != QUEST_STATUS_COMPLETE )
14065 curitemcount = q_status.m_itemcount[j];
14066 else
14067 curitemcount = GetItemCount(entry, true);
14068 if ( curitemcount < reqitemcount + count )
14070 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
14071 q_status.m_itemcount[j] = curitemcount - remitemcount;
14072 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14074 IncompleteQuest( questid );
14076 return;
14080 UpdateForQuestWorldObjects();
14083 void Player::KilledMonster( CreatureInfo const* cInfo, uint64 guid )
14085 if(cInfo->Entry)
14086 KilledMonsterCredit(cInfo->Entry,guid);
14088 for(int i = 0; i < MAX_KILL_CREDIT; ++i)
14089 if(cInfo->KillCredit[i])
14090 KilledMonsterCredit(cInfo->KillCredit[i],guid);
14093 void Player::KilledMonsterCredit( uint32 entry, uint64 guid )
14095 uint32 addkillcount = 1;
14096 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
14097 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14099 uint32 questid = GetQuestSlotQuestId(i);
14100 if(!questid)
14101 continue;
14103 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14104 if( !qInfo )
14105 continue;
14106 // just if !ingroup || !noraidgroup || raidgroup
14107 QuestStatusData& q_status = mQuestStatus[questid];
14108 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
14110 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
14112 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14114 // skip GO activate objective or none
14115 if(qInfo->ReqCreatureOrGOId[j] <=0)
14116 continue;
14118 // skip Cast at creature objective
14119 if(qInfo->ReqSpell[j] !=0 )
14120 continue;
14122 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
14124 if ( reqkill == entry )
14126 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
14127 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
14128 if ( curkillcount < reqkillcount )
14130 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
14131 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14133 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
14135 if ( CanCompleteQuest( questid ) )
14136 CompleteQuest( questid );
14138 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14139 continue;
14147 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
14149 bool isCreature = IS_CREATURE_GUID(guid);
14151 uint32 addCastCount = 1;
14152 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
14154 uint32 questid = GetQuestSlotQuestId(i);
14155 if(!questid)
14156 continue;
14158 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14159 if ( !qInfo )
14160 continue;
14162 QuestStatusData& q_status = mQuestStatus[questid];
14164 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14166 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
14168 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14170 // skip kill creature objective (0) or wrong spell casts
14171 if(qInfo->ReqSpell[j] != spell_id )
14172 continue;
14174 uint32 reqTarget = 0;
14176 if(isCreature)
14178 // creature activate objectives
14179 if(qInfo->ReqCreatureOrGOId[j] > 0)
14180 // checked at quest_template loading
14181 reqTarget = qInfo->ReqCreatureOrGOId[j];
14183 else
14185 // GO activate objective
14186 if(qInfo->ReqCreatureOrGOId[j] < 0)
14187 // checked at quest_template loading
14188 reqTarget = - qInfo->ReqCreatureOrGOId[j];
14191 // other not this creature/GO related objectives
14192 if( reqTarget != entry )
14193 continue;
14195 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
14196 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
14197 if ( curCastCount < reqCastCount )
14199 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
14200 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14202 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
14205 if ( CanCompleteQuest( questid ) )
14206 CompleteQuest( questid );
14208 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14209 break;
14216 void Player::TalkedToCreature( uint32 entry, uint64 guid )
14218 uint32 addTalkCount = 1;
14219 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14221 uint32 questid = GetQuestSlotQuestId(i);
14222 if(!questid)
14223 continue;
14225 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14226 if ( !qInfo )
14227 continue;
14229 QuestStatusData& q_status = mQuestStatus[questid];
14231 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14233 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
14235 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14237 // skip spell casts and Gameobject objectives
14238 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
14239 continue;
14241 uint32 reqTarget = 0;
14243 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
14244 // checked at quest_template loading
14245 reqTarget = qInfo->ReqCreatureOrGOId[j];
14246 else
14247 continue;
14249 if ( reqTarget == entry )
14251 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
14252 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
14253 if ( curTalkCount < reqTalkCount )
14255 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
14256 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14258 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
14260 if ( CanCompleteQuest( questid ) )
14261 CompleteQuest( questid );
14263 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14264 continue;
14272 void Player::MoneyChanged( uint32 count )
14274 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14276 uint32 questid = GetQuestSlotQuestId(i);
14277 if (!questid)
14278 continue;
14280 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14281 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
14283 QuestStatusData& q_status = mQuestStatus[questid];
14285 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14287 if(int32(count) >= -qInfo->GetRewOrReqMoney())
14289 if ( CanCompleteQuest( questid ) )
14290 CompleteQuest( questid );
14293 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14295 if(int32(count) < -qInfo->GetRewOrReqMoney())
14296 IncompleteQuest( questid );
14302 void Player::ReputationChanged(FactionEntry const* factionEntry )
14304 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14306 if(uint32 questid = GetQuestSlotQuestId(i))
14308 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid))
14310 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
14312 QuestStatusData& q_status = mQuestStatus[questid];
14313 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14315 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
14316 if ( CanCompleteQuest( questid ) )
14317 CompleteQuest( questid );
14319 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14321 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
14322 IncompleteQuest( questid );
14330 bool Player::HasQuestForItem( uint32 itemid ) const
14332 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14334 uint32 questid = GetQuestSlotQuestId(i);
14335 if ( questid == 0 )
14336 continue;
14338 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
14339 if(qs_itr == mQuestStatus.end())
14340 continue;
14342 QuestStatusData const& q_status = qs_itr->second;
14344 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
14346 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
14347 if(!qinfo)
14348 continue;
14350 // hide quest if player is in raid-group and quest is no raid quest
14351 if (GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID
14352 && !InBattleGround())
14353 continue;
14355 // There should be no mixed ReqItem/ReqSource drop
14356 // This part for ReqItem drop
14357 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
14359 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
14360 return true;
14362 // This part - for ReqSource
14363 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
14365 // examined item is a source item
14366 if (qinfo->ReqSourceId[j] == itemid)
14368 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(itemid);
14370 // 'unique' item
14371 if (pProto->MaxCount && (int32)GetItemCount(itemid,true) < pProto->MaxCount)
14372 return true;
14374 // allows custom amount drop when not 0
14375 if (qinfo->ReqSourceCount[j])
14377 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
14378 return true;
14379 } else if ((int32)GetItemCount(itemid,true) < pProto->Stackable)
14380 return true;
14385 return false;
14388 void Player::SendQuestComplete( uint32 quest_id )
14390 if( quest_id )
14392 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
14393 data << uint32(quest_id);
14394 GetSession()->SendPacket( &data );
14395 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
14399 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
14401 uint32 questid = pQuest->GetQuestId();
14402 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
14403 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
14404 data << uint32(questid);
14406 if ( getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
14408 data << uint32(XP);
14409 data << uint32(pQuest->GetRewOrReqMoney());
14411 else
14413 data << uint32(0);
14414 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY)));
14417 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorAddition()));
14418 data << uint32(pQuest->GetBonusTalents()); // bonus talents
14419 data << uint32(0);
14420 GetSession()->SendPacket( &data );
14422 if (pQuest->GetQuestCompleteScript() != 0)
14423 GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
14426 void Player::SendQuestFailed( uint32 quest_id )
14428 if( quest_id )
14430 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
14431 data << uint32(quest_id);
14432 data << uint32(0); // failed reason (4 for inventory is full)
14433 GetSession()->SendPacket( &data );
14434 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
14438 void Player::SendQuestTimerFailed( uint32 quest_id )
14440 if( quest_id )
14442 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
14443 data << uint32(quest_id);
14444 GetSession()->SendPacket( &data );
14445 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
14449 void Player::SendCanTakeQuestResponse( uint32 msg )
14451 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
14452 data << uint32(msg);
14453 GetSession()->SendPacket( &data );
14454 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
14457 void Player::SendQuestConfirmAccept(const Quest* pQuest, Player* pReceiver)
14459 if (pReceiver)
14461 std::string strTitle = pQuest->GetTitle();
14463 int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
14465 if (loc_idx >= 0)
14467 if (const QuestLocale* pLocale = sObjectMgr.GetQuestLocale(pQuest->GetQuestId()))
14469 if ((int32)pLocale->Title.size() > loc_idx && !pLocale->Title[loc_idx].empty())
14470 strTitle = pLocale->Title[loc_idx];
14474 WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8));
14475 data << uint32(pQuest->GetQuestId());
14476 data << strTitle;
14477 data << uint64(GetGUID());
14478 pReceiver->GetSession()->SendPacket(&data);
14480 sLog.outDebug("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
14484 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
14486 if( pPlayer )
14488 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
14489 data << uint64(pPlayer->GetGUID());
14490 data << uint8(msg); // valid values: 0-8
14491 GetSession()->SendPacket( &data );
14492 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
14496 void Player::SendQuestUpdateAddItem( Quest const* /*pQuest*/, uint32 /*item_idx*/, uint32 /*count*/ )
14498 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
14499 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
14500 //data << pQuest->ReqItemId[item_idx];
14501 //data << count;
14502 GetSession()->SendPacket( &data );
14505 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
14507 assert(old_count + add_count < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
14509 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
14510 if (entry < 0)
14511 // client expected gameobject template id in form (id|0x80000000)
14512 entry = (-entry) | 0x80000000;
14514 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
14515 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
14516 data << uint32(pQuest->GetQuestId());
14517 data << uint32(entry);
14518 data << uint32(old_count + add_count);
14519 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
14520 data << uint64(guid);
14521 GetSession()->SendPacket(&data);
14523 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
14524 if( log_slot < MAX_QUEST_LOG_SIZE)
14525 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
14528 /*********************************************************/
14529 /*** LOAD SYSTEM ***/
14530 /*********************************************************/
14532 void Player::_LoadDeclinedNames(QueryResult* result)
14534 if(!result)
14535 return;
14537 if(m_declinedname)
14538 delete m_declinedname;
14540 m_declinedname = new DeclinedName;
14541 Field *fields = result->Fetch();
14542 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
14543 m_declinedname->name[i] = fields[i].GetCppString();
14545 delete result;
14548 void Player::_LoadArenaTeamInfo(QueryResult *result)
14550 // arenateamid, played_week, played_season, personal_rating
14551 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
14552 if (!result)
14553 return;
14557 Field *fields = result->Fetch();
14559 uint32 arenateamid = fields[0].GetUInt32();
14560 uint32 played_week = fields[1].GetUInt32();
14561 uint32 played_season = fields[2].GetUInt32();
14562 uint32 wons_season = fields[3].GetUInt32();
14563 uint32 personal_rating = fields[4].GetUInt32();
14565 ArenaTeam* aTeam = sObjectMgr.GetArenaTeamById(arenateamid);
14566 if(!aTeam)
14568 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid);
14569 continue;
14571 uint8 arenaSlot = aTeam->GetSlot();
14573 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_ID, arenateamid);
14574 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_TYPE, aTeam->GetType());
14575 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_MEMBER, (aTeam->GetCaptain() == GetGUID()) ? 0 : 1);
14576 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_WEEK, played_week);
14577 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_SEASON, played_season);
14578 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_WINS_SEASON, wons_season);
14579 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_PERSONAL_RATING, personal_rating);
14581 } while (result->NextRow());
14582 delete result;
14585 void Player::_LoadEquipmentSets(QueryResult *result)
14587 // 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));
14588 if (!result)
14589 return;
14591 uint32 count = 0;
14594 Field *fields = result->Fetch();
14596 EquipmentSet eqSet;
14598 eqSet.Guid = fields[0].GetUInt64();
14599 uint32 index = fields[1].GetUInt32();
14600 eqSet.Name = fields[2].GetCppString();
14601 eqSet.IconName = fields[3].GetCppString();
14602 eqSet.state = EQUIPMENT_SET_UNCHANGED;
14604 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
14605 eqSet.Items[i] = fields[4+i].GetUInt32();
14607 m_EquipmentSets[index] = eqSet;
14609 ++count;
14611 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
14612 break;
14613 } while (result->NextRow());
14614 delete result;
14617 void Player::_LoadBGData(QueryResult* result)
14619 if (!result)
14620 return;
14622 // Expecting only one row
14623 Field *fields = result->Fetch();
14624 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
14625 m_bgData.bgInstanceID = fields[0].GetUInt32();
14626 m_bgData.bgTeam = fields[1].GetUInt32();
14627 m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
14628 fields[2].GetFloat(), // X
14629 fields[3].GetFloat(), // Y
14630 fields[4].GetFloat(), // Z
14631 fields[5].GetFloat()); // Orientation
14632 m_bgData.taxiPath[0] = fields[7].GetUInt32();
14633 m_bgData.taxiPath[1] = fields[8].GetUInt32();
14634 m_bgData.mountSpell = fields[9].GetUInt32();
14636 delete result;
14639 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
14641 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
14642 if(!result)
14643 return false;
14645 Field *fields = result->Fetch();
14647 x = fields[0].GetFloat();
14648 y = fields[1].GetFloat();
14649 z = fields[2].GetFloat();
14650 o = fields[3].GetFloat();
14651 mapid = fields[4].GetUInt32();
14652 in_flight = !fields[5].GetCppString().empty();
14654 delete result;
14655 return true;
14658 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
14660 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
14661 if( !result )
14662 return false;
14664 Field *fields = result->Fetch();
14666 data = StrSplit(fields[0].GetCppString(), " ");
14668 delete result;
14670 return true;
14673 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
14675 if(index >= data.size())
14676 return 0;
14678 return (uint32)atoi(data[index].c_str());
14681 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
14683 float result;
14684 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
14685 memcpy(&result, &temp, sizeof(result));
14687 return result;
14690 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14692 Tokens data;
14693 if(!LoadValuesArrayFromDB(data,guid))
14694 return 0;
14696 return GetUInt32ValueFromArray(data,index);
14699 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14701 float result;
14702 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14703 memcpy(&result, &temp, sizeof(result));
14705 return result;
14708 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14710 // 0 1 2 3 4 5 6 7 8 9 10 11 12
14711 //SELECT guid, account, data, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags,"
14712 // 13 14 15 16 17 18 19 20 21 22 23 24 25
14713 //"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost,"
14714 // 26 27 28 29 30 31 32 33 34 35 36 37 38 39
14715 //"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,"
14716 // 40 41 42 43 44 45 46 47 48 49 50
14717 //"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk,"
14718 // 51 52 53 54 55 56 57 58 59 60
14719 //"health, power1, power2, power3, power4, power5, power6, power7, specCount, activeSpec FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid));
14720 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14722 if(!result)
14724 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14725 return false;
14728 Field *fields = result->Fetch();
14730 uint32 dbAccountId = fields[1].GetUInt32();
14732 // check if the character's account in the db and the logged in account match.
14733 // player should be able to load/delete character only with correct account!
14734 if( dbAccountId != GetSession()->GetAccountId() )
14736 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14737 delete result;
14738 return false;
14741 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14743 m_name = fields[3].GetCppString();
14745 // check name limitations
14746 if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
14747 (GetSession()->GetSecurity() == SEC_PLAYER && sObjectMgr.IsReservedName(m_name)))
14749 delete result;
14750 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14751 return false;
14754 if(!LoadValues( fields[2].GetString()))
14756 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
14757 delete result;
14758 return false;
14761 // overwrite possible wrong/corrupted guid
14762 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14764 // overwrite some data fields
14765 uint32 bytes0 = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0xFF000000;
14766 bytes0 |= fields[4].GetUInt8(); // race
14767 bytes0 |= fields[5].GetUInt8() << 8; // class
14768 bytes0 |= fields[6].GetUInt8() << 16; // gender
14769 SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
14771 SetUInt32Value(UNIT_FIELD_LEVEL, fields[7].GetUInt8());
14772 SetUInt32Value(PLAYER_XP, fields[8].GetUInt32());
14774 uint32 money = fields[9].GetUInt32();
14775 if(money > MAX_MONEY_AMOUNT)
14776 money = MAX_MONEY_AMOUNT;
14777 SetMoney(money);
14779 SetUInt32Value(PLAYER_BYTES, fields[10].GetUInt32());
14780 SetUInt32Value(PLAYER_BYTES_2, fields[11].GetUInt32());
14781 SetUInt32Value(PLAYER_BYTES_3, (fields[50].GetUInt16() & 0xFFFE) | fields[6].GetUInt8());
14782 SetUInt32Value(PLAYER_FLAGS, fields[12].GetUInt32());
14783 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[49].GetInt32());
14785 SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES, fields[48].GetUInt64());
14788 InitDisplayIds();
14790 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14791 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14793 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
14794 SetVisibleItemSlot(slot, NULL);
14796 if (m_items[slot])
14798 delete m_items[slot];
14799 m_items[slot] = NULL;
14803 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14804 outDebugValues();
14806 //Need to call it to initialize m_team (m_team can be calculated from race)
14807 //Other way is to saves m_team into characters table.
14808 setFactionForRace(getRace());
14809 SetCharm(NULL);
14811 // load home bind and check in same time class/race pair, it used later for restore broken positions
14812 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14814 delete result;
14815 return false;
14818 InitPrimaryProfessions(); // to max set before any spell loaded
14820 // init saved position, and fix it later if problematic
14821 uint32 transGUID = fields[31].GetUInt32();
14822 Relocate(fields[13].GetFloat(),fields[14].GetFloat(),fields[15].GetFloat(),fields[17].GetFloat());
14823 SetLocationMapId(fields[16].GetUInt32());
14825 uint32 difficulty = fields[39].GetUInt32();
14826 if(difficulty >= MAX_DUNGEON_DIFFICULTY)
14827 difficulty = DUNGEON_DIFFICULTY_NORMAL;
14828 SetDungeonDifficulty(Difficulty(difficulty)); // may be changed in _LoadGroup
14830 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14832 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14834 uint32 arena_currency = fields[40].GetUInt32();
14835 if (arena_currency > sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS))
14836 arena_currency = sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS);
14838 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14840 // check arena teams integrity
14841 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14843 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14844 if(!arena_team_id)
14845 continue;
14847 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(arena_team_id))
14848 if(at->HaveMember(GetGUID()))
14849 continue;
14851 // arena team not exist or not member, cleanup fields
14852 for(int j = 0; j < ARENA_TEAM_END; ++j)
14853 SetArenaTeamInfoField(arena_slot, ArenaTeamInfoType(j), 0);
14856 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, fields[41].GetUInt32());
14857 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, fields[42].GetUInt32());
14858 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, fields[43].GetUInt32());
14859 SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, fields[44].GetUInt32());
14860 SetUInt16Value(PLAYER_FIELD_KILLS, 0, fields[45].GetUInt16());
14861 SetUInt16Value(PLAYER_FIELD_KILLS, 1, fields[46].GetUInt16());
14863 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14865 if(!IsPositionValid())
14867 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());
14868 RelocateToHomebind();
14870 transGUID = 0;
14872 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
14875 _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
14877 if(m_bgData.bgInstanceID) //saved in BattleGround
14879 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
14881 bool player_at_bg = currentBg && currentBg->IsPlayerInBattleGround(GetGUID());
14883 if(player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE)
14885 BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14886 AddBattleGroundQueueId(bgQueueTypeId);
14888 m_bgData.bgTypeID = currentBg->GetTypeID();
14890 //join player to battleground group
14891 currentBg->EventPlayerLoggedIn(this, GetGUID());
14892 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData.bgTeam);
14894 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14896 else
14898 // leave bg
14899 if (player_at_bg)
14900 currentBg->RemovePlayerAtLeave(GetGUID(), false, true);
14902 // move to bg enter point
14903 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14904 SetLocationMapId(_loc.mapid);
14905 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14907 // We are not in BG anymore
14908 m_bgData.bgInstanceID = 0;
14911 else
14913 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14914 // if server restart after player save in BG or area
14915 // player can have current coordinates in to BG/Arena map, fix this
14916 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14918 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14919 SetLocationMapId(_loc.mapid);
14920 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14924 if (transGUID != 0)
14926 m_movementInfo.SetTransportData(transGUID, fields[27].GetFloat(), fields[28].GetFloat(), fields[29].GetFloat(), fields[30].GetFloat(), 0, -1);
14928 if( !MaNGOS::IsValidMapCoord(
14929 GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
14930 GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o) ||
14931 // transport size limited
14932 m_movementInfo.GetTransportPos()->x > 50 || m_movementInfo.GetTransportPos()->y > 50 || m_movementInfo.GetTransportPos()->z > 50 )
14934 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14935 guid, GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
14936 GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o);
14938 RelocateToHomebind();
14940 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
14942 transGUID = 0;
14946 if (transGUID != 0)
14948 for (MapManager::TransportSet::const_iterator iter = sMapMgr.m_Transports.begin(); iter != sMapMgr.m_Transports.end(); ++iter)
14950 if( (*iter)->GetGUIDLow() == transGUID)
14952 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14953 // client without expansion support
14954 if(GetSession()->Expansion() < transMapEntry->Expansion())
14956 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14957 break;
14960 m_transport = *iter;
14961 m_transport->AddPassenger(this);
14962 SetLocationMapId(m_transport->GetMapId());
14963 break;
14967 if(!m_transport)
14969 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14970 guid,transGUID);
14972 RelocateToHomebind();
14974 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
14976 transGUID = 0;
14979 else // not transport case
14981 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14982 // client without expansion support
14983 if(GetSession()->Expansion() < mapEntry->Expansion())
14985 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14986 RelocateToHomebind();
14990 // NOW player must have valid map
14991 // load the player's map here if it's not already loaded
14992 SetMap(sMapMgr.CreateMap(GetMapId(), this));
14994 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14995 if(GetInstanceId() && !sInstanceSaveMgr.GetInstanceSave(GetInstanceId()))
14997 AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(GetMapId());
14998 if(at)
14999 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
15000 else
15001 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());
15004 SaveRecallPosition();
15006 time_t now = time(NULL);
15007 time_t logoutTime = time_t(fields[23].GetUInt64());
15009 // since last logout (in seconds)
15010 uint32 time_diff = uint32(now - logoutTime);
15012 // set value, including drunk invisibility detection
15013 // calculate sobering. after 15 minutes logged out, the player will be sober again
15014 float soberFactor;
15015 if(time_diff > 15*MINUTE)
15016 soberFactor = 0;
15017 else
15018 soberFactor = 1-time_diff/(15.0f*MINUTE);
15019 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
15020 SetDrunkValue(newDrunkenValue);
15022 m_rest_bonus = fields[22].GetFloat();
15023 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
15024 float bubble0 = 0.031f;
15025 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
15026 float bubble1 = 0.125f;
15028 if(time_diff > 0)
15030 float bubble = fields[24].GetUInt32() > 0
15031 ? bubble1*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
15032 : bubble0*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_WILDERNESS);
15034 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
15037 m_cinematic = fields[19].GetUInt32();
15038 m_Played_time[PLAYED_TIME_TOTAL]= fields[20].GetUInt32();
15039 m_Played_time[PLAYED_TIME_LEVEL]= fields[21].GetUInt32();
15041 m_resetTalentsCost = fields[25].GetUInt32();
15042 m_resetTalentsTime = time_t(fields[26].GetUInt64());
15044 // reserve some flags
15045 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
15047 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
15048 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
15050 m_taxi.LoadTaxiMask( fields[18].GetString() ); // must be before InitTaxiNodesForLevel
15052 uint32 extraflags = fields[32].GetUInt32();
15054 m_stableSlots = fields[33].GetUInt32();
15055 if(m_stableSlots > MAX_PET_STABLES)
15057 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
15058 m_stableSlots = MAX_PET_STABLES;
15061 m_atLoginFlags = fields[34].GetUInt32();
15063 // Honor system
15064 // Update Honor kills data
15065 m_lastHonorUpdateTime = logoutTime;
15066 UpdateHonorFields();
15068 m_deathExpireTime = (time_t)fields[37].GetUInt64();
15069 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
15070 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
15072 std::string taxi_nodes = fields[38].GetCppString();
15074 // clear channel spell data (if saved at channel spell casting)
15075 SetChannelObjectGUID(0);
15076 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
15078 // clear charm/summon related fields
15079 SetCharm(NULL);
15080 SetPet(NULL);
15081 SetTargetGUID(0);
15082 SetChannelObjectGUID(0);
15083 SetCharmerGUID(0);
15084 SetOwnerGUID(0);
15085 SetCreatorGUID(0);
15087 // reset some aura modifiers before aura apply
15088 SetFarSightGUID(0);
15089 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
15090 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
15092 // cleanup aura list explicitly before skill load wher some spells can be applied
15093 RemoveAllAuras();
15095 // make sure the unit is considered out of combat for proper loading
15096 ClearInCombat();
15098 // make sure the unit is considered not in duel for proper loading
15099 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
15100 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
15102 // reset stats before loading any modifiers
15103 InitStatsForLevel();
15104 InitGlyphsForLevel();
15105 InitTaxiNodesForLevel();
15106 InitRunes();
15108 // load skills after InitStatsForLevel because it triggering aura apply also
15109 _LoadSkills(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS));
15111 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
15113 // Mail
15114 _LoadMail();
15115 UpdateNextMailTimeAndUnreads();
15117 m_specsCount = fields[59].GetUInt8();
15118 m_activeSpec = fields[60].GetUInt8();
15120 _LoadGlyphs(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGLYPHS));
15122 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
15123 ApplyGlyphs(true);
15125 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
15126 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
15127 m_deathState = DEAD;
15129 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
15131 // after spell load, learn rewarded spell if need also
15132 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
15133 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
15135 // after spell and quest load
15136 InitTalentForLevel();
15137 learnDefaultSpells();
15139 // must be before inventory (some items required reputation check)
15140 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
15142 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
15144 // update items with duration and realtime
15145 UpdateItemDuration(time_diff, true);
15147 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
15149 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
15151 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
15152 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
15153 uint32 curTitle = fields[47].GetUInt32();
15154 if (curTitle && !HasTitle(curTitle))
15155 curTitle = 0;
15157 SetUInt32Value(PLAYER_CHOSEN_TITLE, curTitle);
15159 // Not finish taxi flight path
15160 if(m_bgData.HasTaxiPath())
15162 m_taxi.ClearTaxiDestinations();
15163 for (int i = 0; i < 2; ++i)
15164 m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
15166 else if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
15168 // problems with taxi path loading
15169 TaxiNodesEntry const* nodeEntry = NULL;
15170 if(uint32 node_id = m_taxi.GetTaxiSource())
15171 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
15173 if(!nodeEntry) // don't know taxi start node, to homebind
15175 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
15176 RelocateToHomebind();
15178 else // have start node, to it
15180 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
15181 SetLocationMapId(nodeEntry->map_id);
15182 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
15185 //we can be relocated from taxi and still have an outdated Map pointer!
15186 //so we need to get a new Map pointer!
15187 SetMap(sMapMgr.CreateMap(GetMapId(), this));
15188 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
15190 m_taxi.ClearTaxiDestinations();
15193 if(uint32 node_id = m_taxi.GetTaxiSource())
15195 // save source node as recall coord to prevent recall and fall from sky
15196 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
15197 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
15198 m_recallMap = nodeEntry->map_id;
15199 m_recallX = nodeEntry->x;
15200 m_recallY = nodeEntry->y;
15201 m_recallZ = nodeEntry->z;
15203 // flight will started later
15206 // has to be called after last Relocate() in Player::LoadFromDB
15207 SetFallInformation(0, GetPositionZ());
15209 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
15211 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
15212 // Do now before stats re-calculation cleanup for ghost state unexpected auras
15213 if(!isAlive())
15214 RemoveAllAurasOnDeath();
15216 //apply all stat bonuses from items and auras
15217 SetCanModifyStats(true);
15218 UpdateAllStats();
15220 // restore remembered power/health values (but not more max values)
15221 uint32 savedhealth = fields[51].GetUInt32();
15222 SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth);
15223 for(uint32 i = 0; i < MAX_POWERS; ++i)
15225 uint32 savedpower = fields[52+i].GetUInt32();
15226 SetPower(Powers(i),savedpower > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedpower);
15229 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
15230 outDebugValues();
15232 // all fields read
15233 delete result;
15235 // GM state
15236 if(GetSession()->GetSecurity() > SEC_PLAYER)
15238 switch(sWorld.getConfig(CONFIG_UINT32_GM_LOGIN_STATE))
15240 default:
15241 case 0: break; // disable
15242 case 1: SetGameMaster(true); break; // enable
15243 case 2: // save state
15244 if(extraflags & PLAYER_EXTRA_GM_ON)
15245 SetGameMaster(true);
15246 break;
15249 switch(sWorld.getConfig(CONFIG_UINT32_GM_VISIBLE_STATE))
15251 default:
15252 case 0: SetGMVisible(false); break; // invisible
15253 case 1: break; // visible
15254 case 2: // save state
15255 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
15256 SetGMVisible(false);
15257 break;
15260 switch(sWorld.getConfig(CONFIG_UINT32_GM_ACCEPT_TICKETS))
15262 default:
15263 case 0: break; // disable
15264 case 1: SetAcceptTicket(true); break; // enable
15265 case 2: // save state
15266 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
15267 SetAcceptTicket(true);
15268 break;
15271 switch(sWorld.getConfig(CONFIG_UINT32_GM_CHAT))
15273 default:
15274 case 0: break; // disable
15275 case 1: SetGMChat(true); break; // enable
15276 case 2: // save state
15277 if(extraflags & PLAYER_EXTRA_GM_CHAT)
15278 SetGMChat(true);
15279 break;
15282 switch(sWorld.getConfig(CONFIG_UINT32_GM_WISPERING_TO))
15284 default:
15285 case 0: break; // disable
15286 case 1: SetAcceptWhispers(true); break; // enable
15287 case 2: // save state
15288 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
15289 SetAcceptWhispers(true);
15290 break;
15294 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
15296 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
15297 m_achievementMgr.CheckAllAchievementCriteria();
15299 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
15301 return true;
15304 bool Player::isAllowedToLoot(Creature* creature)
15306 if(Player* recipient = creature->GetLootRecipient())
15308 if (recipient == this)
15309 return true;
15310 if( Group* otherGroup = recipient->GetGroup())
15312 Group* thisGroup = GetGroup();
15313 if(!thisGroup)
15314 return false;
15315 return thisGroup == otherGroup;
15317 return false;
15319 else
15320 // prevent other players from looting if the recipient got disconnected
15321 return !creature->hasLootRecipient();
15324 void Player::_LoadActions(QueryResult *result)
15326 for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
15327 m_actionButtons[i].clear();
15329 //QueryResult *result = CharacterDatabase.PQuery("SELECT spec, button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
15331 if(result)
15335 Field *fields = result->Fetch();
15337 uint8 spec = fields[0].GetUInt8();
15338 uint8 button = fields[1].GetUInt8();
15339 uint32 action = fields[2].GetUInt32();
15340 uint8 type = fields[3].GetUInt8();
15342 if(ActionButton* ab = addActionButton(spec, button, action, type))
15343 ab->uState = ACTIONBUTTON_UNCHANGED;
15344 else
15346 sLog.outError( " ...at loading, and will deleted in DB also");
15348 // Will deleted in DB at next save (it can create data until save but marked as deleted)
15349 m_actionButtons[spec][button].uState = ACTIONBUTTON_DELETED;
15352 while( result->NextRow() );
15354 delete result;
15358 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
15360 //RemoveAllAuras(); -- some spells casted before aura load, for example in LoadSkills, aura list explcitly cleaned early
15362 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15364 if(result)
15368 Field *fields = result->Fetch();
15369 uint64 caster_guid = fields[0].GetUInt64();
15370 uint32 spellid = fields[1].GetUInt32();
15371 SpellEffectIndex effindex = SpellEffectIndex(fields[2].GetUInt32());
15372 uint32 stackcount = fields[3].GetUInt32();
15373 int32 damage = fields[4].GetInt32();
15374 int32 maxduration = fields[5].GetInt32();
15375 int32 remaintime = fields[6].GetInt32();
15376 int32 remaincharges = fields[7].GetInt32();
15378 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
15379 if (!spellproto)
15381 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
15382 continue;
15385 if (effindex >= MAX_EFFECT_INDEX)
15387 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
15388 continue;
15391 // negative effects should continue counting down after logout
15392 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
15394 if (remaintime/IN_MILISECONDS <= int32(timediff))
15395 continue;
15397 remaintime -= timediff*IN_MILISECONDS;
15400 // prevent wrong values of remaincharges
15401 if (spellproto->procCharges)
15403 if (remaincharges <= 0 || remaincharges > (int32)spellproto->procCharges)
15404 remaincharges = spellproto->procCharges;
15406 else
15407 remaincharges = 0;
15410 for(uint32 i = 0; i < stackcount; ++i)
15412 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
15413 if (!damage)
15414 damage = aura->GetModifier()->m_amount;
15416 // reset stolen single target auras
15417 if (caster_guid != GetGUID() && aura->IsSingleTarget())
15418 aura->SetIsSingleTarget(false);
15420 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
15421 AddAura(aura);
15422 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
15425 while( result->NextRow() );
15427 delete result;
15430 if(getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
15431 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
15434 void Player::_LoadGlyphs(QueryResult *result)
15436 if(!result)
15437 return;
15439 // 0 1 2
15440 // "SELECT spec, slot, glyph FROM character_glyphs WHERE guid='%u'"
15444 Field *fields = result->Fetch();
15445 uint8 spec = fields[0].GetUInt8();
15446 uint8 slot = fields[1].GetUInt8();
15447 uint32 glyph = fields[2].GetUInt32();
15449 GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph);
15450 if(!gp)
15452 sLog.outError("Player %s has not existing glyph entry %u on index %u, spec %u", m_name.c_str(), glyph, slot, spec);
15453 continue;
15456 GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(slot));
15457 if (!gs)
15459 sLog.outError("Player %s has not existing glyph slot entry %u on index %u, spec %u", m_name.c_str(), GetGlyphSlot(slot), slot, spec);
15460 continue;
15463 if(gp->TypeFlags != gs->TypeFlags)
15465 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
15466 continue;
15469 m_glyphs[spec][slot].id = glyph;
15471 } while( result->NextRow() );
15473 delete result;
15478 void Player::LoadCorpse()
15480 if( isAlive() )
15482 sObjectAccessor.ConvertCorpseForPlayer(GetGUID());
15484 else
15486 if(Corpse *corpse = GetCorpse())
15488 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
15490 else
15492 //Prevent Dead Player login without corpse
15493 ResurrectPlayer(0.5f);
15498 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
15500 //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());
15501 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
15502 //NOTE: the "order by `bag`" is important because it makes sure
15503 //the bagMap is filled before items in the bags are loaded
15504 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
15505 //expected to be equipped before offhand items (TODO: fixme)
15507 uint32 zone = GetZoneId();
15509 if (result)
15511 std::list<Item*> problematicItems;
15513 // prevent items from being added to the queue when stored
15514 m_itemUpdateQueueBlocked = true;
15517 Field *fields = result->Fetch();
15518 uint32 bag_guid = fields[1].GetUInt32();
15519 uint8 slot = fields[2].GetUInt8();
15520 uint32 item_guid = fields[3].GetUInt32();
15521 uint32 item_id = fields[4].GetUInt32();
15523 ItemPrototype const * proto = ObjectMgr::GetItemPrototype(item_id);
15525 if(!proto)
15527 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15528 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
15529 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
15530 continue;
15533 Item *item = NewItemOrBag(proto);
15535 if(!item->LoadFromDB(item_guid, GetGUID(), result))
15537 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
15538 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15539 item->FSetState(ITEM_REMOVED);
15540 item->SaveToDB(); // it also deletes item object !
15541 continue;
15544 // not allow have in alive state item limited to another map/zone
15545 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
15547 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15548 item->FSetState(ITEM_REMOVED);
15549 item->SaveToDB(); // it also deletes item object !
15550 continue;
15553 // "Conjured items disappear if you are logged out for more than 15 minutes"
15554 if (timediff > 15*MINUTE && item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED))
15556 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15557 item->FSetState(ITEM_REMOVED);
15558 item->SaveToDB(); // it also deletes item object !
15559 continue;
15562 bool success = true;
15564 // the item/bag is not in a bag
15565 if (!bag_guid)
15567 item->SetContainer( NULL );
15568 item->SetSlot(slot);
15570 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
15572 ItemPosCountVec dest;
15573 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
15574 item = StoreItem(dest, item, true);
15575 else
15576 success = false;
15578 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
15580 uint16 dest;
15581 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
15582 QuickEquipItem(dest, item);
15583 else
15584 success = false;
15586 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
15588 ItemPosCountVec dest;
15589 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
15590 item = BankItem(dest, item, true);
15591 else
15592 success = false;
15595 if(success)
15597 // store bags that may contain items in them
15598 if(item->IsBag() && IsBagPos(item->GetPos()))
15599 bagMap[item_guid] = (Bag*)item;
15602 // the item/bag in a bag
15603 else
15605 item->SetSlot(NULL_SLOT);
15606 // the item is in a bag, find the bag
15607 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
15608 if(itr != bagMap.end() && slot < itr->second->GetBagSize())
15610 ItemPosCountVec dest;
15611 if( CanStoreItem( itr->second->GetSlot(), slot, dest, item, false ) == EQUIP_ERR_OK )
15612 item = StoreItem(dest, item, true);
15613 else
15614 success = false;
15616 else
15617 success = false;
15620 // item's state may have changed after stored
15621 if (success)
15623 item->SetState(ITEM_UNCHANGED, this);
15625 // recharged mana gem
15626 if (timediff > 15*MINUTE && proto->ItemLimitCategory ==ITEM_LIMIT_CATEGORY_MANA_GEM)
15627 item->RestoreCharges();
15629 else
15631 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);
15632 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15633 problematicItems.push_back(item);
15635 } while (result->NextRow());
15637 delete result;
15638 m_itemUpdateQueueBlocked = false;
15640 // send by mail problematic items
15641 while(!problematicItems.empty())
15643 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
15645 // fill mail
15646 MailDraft draft(subject);
15648 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
15650 Item* item = problematicItems.front();
15651 problematicItems.pop_front();
15653 draft.AddItem(item);
15656 draft.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
15659 //if(isAlive())
15660 _ApplyAllItemMods();
15663 // load mailed item which should receive current player
15664 void Player::_LoadMailedItems(Mail *mail)
15666 // data needs to be at first place for Item::LoadFromDB
15667 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);
15668 if(!result)
15669 return;
15673 Field *fields = result->Fetch();
15674 uint32 item_guid_low = fields[1].GetUInt32();
15675 uint32 item_template = fields[2].GetUInt32();
15677 mail->AddItem(item_guid_low, item_template);
15679 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(item_template);
15681 if(!proto)
15683 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);
15684 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15685 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
15686 continue;
15689 Item *item = NewItemOrBag(proto);
15691 if(!item->LoadFromDB(item_guid_low, 0, result))
15693 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
15694 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15695 item->FSetState(ITEM_REMOVED);
15696 item->SaveToDB(); // it also deletes item object !
15697 continue;
15700 AddMItem(item);
15701 } while (result->NextRow());
15703 delete result;
15706 void Player::_LoadMail()
15708 m_mail.clear();
15709 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15710 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());
15711 if(result)
15715 Field *fields = result->Fetch();
15716 Mail *m = new Mail;
15717 m->messageID = fields[0].GetUInt32();
15718 m->messageType = fields[1].GetUInt8();
15719 m->sender = fields[2].GetUInt32();
15720 m->receiver = fields[3].GetUInt32();
15721 m->subject = fields[4].GetCppString();
15722 m->itemTextId = fields[5].GetUInt32();
15723 bool has_items = fields[6].GetBool();
15724 m->expire_time = (time_t)fields[7].GetUInt64();
15725 m->deliver_time = (time_t)fields[8].GetUInt64();
15726 m->money = fields[9].GetUInt32();
15727 m->COD = fields[10].GetUInt32();
15728 m->checked = fields[11].GetUInt32();
15729 m->stationery = fields[12].GetUInt8();
15730 m->mailTemplateId = fields[13].GetInt16();
15732 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15734 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15735 m->mailTemplateId = 0;
15738 m->state = MAIL_STATE_UNCHANGED;
15740 if (has_items)
15741 _LoadMailedItems(m);
15743 m_mail.push_back(m);
15744 } while( result->NextRow() );
15745 delete result;
15749 void Player::LoadPet()
15751 //fixme: the pet should still be loaded if the player is not in world
15752 // just not added to the map
15753 if(IsInWorld())
15755 Pet *pet = new Pet;
15756 if(!pet->LoadPetFromDB(this,0,0,true))
15757 delete pet;
15761 void Player::_LoadQuestStatus(QueryResult *result)
15763 mQuestStatus.clear();
15765 uint32 slot = 0;
15767 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15768 //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());
15770 if(result)
15774 Field *fields = result->Fetch();
15776 uint32 quest_id = fields[0].GetUInt32();
15777 // used to be new, no delete?
15778 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15779 if( pQuest )
15781 // find or create
15782 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15784 uint32 qstatus = fields[1].GetUInt32();
15785 if(qstatus < MAX_QUEST_STATUS)
15786 questStatusData.m_status = QuestStatus(qstatus);
15787 else
15789 questStatusData.m_status = QUEST_STATUS_NONE;
15790 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15793 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15794 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15796 time_t quest_time = time_t(fields[4].GetUInt64());
15798 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15800 AddTimedQuest( quest_id );
15802 if (quest_time <= sWorld.GetGameTime())
15803 questStatusData.m_timer = 1;
15804 else
15805 questStatusData.m_timer = uint32(quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
15807 else
15808 quest_time = 0;
15810 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15811 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15812 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15813 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15814 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15815 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15816 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15817 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15819 questStatusData.uState = QUEST_UNCHANGED;
15821 // add to quest log
15822 if (slot < MAX_QUEST_LOG_SIZE &&
15823 ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
15824 questStatusData.m_status == QUEST_STATUS_COMPLETE ||
15825 questStatusData.m_status == QUEST_STATUS_FAILED) &&
15826 (!questStatusData.m_rewarded || pQuest->IsRepeatable())))
15828 SetQuestSlot(slot, quest_id, uint32(quest_time));
15830 if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
15831 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
15833 if (questStatusData.m_status == QUEST_STATUS_FAILED)
15834 SetQuestSlotState(slot, QUEST_STATE_FAIL);
15836 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15837 if(questStatusData.m_creatureOrGOcount[idx])
15838 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
15840 ++slot;
15843 if(questStatusData.m_rewarded)
15845 // learn rewarded spell if unknown
15846 learnQuestRewardedSpells(pQuest);
15848 // set rewarded title if any
15849 if(pQuest->GetCharTitleId())
15851 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15852 SetTitle(titleEntry);
15855 if(pQuest->GetBonusTalents())
15856 m_questRewardTalentCount += pQuest->GetBonusTalents();
15859 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15862 while( result->NextRow() );
15864 delete result;
15867 // clear quest log tail
15868 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15869 SetQuestSlot(i, 0);
15872 void Player::_LoadDailyQuestStatus(QueryResult *result)
15874 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15875 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15877 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15879 if(result)
15881 uint32 quest_daily_idx = 0;
15885 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15887 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15888 break;
15891 Field *fields = result->Fetch();
15893 uint32 quest_id = fields[0].GetUInt32();
15895 // save _any_ from daily quest times (it must be after last reset anyway)
15896 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15898 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15899 if( !pQuest )
15900 continue;
15902 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15903 ++quest_daily_idx;
15905 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15907 while( result->NextRow() );
15909 delete result;
15912 m_DailyQuestChanged = false;
15915 void Player::_LoadSpells(QueryResult *result)
15917 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15919 if(result)
15923 Field *fields = result->Fetch();
15925 addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool());
15927 while( result->NextRow() );
15929 delete result;
15933 void Player::_LoadGroup(QueryResult *result)
15935 //QueryResult *result = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15936 if (result)
15938 uint32 groupId = (*result)[0].GetUInt32();
15939 delete result;
15941 if (Group* group = sObjectMgr.GetGroupById(groupId))
15943 uint8 subgroup = group->GetMemberGroup(GetGUID());
15944 SetGroup(group, subgroup);
15945 if (getLevel() >= LEVELREQUIREMENT_HEROIC)
15947 // the group leader may change the instance difficulty while the player is offline
15948 SetDungeonDifficulty(group->GetDungeonDifficulty());
15949 SetRaidDifficulty(group->GetRaidDifficulty());
15955 void Player::_LoadBoundInstances(QueryResult *result)
15957 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15958 m_boundInstances[i].clear();
15960 Group *group = GetGroup();
15962 //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));
15963 if(result)
15967 Field *fields = result->Fetch();
15968 bool perm = fields[1].GetBool();
15969 uint32 mapId = fields[2].GetUInt32();
15970 uint32 instanceId = fields[0].GetUInt32();
15971 uint8 difficulty = fields[3].GetUInt8();
15973 time_t resetTime = (time_t)fields[4].GetUInt64();
15974 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15975 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15976 // and in that case it is not used
15978 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15979 if(!mapEntry || !mapEntry->IsDungeon())
15981 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15982 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15983 continue;
15986 if(difficulty >= MAX_DIFFICULTY)
15988 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15989 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15990 continue;
15993 MapDifficulty const* mapDiff = GetMapDifficultyData(mapId,Difficulty(difficulty));
15994 if(!mapDiff)
15996 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15997 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15998 continue;
16001 if(!perm && group)
16003 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);
16004 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
16005 continue;
16008 // since non permanent binds are always solo bind, they can always be reset
16009 InstanceSave *save = sInstanceSaveMgr.AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, !perm, true);
16010 if(save) BindToInstance(save, perm, true);
16011 } while(result->NextRow());
16012 delete result;
16016 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
16018 // some instances only have one difficulty
16019 MapDifficulty const* mapDiff = GetMapDifficultyData(mapid,difficulty);
16020 if(!mapDiff)
16021 return NULL;
16023 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
16024 if(itr != m_boundInstances[difficulty].end())
16025 return &itr->second;
16026 else
16027 return NULL;
16030 void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
16032 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
16033 UnbindInstance(itr, difficulty, unload);
16036 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
16038 if(itr != m_boundInstances[difficulty].end())
16040 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
16041 itr->second.save->RemovePlayer(this); // save can become invalid
16042 m_boundInstances[difficulty].erase(itr++);
16046 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
16048 if(save)
16050 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
16051 if(bind.save)
16053 // update the save when the group kills a boss
16054 if(permanent != bind.perm || save != bind.save)
16055 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());
16057 else
16058 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
16060 if(bind.save != save)
16062 if(bind.save) bind.save->RemovePlayer(this);
16063 save->AddPlayer(this);
16066 if(permanent) save->SetCanReset(false);
16068 bind.save = save;
16069 bind.perm = permanent;
16070 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());
16071 return &bind;
16073 else
16074 return NULL;
16077 void Player::SendRaidInfo()
16079 uint32 counter = 0;
16081 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
16083 size_t p_counter = data.wpos();
16084 data << uint32(counter); // placeholder
16086 time_t now = time(NULL);
16088 for(int i = 0; i < MAX_DIFFICULTY; ++i)
16090 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
16092 if(itr->second.perm)
16094 InstanceSave *save = itr->second.save;
16095 data << uint32(save->GetMapId()); // map id
16096 data << uint32(save->GetDifficulty()); // difficulty
16097 data << uint64(save->GetInstanceId()); // instance id
16098 data << uint8(1); // expired = 0
16099 data << uint8(0); // extended = 1
16100 data << uint32(save->GetResetTime() - now); // reset time
16101 ++counter;
16105 data.put<uint32>(p_counter, counter);
16106 GetSession()->SendPacket(&data);
16110 - called on every successful teleportation to a map
16112 void Player::SendSavedInstances()
16114 bool hasBeenSaved = false;
16115 WorldPacket data;
16117 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16119 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
16121 if(itr->second.perm) // only permanent binds are sent
16123 hasBeenSaved = true;
16124 break;
16129 //Send opcode 811. true or false means, whether you have current raid/heroic instances
16130 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
16131 data << uint32(hasBeenSaved);
16132 GetSession()->SendPacket(&data);
16134 if(!hasBeenSaved)
16135 return;
16137 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16139 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
16141 if(itr->second.perm)
16143 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
16144 data << uint32(itr->second.save->GetMapId());
16145 GetSession()->SendPacket(&data);
16151 /// convert the player's binds to the group
16152 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
16154 bool has_binds = false;
16155 bool has_solo = false;
16157 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
16158 assert(player_guid);
16160 // copy all binds to the group, when changing leader it's assumed the character
16161 // will not have any solo binds
16163 if(player)
16165 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16167 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
16169 has_binds = true;
16170 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
16171 // permanent binds are not removed
16172 if(!itr->second.perm)
16174 // increments itr in call
16175 player->UnbindInstance(itr, Difficulty(i), true);
16176 has_solo = true;
16178 else
16179 ++itr;
16184 // if the player's not online we don't know what binds it has
16185 if(!player || !group || has_binds)
16186 CharacterDatabase.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid));
16188 // the following should not get executed when changing leaders
16189 if(!player || has_solo)
16190 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
16193 bool Player::_LoadHomeBind(QueryResult *result)
16195 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
16196 if(!info)
16198 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
16199 return false;
16202 bool ok = false;
16203 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
16204 if (result)
16206 Field *fields = result->Fetch();
16207 m_homebindMapId = fields[0].GetUInt32();
16208 m_homebindAreaId = fields[1].GetUInt16();
16209 m_homebindX = fields[2].GetFloat();
16210 m_homebindY = fields[3].GetFloat();
16211 m_homebindZ = fields[4].GetFloat();
16212 delete result;
16214 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
16216 // accept saved data only for valid position (and non instanceable), and accessable
16217 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
16218 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
16220 ok = true;
16222 else
16223 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
16226 if(!ok)
16228 m_homebindMapId = info->mapId;
16229 m_homebindAreaId = info->areaId;
16230 m_homebindX = info->positionX;
16231 m_homebindY = info->positionY;
16232 m_homebindZ = info->positionZ;
16234 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);
16237 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
16238 m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ);
16240 return true;
16243 /*********************************************************/
16244 /*** SAVE SYSTEM ***/
16245 /*********************************************************/
16247 void Player::SaveToDB()
16249 // we should assure this: assert((m_nextSave != sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE)));
16250 // delay auto save at any saves (manual, in code, or autosave)
16251 m_nextSave = sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE);
16253 //lets allow only players in world to be saved
16254 if(IsBeingTeleportedFar())
16256 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
16257 return;
16260 // first save/honor gain after midnight will also update the player's honor fields
16261 UpdateHonorFields();
16263 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
16264 outDebugValues();
16266 CharacterDatabase.BeginTransaction();
16268 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
16270 std::string sql_name = m_name;
16271 CharacterDatabase.escape_string(sql_name);
16273 std::ostringstream ss;
16274 ss << "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
16275 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
16276 "taximask, online, cinematic, "
16277 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
16278 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
16279 "death_expire_time, taxi_path, arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, "
16280 "todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, health, power1, power2, power3, "
16281 "power4, power5, power6, power7, specCount, activeSpec) VALUES ("
16282 << GetGUIDLow() << ", "
16283 << GetSession()->GetAccountId() << ", '"
16284 << sql_name << "', "
16285 << (uint32)getRace() << ", "
16286 << (uint32)getClass() << ", "
16287 << (uint32)getGender() << ", "
16288 << getLevel() << ", "
16289 << GetUInt32Value(PLAYER_XP) << ", "
16290 << GetMoney() << ", "
16291 << GetUInt32Value(PLAYER_BYTES) << ", "
16292 << GetUInt32Value(PLAYER_BYTES_2) << ", "
16293 << GetUInt32Value(PLAYER_FLAGS) << ", ";
16295 if(!IsBeingTeleported())
16297 ss << GetMapId() << ", "
16298 << (uint32)GetDungeonDifficulty() << ", "
16299 << finiteAlways(GetPositionX()) << ", "
16300 << finiteAlways(GetPositionY()) << ", "
16301 << finiteAlways(GetPositionZ()) << ", "
16302 << finiteAlways(GetOrientation()) << ", '";
16304 else
16306 ss << GetTeleportDest().mapid << ", "
16307 << (uint32)GetDungeonDifficulty() << ", "
16308 << finiteAlways(GetTeleportDest().coord_x) << ", "
16309 << finiteAlways(GetTeleportDest().coord_y) << ", "
16310 << finiteAlways(GetTeleportDest().coord_z) << ", "
16311 << finiteAlways(GetTeleportDest().orientation) << ", '";
16314 uint16 i;
16315 for( i = 0; i < m_valuesCount; ++i )
16317 ss << GetUInt32Value(i) << " ";
16320 ss << "', ";
16322 ss << m_taxi << ", "; // string with TaxiMaskSize numbers
16324 ss << (IsInWorld() ? 1 : 0) << ", ";
16326 ss << m_cinematic << ", ";
16328 ss << m_Played_time[PLAYED_TIME_TOTAL] << ", ";
16329 ss << m_Played_time[PLAYED_TIME_LEVEL] << ", ";
16331 ss << finiteAlways(m_rest_bonus) << ", ";
16332 ss << (uint64)time(NULL) << ", ";
16333 ss << (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0) << ", ";
16334 //save, far from tavern/city
16335 //save, but in tavern/city
16336 ss << m_resetTalentsCost << ", ";
16337 ss << (uint64)m_resetTalentsTime << ", ";
16339 ss << finiteAlways(m_movementInfo.GetTransportPos()->x) << ", ";
16340 ss << finiteAlways(m_movementInfo.GetTransportPos()->y) << ", ";
16341 ss << finiteAlways(m_movementInfo.GetTransportPos()->z) << ", ";
16342 ss << finiteAlways(m_movementInfo.GetTransportPos()->o) << ", ";
16343 if (m_transport)
16344 ss << m_transport->GetGUIDLow();
16345 else
16346 ss << "0";
16347 ss << ", ";
16349 ss << m_ExtraFlags << ", ";
16351 ss << uint32(m_stableSlots) << ", "; // to prevent save uint8 as char
16353 ss << uint32(m_atLoginFlags) << ", ";
16355 ss << GetZoneId() << ", ";
16357 ss << (uint64)m_deathExpireTime << ", '";
16359 ss << m_taxi.SaveTaxiDestinationsToString() << "', ";
16361 ss << GetArenaPoints() << ", ";
16363 ss << GetHonorPoints() << ", ";
16365 ss << GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION) << ", ";
16367 ss << GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION) << ", ";
16369 ss << GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS) << ", ";
16371 ss << GetUInt16Value(PLAYER_FIELD_KILLS, 0) << ", ";
16373 ss << GetUInt16Value(PLAYER_FIELD_KILLS, 1) << ", ";
16375 ss << GetUInt32Value(PLAYER_CHOSEN_TITLE) << ", ";
16377 ss << GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES) << ", ";
16379 // FIXME: at this moment send to DB as unsigned, including unit32(-1)
16380 ss << GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX) << ", ";
16382 ss << (uint16)(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE) << ", ";
16384 ss << GetHealth();
16386 for(uint32 i = 0; i < MAX_POWERS; ++i)
16387 ss << "," << GetPower(Powers(i));
16389 ss << ", ";
16390 ss << uint32(m_specsCount) << ", ";
16391 ss << uint32(m_activeSpec);
16393 ss << ")";
16395 CharacterDatabase.Execute( ss.str().c_str() );
16397 if(m_mailsUpdated) //save mails only when needed
16398 _SaveMail();
16400 _SaveBGData();
16401 _SaveInventory();
16402 _SaveQuestStatus();
16403 _SaveDailyQuestStatus();
16404 _SaveSpells();
16405 _SaveSpellCooldowns();
16406 _SaveActions();
16407 _SaveAuras();
16408 _SaveSkills();
16409 m_achievementMgr.SaveToDB();
16410 m_reputationMgr.SaveToDB();
16411 _SaveEquipmentSets();
16412 GetSession()->SaveTutorialsData(); // changed only while character in game
16413 _SaveGlyphs();
16415 CharacterDatabase.CommitTransaction();
16417 // save pet (hunter pet level and experience and all type pets health/mana).
16418 if(Pet* pet = GetPet())
16419 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
16422 // fast save function for item/money cheating preventing - save only inventory and money state
16423 void Player::SaveInventoryAndGoldToDB()
16425 _SaveInventory();
16426 SaveGoldToDB();
16429 void Player::SaveGoldToDB()
16431 CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
16434 void Player::_SaveActions()
16436 for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
16438 for(ActionButtonList::iterator itr = m_actionButtons[i].begin(); itr != m_actionButtons[i].end(); )
16440 switch (itr->second.uState)
16442 case ACTIONBUTTON_NEW:
16443 CharacterDatabase.PExecute("INSERT INTO character_action (guid,spec, button,action,type) VALUES ('%u', '%u', '%u', '%u', '%u')",
16444 GetGUIDLow(), i, (uint32)itr->first, (uint32)itr->second.GetAction(), (uint32)itr->second.GetType() );
16445 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16446 ++itr;
16447 break;
16448 case ACTIONBUTTON_CHANGED:
16449 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' AND spec = '%u'",
16450 (uint32)itr->second.GetAction(), (uint32)itr->second.GetType(), GetGUIDLow(), (uint32)itr->first, i );
16451 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16452 ++itr;
16453 break;
16454 case ACTIONBUTTON_DELETED:
16455 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' AND button = '%u' AND spec = '%u'", GetGUIDLow(), (uint32)itr->first, i);
16456 m_actionButtons[i].erase(itr++);
16457 break;
16458 default:
16459 ++itr;
16460 break;
16466 void Player::_SaveAuras()
16468 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
16470 AuraMap const& auras = GetAuras();
16472 if (auras.empty())
16473 return;
16475 spellEffectPair lastEffectPair = auras.begin()->first;
16476 uint32 stackCounter = 1;
16478 /* copied following sql-code partly from achievementmgr */
16479 bool first_round = true;
16480 std::ostringstream ss;
16481 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
16483 if(itr == auras.end() || lastEffectPair != itr->first)
16485 AuraMap::const_iterator itr2 = itr;
16486 // save previous spellEffectPair to db
16487 itr2--;
16489 //skip all auras from spells that are passive
16490 //do not save single target auras (unless they were cast by the player)
16491 if (!itr2->second->IsPassive() && (itr2->second->GetCasterGUID() == GetGUID() || !itr2->second->IsSingleTarget()))
16493 if (first_round)
16495 ss << "INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges)VALUES ";
16496 first_round = false;
16498 // next new/changed record prefix
16499 else
16500 ss << ", ";
16502 ss << "("<< GetGUIDLow() << "," << itr2->second->GetCasterGUID() << ","
16503 << (uint32)itr2->second->GetId() << "," << (uint32)itr2->second->GetEffIndex() << ","
16504 << stackCounter << "," << itr2->second->GetModifier()->m_amount << ","
16505 <<int(itr2->second->GetAuraMaxDuration()) << "," << int(itr2->second->GetAuraDuration()) << ","
16506 << int(itr2->second->GetAuraCharges()) << ")";
16509 if(itr == auras.end())
16510 break;
16513 if (lastEffectPair == itr->first)
16514 stackCounter++;
16515 else
16517 lastEffectPair = itr->first;
16518 stackCounter = 1;
16522 // if something changed execute
16523 if (!first_round)
16524 CharacterDatabase.Execute( ss.str().c_str() );
16527 void Player::_SaveGlyphs()
16530 for (uint8 spec = 0; spec < m_specsCount; ++spec)
16532 for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
16534 switch(m_glyphs[spec][slot].uState)
16536 case GLYPH_NEW:
16537 CharacterDatabase.PExecute("INSERT INTO character_glyphs (guid, spec, slot, glyph) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), spec, slot, m_glyphs[spec][slot].GetId());
16538 break;
16539 case GLYPH_CHANGED:
16540 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);
16541 break;
16542 case GLYPH_DELETED:
16543 CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid='%u' AND spec = '%u' AND slot = '%u'",GetGUIDLow(), spec, slot);
16544 break;
16545 case GLYPH_UNCHANGED:
16546 break;
16548 m_glyphs[spec][slot].uState = GLYPH_UNCHANGED;
16553 void Player::_SaveInventory()
16555 // force items in buyback slots to new state
16556 // and remove those that aren't already
16557 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
16559 Item *item = m_items[i];
16560 if (!item || item->GetState() == ITEM_NEW) continue;
16561 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16562 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
16563 m_items[i]->FSetState(ITEM_NEW);
16566 // update enchantment durations
16567 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
16569 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
16572 // if no changes
16573 if (m_itemUpdateQueue.empty()) return;
16575 // do not save if the update queue is corrupt
16576 bool error = false;
16577 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16579 Item *item = m_itemUpdateQueue[i];
16580 if(!item || item->GetState() == ITEM_REMOVED) continue;
16581 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
16583 if (test == NULL)
16585 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());
16586 error = true;
16588 else if (test != item)
16590 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());
16591 error = true;
16595 if (error)
16597 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
16598 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
16599 return;
16602 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16604 Item *item = m_itemUpdateQueue[i];
16605 if(!item) continue;
16607 Bag *container = item->GetContainer();
16608 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
16610 switch(item->GetState())
16612 case ITEM_NEW:
16613 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());
16614 break;
16615 case ITEM_CHANGED:
16616 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());
16617 break;
16618 case ITEM_REMOVED:
16619 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16620 break;
16621 case ITEM_UNCHANGED:
16622 break;
16625 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
16627 m_itemUpdateQueue.clear();
16630 void Player::_SaveMail()
16632 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
16634 Mail *m = (*itr);
16635 if (m->state == MAIL_STATE_CHANGED)
16637 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'",
16638 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
16639 if(m->removedItems.size())
16641 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
16642 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
16643 m->removedItems.clear();
16645 m->state = MAIL_STATE_UNCHANGED;
16647 else if (m->state == MAIL_STATE_DELETED)
16649 if (m->HasItems())
16650 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
16651 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
16652 if (m->itemTextId)
16653 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
16654 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
16655 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
16659 //deallocate deleted mails...
16660 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
16662 if ((*itr)->state == MAIL_STATE_DELETED)
16664 Mail* m = *itr;
16665 m_mail.erase(itr);
16666 delete m;
16667 itr = m_mail.begin();
16669 else
16670 ++itr;
16673 m_mailsUpdated = false;
16676 void Player::_SaveQuestStatus()
16678 // we don't need transactions here.
16679 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
16681 switch (i->second.uState)
16683 case QUEST_NEW :
16684 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
16685 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
16686 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]);
16687 break;
16688 case QUEST_CHANGED :
16689 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' ",
16690 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 );
16691 break;
16692 case QUEST_UNCHANGED:
16693 break;
16695 i->second.uState = QUEST_UNCHANGED;
16699 void Player::_SaveDailyQuestStatus()
16701 if(!m_DailyQuestChanged)
16702 return;
16704 m_DailyQuestChanged = false;
16706 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
16708 // we don't need transactions here.
16709 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
16710 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
16711 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
16712 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
16713 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
16717 void Player::_SaveSkills()
16719 // we don't need transactions here.
16720 for( SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); )
16722 if(itr->second.uState == SKILL_UNCHANGED)
16724 ++itr;
16725 continue;
16728 if(itr->second.uState == SKILL_DELETED)
16730 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), itr->first );
16731 mSkillStatus.erase(itr++);
16732 continue;
16735 uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos));
16736 uint16 value = SKILL_VALUE(valueData);
16737 uint16 max = SKILL_MAX(valueData);
16739 switch (itr->second.uState)
16741 case SKILL_NEW:
16742 CharacterDatabase.PExecute("INSERT INTO character_skills (guid, skill, value, max) VALUES ('%u', '%u', '%u', '%u')",
16743 GetGUIDLow(), itr->first, value, max);
16744 break;
16745 case SKILL_CHANGED:
16746 CharacterDatabase.PExecute("UPDATE character_skills SET value = '%u',max = '%u'WHERE guid = '%u' AND skill = '%u' ",
16747 value, max, GetGUIDLow(), itr->first );
16748 break;
16750 itr->second.uState = SKILL_UNCHANGED;
16752 ++itr;
16756 void Player::_SaveSpells()
16758 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
16760 if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.state == PLAYERSPELL_CHANGED)
16761 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
16763 // add only changed/new not dependent spells
16764 if (!itr->second.dependent && (itr->second.state == PLAYERSPELL_NEW || itr->second.state == PLAYERSPELL_CHANGED))
16765 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);
16767 if (itr->second.state == PLAYERSPELL_REMOVED)
16768 m_spells.erase(itr++);
16769 else
16771 itr->second.state = PLAYERSPELL_UNCHANGED;
16772 ++itr;
16778 void Player::outDebugValues() const
16780 if(!sLog.IsOutDebug()) // optimize disabled debug output
16781 return;
16783 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
16784 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
16785 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
16786 sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
16787 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
16788 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
16789 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
16790 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
16791 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
16792 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
16793 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
16794 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
16797 /*********************************************************/
16798 /*** FLOOD FILTER SYSTEM ***/
16799 /*********************************************************/
16801 void Player::UpdateSpeakTime()
16803 // ignore chat spam protection for GMs in any mode
16804 if(GetSession()->GetSecurity() > SEC_PLAYER)
16805 return;
16807 time_t current = time (NULL);
16808 if(m_speakTime > current)
16810 uint32 max_count = sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_COUNT);
16811 if(!max_count)
16812 return;
16814 ++m_speakCount;
16815 if(m_speakCount >= max_count)
16817 // prevent overwrite mute time, if message send just before mutes set, for example.
16818 time_t new_mute = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MUTE_TIME);
16819 if(GetSession()->m_muteTime < new_mute)
16820 GetSession()->m_muteTime = new_mute;
16822 m_speakCount = 0;
16825 else
16826 m_speakCount = 0;
16828 m_speakTime = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_DELAY);
16831 bool Player::CanSpeak() const
16833 return GetSession()->m_muteTime <= time (NULL);
16836 /*********************************************************/
16837 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16838 /*********************************************************/
16840 void Player::SendAttackSwingNotInRange()
16842 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16843 GetSession()->SendPacket( &data );
16846 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16848 std::ostringstream ss;
16849 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16850 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16851 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16852 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16853 sLog.outDebug("%s", ss.str().c_str());
16854 CharacterDatabase.Execute(ss.str().c_str());
16857 void Player::SaveDataFieldToDB()
16859 std::ostringstream ss;
16860 ss<<"UPDATE characters SET data='";
16862 for(uint16 i = 0; i < m_valuesCount; ++i )
16864 ss << GetUInt32Value(i) << " ";
16866 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16868 CharacterDatabase.Execute(ss.str().c_str());
16871 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16873 std::ostringstream ss2;
16874 ss2 << "UPDATE characters SET data='";
16875 int i = 0;
16876 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16878 ss2 << tokens[i] << " ";
16880 ss2 << "' WHERE guid='" << GUID_LOPART(guid) << "'";
16882 return CharacterDatabase.Execute(ss2.str().c_str());
16885 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16887 char buf[11];
16888 snprintf(buf,11,"%u",value);
16890 if(index >= tokens.size())
16891 return;
16893 tokens[index] = buf;
16896 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16898 Tokens tokens;
16899 if(!LoadValuesArrayFromDB(tokens,guid))
16900 return;
16902 if(index >= tokens.size())
16903 return;
16905 char buf[11];
16906 snprintf(buf,11,"%u",value);
16907 tokens[index] = buf;
16909 SaveValuesArrayInDB(tokens,guid);
16912 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16914 uint32 temp;
16915 memcpy(&temp, &value, sizeof(value));
16916 Player::SetUInt32ValueInDB(index, temp, guid);
16919 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16921 // 0
16922 QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
16923 if(!result)
16924 return;
16926 Field* fields = result->Fetch();
16928 uint32 player_bytes2 = fields[0].GetUInt32();
16929 player_bytes2 &= ~0xFF;
16930 player_bytes2 |= facialHair;
16932 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));
16934 delete result;
16937 void Player::SendAttackSwingDeadTarget()
16939 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16940 GetSession()->SendPacket( &data );
16943 void Player::SendAttackSwingCantAttack()
16945 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16946 GetSession()->SendPacket( &data );
16949 void Player::SendAttackSwingCancelAttack()
16951 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16952 GetSession()->SendPacket( &data );
16955 void Player::SendAttackSwingBadFacingAttack()
16957 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16958 GetSession()->SendPacket( &data );
16961 void Player::SendAutoRepeatCancel(Unit *target)
16963 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
16964 data.append(target->GetPackGUID()); // may be it's target guid
16965 GetSession()->SendPacket( &data );
16968 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16970 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16971 data << uint32(Area);
16972 data << uint32(Experience);
16973 GetSession()->SendPacket(&data);
16976 void Player::SendDungeonDifficulty(bool IsInGroup)
16978 uint8 val = 0x00000001;
16979 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16980 data << uint32(GetDungeonDifficulty());
16981 data << uint32(val);
16982 data << uint32(IsInGroup);
16983 GetSession()->SendPacket(&data);
16986 void Player::SendRaidDifficulty(bool IsInGroup)
16988 uint8 val = 0x00000001;
16989 WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
16990 data << uint32(GetRaidDifficulty());
16991 data << uint32(val);
16992 data << uint32(IsInGroup);
16993 GetSession()->SendPacket(&data);
16996 void Player::SendResetFailedNotify(uint32 mapid)
16998 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16999 data << uint32(mapid);
17000 GetSession()->SendPacket(&data);
17003 /// Reset all solo instances and optionally send a message on success for each
17004 void Player::ResetInstances(uint8 method, bool isRaid)
17006 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
17008 // we assume that when the difficulty changes, all instances that can be reset will be
17009 Difficulty diff = GetDifficulty(isRaid);
17011 for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
17013 InstanceSave *p = itr->second.save;
17014 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
17015 if(!entry || entry->IsRaid() != isRaid || !p->CanReset())
17017 ++itr;
17018 continue;
17021 if(method == INSTANCE_RESET_ALL)
17023 // the "reset all instances" method can only reset normal maps
17024 if(entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
17026 ++itr;
17027 continue;
17031 // if the map is loaded, reset it
17032 Map *map = sMapMgr.FindMap(p->GetMapId(), p->GetInstanceId());
17033 if(map && map->IsDungeon())
17034 ((InstanceMap*)map)->Reset(method);
17036 // since this is a solo instance there should not be any players inside
17037 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
17038 SendResetInstanceSuccess(p->GetMapId());
17040 p->DeleteFromDB();
17041 m_boundInstances[diff].erase(itr++);
17043 // the following should remove the instance save from the manager and delete it as well
17044 p->RemovePlayer(this);
17048 void Player::SendResetInstanceSuccess(uint32 MapId)
17050 WorldPacket data(SMSG_INSTANCE_RESET, 4);
17051 data << uint32(MapId);
17052 GetSession()->SendPacket(&data);
17055 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
17057 // TODO: find what other fail reasons there are besides players in the instance
17058 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
17059 data << uint32(reason);
17060 data << uint32(MapId);
17061 GetSession()->SendPacket(&data);
17064 /*********************************************************/
17065 /*** Update timers ***/
17066 /*********************************************************/
17068 ///checks the 15 afk reports per 5 minutes limit
17069 void Player::UpdateAfkReport(time_t currTime)
17071 if(m_bgData.bgAfkReportedTimer <= currTime)
17073 m_bgData.bgAfkReportedCount = 0;
17074 m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
17078 void Player::UpdateContestedPvP(uint32 diff)
17080 if(!m_contestedPvPTimer||isInCombat())
17081 return;
17082 if(m_contestedPvPTimer <= diff)
17084 ResetContestedPvP();
17086 else
17087 m_contestedPvPTimer -= diff;
17090 void Player::UpdatePvPFlag(time_t currTime)
17092 if(!IsPvP())
17093 return;
17094 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
17095 return;
17097 UpdatePvP(false);
17100 void Player::UpdateDuelFlag(time_t currTime)
17102 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
17103 return;
17105 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
17106 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
17108 duel->startTimer = 0;
17109 duel->startTime = currTime;
17110 duel->opponent->duel->startTimer = 0;
17111 duel->opponent->duel->startTime = currTime;
17114 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
17116 if(!pet)
17117 pet = GetPet();
17119 if(!pet || pet->GetOwnerGUID()!=GetGUID())
17120 return;
17122 // not save secondary permanent pet as current
17123 if (pet && m_temporaryUnsummonedPetNumber != pet->GetCharmInfo()->GetPetNumber() && mode == PET_SAVE_AS_CURRENT)
17124 mode = PET_SAVE_NOT_IN_SLOT;
17126 if(returnreagent && pet && mode != PET_SAVE_AS_CURRENT)
17128 //returning of reagents only for players, so best done here
17129 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
17130 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
17132 if(spellInfo)
17134 for(uint32 i = 0; i < 7; ++i)
17136 if(spellInfo->Reagent[i] > 0)
17138 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
17139 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
17140 if( msg == EQUIP_ERR_OK )
17142 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
17143 if(IsInWorld())
17144 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
17151 // only if current pet in slot
17152 switch(pet->getPetType())
17154 case MINI_PET:
17155 m_miniPet = 0;
17156 break;
17157 case GUARDIAN_PET:
17158 RemoveGuardian(pet);
17159 break;
17160 default:
17161 if(GetPetGUID() == pet->GetGUID())
17162 SetPet(NULL);
17163 break;
17166 pet->CombatStop();
17168 pet->SavePetToDB(mode);
17170 pet->AddObjectToRemoveList();
17171 pet->m_removed = true;
17173 if(pet->isControlled())
17175 RemovePetActionBar();
17177 if(GetGroup())
17178 SetGroupUpdateFlag(GROUP_UPDATE_PET);
17182 void Player::RemoveMiniPet()
17184 if(Pet* pet = GetMiniPet())
17186 pet->Remove(PET_SAVE_AS_DELETED);
17187 m_miniPet = 0;
17191 Pet* Player::GetMiniPet()
17193 if(!m_miniPet)
17194 return NULL;
17195 return GetMap()->GetPet(m_miniPet);
17198 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
17200 *data << (uint8)msgtype;
17201 *data << (uint32)language;
17202 *data << (uint64)GetGUID();
17203 *data << (uint32)language; //language 2.1.0 ?
17204 *data << (uint64)GetGUID();
17205 *data << (uint32)(text.length()+1);
17206 *data << text;
17207 *data << (uint8)chatTag();
17210 void Player::Say(const std::string& text, const uint32 language)
17212 WorldPacket data(SMSG_MESSAGECHAT, 200);
17213 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
17214 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY),true);
17217 void Player::Yell(const std::string& text, const uint32 language)
17219 WorldPacket data(SMSG_MESSAGECHAT, 200);
17220 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
17221 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL),true);
17224 void Player::TextEmote(const std::string& text)
17226 WorldPacket data(SMSG_MESSAGECHAT, 200);
17227 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
17228 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
17231 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
17233 if (language != LANG_ADDON) // if not addon data
17234 language = LANG_UNIVERSAL; // whispers should always be readable
17236 Player *rPlayer = sObjectMgr.GetPlayer(receiver);
17238 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
17239 if(!rPlayer->isDND() || isGameMaster())
17241 WorldPacket data(SMSG_MESSAGECHAT, 200);
17242 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
17243 rPlayer->GetSession()->SendPacket(&data);
17245 // not send confirmation for addon messages
17246 if (language != LANG_ADDON)
17248 data.Initialize(SMSG_MESSAGECHAT, 200);
17249 rPlayer->BuildPlayerChat(&data, CHAT_MSG_WHISPER_INFORM, text, language);
17250 GetSession()->SendPacket(&data);
17253 else
17255 // announce to player that player he is whispering to is dnd and cannot receive his message
17256 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
17259 if(!isAcceptWhispers())
17261 SetAcceptWhispers(true);
17262 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
17265 // announce to player that player he is whispering to is afk
17266 if(rPlayer->isAFK())
17267 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
17269 // if player whisper someone, auto turn of dnd to be able to receive an answer
17270 if(isDND() && !rPlayer->isGameMaster())
17271 ToggleDND();
17274 void Player::PetSpellInitialize()
17276 Pet* pet = GetPet();
17278 if(!pet)
17279 return;
17281 sLog.outDebug("Pet Spells Groups");
17283 CharmInfo *charmInfo = pet->GetCharmInfo();
17285 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17286 data << uint64(pet->GetGUID());
17287 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
17288 data << uint32(0);
17289 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17291 // action bar loop
17292 charmInfo->BuildActionBar(&data);
17294 size_t spellsCountPos = data.wpos();
17296 // spells count
17297 uint8 addlist = 0;
17298 data << uint8(addlist); // placeholder
17300 if (pet->IsPermanentPetFor(this))
17302 // spells loop
17303 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
17305 if(itr->second.state == PETSPELL_REMOVED)
17306 continue;
17308 data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
17309 ++addlist;
17313 data.put<uint8>(spellsCountPos, addlist);
17315 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
17316 data << uint8(cooldownsCount);
17318 time_t curTime = time(NULL);
17320 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
17322 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
17324 data << uint32(itr->first); // spellid
17325 data << uint16(0); // spell category?
17326 data << uint32(cooldown); // cooldown
17327 data << uint32(0); // category cooldown
17330 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
17332 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
17334 data << uint32(itr->first); // spellid
17335 data << uint16(0); // spell category?
17336 data << uint32(0); // cooldown
17337 data << uint32(cooldown); // category cooldown
17340 GetSession()->SendPacket(&data);
17343 void Player::SendPetGUIDs()
17345 if(!GetPetGUID())
17346 return;
17348 // Later this function might get modified for multiple guids
17349 WorldPacket data(SMSG_PET_GUIDS, 12);
17350 data << uint32(1); // count
17351 data << uint64(GetPetGUID());
17352 GetSession()->SendPacket(&data);
17355 void Player::PossessSpellInitialize()
17357 Unit* charm = GetCharm();
17359 if(!charm)
17360 return;
17362 CharmInfo *charmInfo = charm->GetCharmInfo();
17364 if(!charmInfo)
17366 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17367 return;
17370 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17371 data << uint64(charm->GetGUID());
17372 data << uint16(0);
17373 data << uint32(0);
17374 data << uint32(0);
17376 charmInfo->BuildActionBar(&data);
17378 data << uint8(0); // spells count
17379 data << uint8(0); // cooldowns count
17381 GetSession()->SendPacket(&data);
17384 void Player::CharmSpellInitialize()
17386 Unit* charm = GetCharm();
17388 if(!charm)
17389 return;
17391 CharmInfo *charmInfo = charm->GetCharmInfo();
17392 if(!charmInfo)
17394 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17395 return;
17398 uint8 addlist = 0;
17400 if(charm->GetTypeId() != TYPEID_PLAYER)
17402 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
17404 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
17406 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17408 if(charmInfo->GetCharmSpell(i)->GetAction())
17409 ++addlist;
17414 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
17415 data << uint64(charm->GetGUID());
17416 data << uint16(0);
17417 data << uint32(0);
17419 if(charm->GetTypeId() != TYPEID_PLAYER)
17420 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17421 else
17422 data << uint8(0) << uint8(0) << uint16(0);
17424 charmInfo->BuildActionBar(&data);
17426 data << uint8(addlist);
17428 if(addlist)
17430 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17432 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
17433 if(cspell->GetAction())
17434 data << uint32(cspell->packedData);
17438 data << uint8(0); // cooldowns count
17440 GetSession()->SendPacket(&data);
17443 void Player::RemovePetActionBar()
17445 WorldPacket data(SMSG_PET_SPELLS, 8);
17446 data << uint64(0);
17447 SendDirectMessage(&data);
17450 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
17452 if (!mod || !spellInfo)
17453 return false;
17455 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
17457 // prevent apply to any spell except spell that trigger expire
17458 if(spell)
17460 if(mod->lastAffected != spell)
17461 return false;
17463 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
17464 return false;
17467 return mod->isAffectedOnSpell(spellInfo);
17470 void Player::AddSpellMod(SpellModifier* mod, bool apply)
17472 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
17474 for(int eff = 0; eff < 96; ++eff)
17476 uint64 _mask = 0;
17477 uint32 _mask2= 0;
17479 if (eff < 64)
17480 _mask = uint64(1) << (eff - 0);
17481 else
17482 _mask2= uint32(1) << (eff - 64);
17484 if ( mod->mask & _mask || mod->mask2 & _mask2)
17486 int32 val = 0;
17487 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
17489 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
17490 val += (*itr)->value;
17492 val += apply ? mod->value : -(mod->value);
17493 WorldPacket data(Opcode, (1+1+4));
17494 data << uint8(eff);
17495 data << uint8(mod->op);
17496 data << int32(val);
17497 SendDirectMessage(&data);
17501 if (apply)
17502 m_spellMods[mod->op].push_back(mod);
17503 else
17505 if (mod->charges == -1)
17506 --m_SpellModRemoveCount;
17507 m_spellMods[mod->op].remove(mod);
17508 delete mod;
17512 void Player::RemoveSpellMods(Spell const* spell)
17514 if(!spell || (m_SpellModRemoveCount == 0))
17515 return;
17517 for(int i=0;i<MAX_SPELLMOD;++i)
17519 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
17521 SpellModifier *mod = *itr;
17522 ++itr;
17524 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
17526 RemoveAurasDueToSpell(mod->spellId);
17527 if (m_spellMods[i].empty())
17528 break;
17529 else
17530 itr = m_spellMods[i].begin();
17536 // send Proficiency
17537 void Player::SendProficiency(uint8 pr1, uint32 pr2)
17539 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
17540 data << uint8(pr1) << uint32(pr2);
17541 GetSession()->SendPacket (&data);
17544 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
17546 QueryResult *result = NULL;
17547 if(type == 10)
17548 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17549 else
17550 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17551 if(result)
17553 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.
17554 { // and SendPetitionQueryOpcode reads data from the DB
17555 Field *fields = result->Fetch();
17556 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
17557 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
17559 // send update if charter owner in game
17560 Player* owner = sObjectMgr.GetPlayer(ownerguid);
17561 if(owner)
17562 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
17564 } while ( result->NextRow() );
17566 delete result;
17568 if(type==10)
17569 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17570 else
17571 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17574 CharacterDatabase.BeginTransaction();
17575 if(type == 10)
17577 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
17578 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
17580 else
17582 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17583 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17585 CharacterDatabase.CommitTransaction();
17588 void Player::LeaveAllArenaTeams(uint64 guid)
17590 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));
17591 if(!result)
17592 return;
17596 Field *fields = result->Fetch();
17597 uint32 at_id = fields[0].GetUInt32();
17598 if(at_id != 0)
17600 ArenaTeam * at = sObjectMgr.GetArenaTeamById(at_id);
17601 if(at)
17602 at->DelMember(guid);
17604 } while (result->NextRow());
17606 delete result;
17609 void Player::SetRestBonus (float rest_bonus_new)
17611 // Prevent resting on max level
17612 if(getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
17613 rest_bonus_new = 0;
17615 if(rest_bonus_new < 0)
17616 rest_bonus_new = 0;
17618 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5f/2.0f;
17620 if(rest_bonus_new > rest_bonus_max)
17621 m_rest_bonus = rest_bonus_max;
17622 else
17623 m_rest_bonus = rest_bonus_new;
17625 // update data for client
17626 if(m_rest_bonus>10)
17627 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
17628 else if(m_rest_bonus<=1)
17629 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
17631 //RestTickUpdate
17632 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
17635 void Player::HandleStealthedUnitsDetection()
17637 std::list<Unit*> stealthedUnits;
17639 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17640 Cell cell(p);
17641 cell.data.Part.reserved = ALL_DISTRICT;
17642 cell.SetNoCreate();
17644 MaNGOS::AnyStealthedCheck u_check;
17645 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
17647 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
17648 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
17650 cell.Visit(p, world_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17651 cell.Visit(p, grid_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17653 WorldObject const* viewPoint = GetViewPoint();
17655 for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
17657 if((*i)==this)
17658 continue;
17660 bool hasAtClient = HaveAtClient((*i));
17661 bool hasDetected = (*i)->isVisibleForOrDetect(this, viewPoint, true);
17663 if (hasDetected)
17665 if(!hasAtClient)
17667 (*i)->SendCreateUpdateToPlayer(this);
17668 m_clientGUIDs.insert((*i)->GetGUID());
17670 #ifdef MANGOS_DEBUG
17671 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17672 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
17673 #endif
17675 // target aura duration for caster show only if target exist at caster client
17676 // send data at target visibility change (adding to client)
17677 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
17678 SendAurasForTarget(*i);
17681 else
17683 if(hasAtClient)
17685 (*i)->DestroyForPlayer(this);
17686 m_clientGUIDs.erase((*i)->GetGUID());
17692 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
17694 if(nodes.size() < 2)
17695 return false;
17697 // 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
17698 if(GetSession()->isLogingOut() || isInCombat())
17700 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17701 data << uint32(ERR_TAXIPLAYERBUSY);
17702 GetSession()->SendPacket(&data);
17703 return false;
17706 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
17707 return false;
17709 // taximaster case
17710 if(npc)
17712 // not let cheating with start flight mounted
17713 if(IsMounted())
17715 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17716 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
17717 GetSession()->SendPacket(&data);
17718 return false;
17721 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17723 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17724 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
17725 GetSession()->SendPacket(&data);
17726 return false;
17729 // 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
17730 if(IsNonMeleeSpellCasted(false))
17732 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17733 data << uint32(ERR_TAXIPLAYERBUSY);
17734 GetSession()->SendPacket(&data);
17735 return false;
17738 // cast case or scripted call case
17739 else
17741 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
17743 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17744 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
17746 if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
17747 if (spell->m_spellInfo->Id != spellid)
17748 InterruptSpell(CURRENT_GENERIC_SPELL,false);
17750 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
17752 if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
17753 if (spell->m_spellInfo->Id != spellid)
17754 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
17757 uint32 sourcenode = nodes[0];
17759 // starting node too far away (cheat?)
17760 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
17761 if (!node)
17763 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17764 data << uint32(ERR_TAXINOSUCHPATH);
17765 GetSession()->SendPacket(&data);
17766 return false;
17769 // check node starting pos data set case if provided
17770 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
17772 if (node->map_id != GetMapId() ||
17773 (node->x - GetPositionX())*(node->x - GetPositionX())+
17774 (node->y - GetPositionY())*(node->y - GetPositionY())+
17775 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
17776 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
17778 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17779 data << uint32(ERR_TAXITOOFARAWAY);
17780 GetSession()->SendPacket(&data);
17781 return false;
17784 // node must have pos if taxi master case (npc != NULL)
17785 else if (npc)
17787 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17788 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17789 GetSession()->SendPacket(&data);
17790 return false;
17793 // Prepare to flight start now
17795 // stop combat at start taxi flight if any
17796 CombatStop();
17798 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17799 TradeCancel(true);
17801 // clean not finished taxi path if any
17802 m_taxi.ClearTaxiDestinations();
17804 // 0 element current node
17805 m_taxi.AddTaxiDestination(sourcenode);
17807 // fill destinations path tail
17808 uint32 sourcepath = 0;
17809 uint32 totalcost = 0;
17811 uint32 prevnode = sourcenode;
17812 uint32 lastnode = 0;
17814 for(uint32 i = 1; i < nodes.size(); ++i)
17816 uint32 path, cost;
17818 lastnode = nodes[i];
17819 sObjectMgr.GetTaxiPath(prevnode, lastnode, path, cost);
17821 if(!path)
17823 m_taxi.ClearTaxiDestinations();
17824 return false;
17827 totalcost += cost;
17829 if(prevnode == sourcenode)
17830 sourcepath = path;
17832 m_taxi.AddTaxiDestination(lastnode);
17834 prevnode = lastnode;
17837 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
17838 uint32 mount_display_id = sObjectMgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
17840 // in spell case allow 0 model
17841 if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
17843 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17844 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17845 GetSession()->SendPacket(&data);
17846 m_taxi.ClearTaxiDestinations();
17847 return false;
17850 uint32 money = GetMoney();
17852 if (npc)
17853 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17855 if(money < totalcost)
17857 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17858 data << uint32(ERR_TAXINOTENOUGHMONEY);
17859 GetSession()->SendPacket(&data);
17860 m_taxi.ClearTaxiDestinations();
17861 return false;
17864 //Checks and preparations done, DO FLIGHT
17865 ModifyMoney(-(int32)totalcost);
17866 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
17867 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
17869 // prevent stealth flight
17870 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17872 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17873 data << uint32(ERR_TAXIOK);
17874 GetSession()->SendPacket(&data);
17876 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17878 GetSession()->SendDoFlight(mount_display_id, sourcepath);
17880 return true;
17883 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
17885 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
17886 if(!entry)
17887 return false;
17889 std::vector<uint32> nodes;
17891 nodes.resize(2);
17892 nodes[0] = entry->from;
17893 nodes[1] = entry->to;
17895 return ActivateTaxiPathTo(nodes,NULL,spellid);
17898 void Player::ContinueTaxiFlight()
17900 uint32 sourceNode = m_taxi.GetTaxiSource();
17901 if (!sourceNode)
17902 return;
17904 sLog.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
17906 uint32 mountDisplayId = sObjectMgr.GetTaxiMountDisplayId(sourceNode, GetTeam(),true);
17907 uint32 path = m_taxi.GetCurrentTaxiPath();
17909 // search appropriate start path node
17910 uint32 startNode = 0;
17912 TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
17914 float distPrev = MAP_SIZE*MAP_SIZE;
17915 float distNext =
17916 (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
17917 (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
17918 (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
17920 for(uint32 i = 1; i < nodeList.size(); ++i)
17922 TaxiPathNode const& node = nodeList[i];
17923 TaxiPathNode const& prevNode = nodeList[i-1];
17925 // skip nodes at another map
17926 if(node.mapid != GetMapId())
17927 continue;
17929 distPrev = distNext;
17931 distNext =
17932 (node.x-GetPositionX())*(node.x-GetPositionX())+
17933 (node.y-GetPositionY())*(node.y-GetPositionY())+
17934 (node.z-GetPositionZ())*(node.z-GetPositionZ());
17936 float distNodes =
17937 (node.x-prevNode.x)*(node.x-prevNode.x)+
17938 (node.y-prevNode.y)*(node.y-prevNode.y)+
17939 (node.z-prevNode.z)*(node.z-prevNode.z);
17941 if(distNext + distPrev < distNodes)
17943 startNode = i;
17944 break;
17948 GetSession()->SendDoFlight(mountDisplayId, path, startNode);
17951 void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17953 // last check 2.0.10
17954 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17955 data << uint64(GetGUID());
17956 data << uint8(0x0); // flags (0x1, 0x2)
17957 time_t curTime = time(NULL);
17958 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17960 if (itr->second.state == PLAYERSPELL_REMOVED)
17961 continue;
17962 uint32 unSpellId = itr->first;
17963 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17964 if (!spellInfo)
17966 ASSERT(spellInfo);
17967 continue;
17970 // Not send cooldown for this spells
17971 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17972 continue;
17974 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17976 data << uint32(unSpellId);
17977 data << uint32(unTimeMs); // in m.secs
17978 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17981 GetSession()->SendPacket(&data);
17984 void Player::InitDataForForm(bool reapplyMods)
17986 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17987 if(ssEntry && ssEntry->attackSpeed)
17989 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17990 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17991 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17993 else
17994 SetRegularAttackTime();
17996 switch(m_form)
17998 case FORM_CAT:
18000 if(getPowerType()!=POWER_ENERGY)
18001 setPowerType(POWER_ENERGY);
18002 break;
18004 case FORM_BEAR:
18005 case FORM_DIREBEAR:
18007 if(getPowerType()!=POWER_RAGE)
18008 setPowerType(POWER_RAGE);
18009 break;
18011 default: // 0, for example
18013 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
18014 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
18015 setPowerType(Powers(cEntry->powerType));
18016 break;
18020 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
18021 if (!reapplyMods)
18022 UpdateEquipSpellsAtFormChange();
18024 UpdateAttackPowerAndDamage();
18025 UpdateAttackPowerAndDamage(true);
18028 void Player::InitDisplayIds()
18030 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
18031 if(!info)
18033 sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
18034 return;
18037 uint8 gender = getGender();
18038 switch(gender)
18040 case GENDER_FEMALE:
18041 SetDisplayId(info->displayId_f );
18042 SetNativeDisplayId(info->displayId_f );
18043 break;
18044 case GENDER_MALE:
18045 SetDisplayId(info->displayId_m );
18046 SetNativeDisplayId(info->displayId_m );
18047 break;
18048 default:
18049 sLog.outError("Invalid gender %u for player",gender);
18050 return;
18054 // Return true is the bought item has a max count to force refresh of window by caller
18055 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot)
18057 // cheating attempt
18058 if (count < 1) count = 1;
18060 if (!isAlive())
18061 return false;
18063 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
18064 if (!pProto)
18066 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
18067 return false;
18070 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
18071 if (!pCreature)
18073 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
18074 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
18075 return false;
18078 VendorItemData const* vItems = pCreature->GetVendorItems();
18079 if(!vItems || vItems->Empty())
18081 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
18082 return false;
18085 size_t vendor_slot = vItems->FindItemSlot(item);
18086 if (vendor_slot >= vItems->GetItemCount())
18088 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
18089 return false;
18092 VendorItem const* crItem = vItems->m_items[vendor_slot];
18094 // check current item amount if it limited
18095 if (crItem->maxcount != 0)
18097 if (pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
18099 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
18100 return false;
18104 if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
18106 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
18107 return false;
18110 if (crItem->ExtendedCost)
18112 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
18113 if (!iece)
18115 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
18116 return false;
18119 // honor points price
18120 if (GetHonorPoints() < (iece->reqhonorpoints * count))
18122 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
18123 return false;
18126 // arena points price
18127 if (GetArenaPoints() < (iece->reqarenapoints * count))
18129 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
18130 return false;
18133 // item base price
18134 for (uint8 i = 0; i < 5; ++i)
18136 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
18138 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
18139 return false;
18143 // check for personal arena rating requirement
18144 if( GetMaxPersonalArenaRatingRequirement(iece->reqarenaslot) < iece->reqpersonalarenarating )
18146 // probably not the proper equip err
18147 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
18148 return false;
18152 uint32 price = pProto->BuyPrice * count;
18154 // reputation discount
18155 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
18157 if (GetMoney() < price)
18159 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
18160 return false;
18163 if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
18165 ItemPosCountVec dest;
18166 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
18167 if (msg != EQUIP_ERR_OK)
18169 SendEquipError( msg, NULL, NULL, item );
18170 return false;
18173 ModifyMoney( -(int32)price );
18174 if (crItem->ExtendedCost) // case for new honor system
18176 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
18177 if (iece->reqhonorpoints)
18178 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
18179 if (iece->reqarenapoints)
18180 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
18181 for (uint8 i = 0; i < 5; ++i)
18183 if (iece->reqitem[i])
18184 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
18188 if (Item *it = StoreNewItem( dest, item, true ))
18190 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
18192 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
18193 data << uint64(pCreature->GetGUID());
18194 data << uint32(vendor_slot+1); // numbered from 1 at client
18195 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
18196 data << uint32(count);
18197 GetSession()->SendPacket(&data);
18199 SendNewItem(it, pProto->BuyCount*count, true, false, false);
18202 else if (IsEquipmentPos(bag, slot))
18204 if (pProto->BuyCount * count != 1)
18206 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
18207 return false;
18210 uint16 dest;
18211 uint8 msg = CanEquipNewItem( slot, dest, item, false );
18212 if (msg != EQUIP_ERR_OK)
18214 SendEquipError( msg, NULL, NULL, item );
18215 return false;
18218 ModifyMoney( -(int32)price );
18219 if (crItem->ExtendedCost) // case for new honor system
18221 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
18222 if (iece->reqhonorpoints)
18223 ModifyHonorPoints( - int32(iece->reqhonorpoints));
18224 if (iece->reqarenapoints)
18225 ModifyArenaPoints( - int32(iece->reqarenapoints));
18226 for (uint8 i = 0; i < 5; ++i)
18228 if(iece->reqitem[i])
18229 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
18233 if (Item *it = EquipNewItem( dest, item, true ))
18235 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
18237 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
18238 data << uint64(pCreature->GetGUID());
18239 data << uint32(vendor_slot + 1); // numbered from 1 at client
18240 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
18241 data << uint32(count);
18242 GetSession()->SendPacket(&data);
18244 SendNewItem(it, pProto->BuyCount*count, true, false, false);
18246 AutoUnequipOffhandIfNeed();
18249 else
18251 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
18252 return false;
18255 return crItem->maxcount != 0;
18258 uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot)
18260 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
18261 // the personal rating of the arena team must match the required limit as well
18262 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
18263 uint32 max_personal_rating = 0;
18264 for(int i = minarenaslot; i < MAX_ARENA_SLOT; ++i)
18266 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(GetArenaTeamId(i)))
18268 uint32 p_rating = GetArenaPersonalRating(i);
18269 uint32 t_rating = at->GetRating();
18270 p_rating = p_rating < t_rating ? p_rating : t_rating;
18271 if(max_personal_rating < p_rating)
18272 max_personal_rating = p_rating;
18275 return max_personal_rating;
18278 void Player::UpdateHomebindTime(uint32 time)
18280 // GMs never get homebind timer online
18281 if (m_InstanceValid || isGameMaster())
18283 if(m_HomebindTimer) // instance valid, but timer not reset
18285 // hide reminder
18286 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
18287 data << uint32(0);
18288 data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
18289 GetSession()->SendPacket(&data);
18291 // instance is valid, reset homebind timer
18292 m_HomebindTimer = 0;
18294 else if (m_HomebindTimer > 0)
18296 if (time >= m_HomebindTimer)
18298 // teleport to nearest graveyard
18299 RepopAtGraveyard();
18301 else
18302 m_HomebindTimer -= time;
18304 else
18306 // instance is invalid, start homebind timer
18307 m_HomebindTimer = 60000;
18308 // send message to player
18309 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
18310 data << uint32(m_HomebindTimer);
18311 data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
18312 GetSession()->SendPacket(&data);
18313 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
18317 void Player::UpdatePvP(bool state, bool ovrride)
18319 if(!state || ovrride)
18321 SetPvP(state);
18322 pvpInfo.endTimer = 0;
18324 else
18326 if(pvpInfo.endTimer != 0)
18327 pvpInfo.endTimer = time(NULL);
18328 else
18329 SetPvP(state);
18333 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
18335 // init cooldown values
18336 uint32 cat = 0;
18337 int32 rec = -1;
18338 int32 catrec = -1;
18340 // some special item spells without correct cooldown in SpellInfo
18341 // cooldown information stored in item prototype
18342 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
18344 if(itemId)
18346 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
18348 for(int idx = 0; idx < 5; ++idx)
18350 if(proto->Spells[idx].SpellId == spellInfo->Id)
18352 cat = proto->Spells[idx].SpellCategory;
18353 rec = proto->Spells[idx].SpellCooldown;
18354 catrec = proto->Spells[idx].SpellCategoryCooldown;
18355 break;
18361 // if no cooldown found above then base at DBC data
18362 if(rec < 0 && catrec < 0)
18364 cat = spellInfo->Category;
18365 rec = spellInfo->RecoveryTime;
18366 catrec = spellInfo->CategoryRecoveryTime;
18369 time_t curTime = time(NULL);
18371 time_t catrecTime;
18372 time_t recTime;
18374 // overwrite time for selected category
18375 if(infinityCooldown)
18377 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
18378 // but not allow ignore until reset or re-login
18379 catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
18380 recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
18382 else
18384 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
18385 // prevent 0 cooldowns set by another way
18386 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
18387 rec = GetAttackTime(RANGED_ATTACK);
18389 // Now we have cooldown data (if found any), time to apply mods
18390 if(rec > 0)
18391 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
18393 if(catrec > 0)
18394 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
18396 // replace negative cooldowns by 0
18397 if (rec < 0) rec = 0;
18398 if (catrec < 0) catrec = 0;
18400 // no cooldown after applying spell mods
18401 if( rec == 0 && catrec == 0)
18402 return;
18404 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
18405 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
18408 // self spell cooldown
18409 if(recTime > 0)
18410 AddSpellCooldown(spellInfo->Id, itemId, recTime);
18412 // category spells
18413 if (cat && catrec > 0)
18415 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
18416 if(i_scstore != sSpellCategoryStore.end())
18418 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
18420 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
18421 continue;
18423 AddSpellCooldown(*i_scset, itemId, catrecTime);
18429 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
18431 SpellCooldown sc;
18432 sc.end = end_time;
18433 sc.itemid = itemid;
18434 m_spellCooldowns[spellid] = sc;
18437 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
18439 // start cooldowns at server side, if any
18440 AddSpellAndCategoryCooldowns(spellInfo, itemId, spell);
18442 // Send activate cooldown timer (possible 0) at client side
18443 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
18444 data << uint32(spellInfo->Id);
18445 data << uint64(GetGUID());
18446 SendDirectMessage(&data);
18449 void Player::UpdatePotionCooldown(Spell* spell)
18451 // no potion used i combat or still in combat
18452 if(!m_lastPotionId || isInCombat())
18453 return;
18455 // Call not from spell cast, send cooldown event for item spells if no in combat
18456 if(!spell)
18458 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
18459 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
18460 for(int idx = 0; idx < 5; ++idx)
18461 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
18462 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
18463 SendCooldownEvent(spellInfo,m_lastPotionId);
18465 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
18466 else
18467 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
18469 m_lastPotionId = 0;
18472 //slot to be excluded while counting
18473 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
18475 if(!enchantmentcondition)
18476 return true;
18478 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
18480 if(!Condition)
18481 return true;
18483 uint8 curcount[4] = {0, 0, 0, 0};
18485 //counting current equipped gem colors
18486 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
18488 if(i == slot)
18489 continue;
18490 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
18491 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
18493 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18495 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18496 if(!enchant_id)
18497 continue;
18499 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18500 if(!enchantEntry)
18501 continue;
18503 uint32 gemid = enchantEntry->GemID;
18504 if(!gemid)
18505 continue;
18507 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
18508 if(!gemProto)
18509 continue;
18511 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
18512 if(!gemProperty)
18513 continue;
18515 uint8 GemColor = gemProperty->color;
18517 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
18519 if(tmpcolormask & GemColor)
18520 ++curcount[b];
18526 bool activate = true;
18528 for(int i = 0; i < 5; ++i)
18530 if(!Condition->Color[i])
18531 continue;
18533 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
18535 // if have <CompareColor> use them as count, else use <value> from Condition
18536 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
18538 switch(Condition->Comparator[i])
18540 case 2: // requires less <color> than (<value> || <comparecolor>) gems
18541 activate &= (_cur_gem < _cmp_gem) ? true : false;
18542 break;
18543 case 3: // requires more <color> than (<value> || <comparecolor>) gems
18544 activate &= (_cur_gem > _cmp_gem) ? true : false;
18545 break;
18546 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
18547 activate &= (_cur_gem >= _cmp_gem) ? true : false;
18548 break;
18552 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");
18554 return activate;
18557 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
18559 //cycle all equipped items
18560 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18562 //enchants for the slot being socketed are handled by Player::ApplyItemMods
18563 if(slot == exceptslot)
18564 continue;
18566 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18568 if(!pItem || !pItem->GetProto()->Socket[0].Color)
18569 continue;
18571 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18573 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18574 if(!enchant_id)
18575 continue;
18577 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18578 if(!enchantEntry)
18579 continue;
18581 uint32 condition = enchantEntry->EnchantmentCondition;
18582 if(condition)
18584 //was enchant active with/without item?
18585 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
18586 //should it now be?
18587 if(wasactive != EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
18589 // ignore item gem conditions
18590 //if state changed, (dis)apply enchant
18591 ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true);
18598 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
18599 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
18601 //cycle all equipped items
18602 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18604 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
18605 if(slot == exceptslot)
18606 continue;
18608 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18610 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
18611 continue;
18613 //cycle all (gem)enchants
18614 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18616 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18617 if(!enchant_id) //if no enchant go to next enchant(slot)
18618 continue;
18620 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18621 if(!enchantEntry)
18622 continue;
18624 //only metagems to be (de)activated, so only enchants with condition
18625 uint32 condition = enchantEntry->EnchantmentCondition;
18626 if(condition)
18627 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
18632 void Player::SetBattleGroundEntryPoint()
18634 // Taxi path store
18635 if (!m_taxi.empty())
18637 m_bgData.mountSpell = 0;
18638 m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
18639 m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
18641 // On taxi we don't need check for dungeon
18642 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18643 return;
18645 else
18647 m_bgData.ClearTaxiPath();
18649 // Mount spell id storing
18650 if (IsMounted())
18652 AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED);
18653 if (!auras.empty())
18654 m_bgData.mountSpell = (*auras.begin())->GetId();
18656 else
18657 m_bgData.mountSpell = 0;
18659 // If map is dungeon find linked graveyard
18660 if(GetMap()->IsDungeon())
18662 if (const WorldSafeLocsEntry* entry = sObjectMgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
18664 m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
18665 return;
18667 else
18668 sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
18670 // If new entry point is not BG or arena set it
18671 else if (!GetMap()->IsBattleGroundOrArena())
18673 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18674 return;
18678 // In error cases use homebind position
18679 m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
18682 void Player::LeaveBattleground(bool teleportToEntryPoint)
18684 if(BattleGround *bg = GetBattleGround())
18686 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
18688 // call after remove to be sure that player resurrected for correct cast
18689 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BOOL_BATTLEGROUND_CAST_DESERTER) )
18691 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
18693 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
18694 if(IsBeingTeleportedFar())
18696 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
18697 return;
18700 CastSpell(this, 26013, true); // Deserter
18706 bool Player::CanJoinToBattleground() const
18708 // check Deserter debuff
18709 if(GetDummyAura(26013))
18710 return false;
18712 return true;
18715 bool Player::CanReportAfkDueToLimit()
18717 // a player can complain about 15 people per 5 minutes
18718 if(m_bgData.bgAfkReportedCount++ >= 15)
18719 return false;
18721 return true;
18724 ///This player has been blamed to be inactive in a battleground
18725 void Player::ReportedAfkBy(Player* reporter)
18727 BattleGround *bg = GetBattleGround();
18728 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
18729 return;
18731 // check if player has 'Idle' or 'Inactive' debuff
18732 if(m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680, EFFECT_INDEX_0) && !HasAura(43681, EFFECT_INDEX_0) && reporter->CanReportAfkDueToLimit())
18734 m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
18735 // 3 players have to complain to apply debuff
18736 if(m_bgData.bgAfkReporter.size() >= 3)
18738 // cast 'Idle' spell
18739 CastSpell(this, 43680, true);
18740 m_bgData.bgAfkReporter.clear();
18745 WorldObject const* Player::GetViewPoint() const
18747 if(uint64 far_sight = GetFarSight())
18749 WorldObject const* viewPoint = GetMap()->GetWorldObject(far_sight);
18750 return viewPoint ? viewPoint : this; // always expected not NULL
18752 else
18753 return this;
18756 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
18758 // gamemaster in GM mode see all, including ghosts
18759 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
18760 return true;
18762 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
18763 if (InBattleGround())
18765 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
18766 return false;
18767 return true;
18770 // Live player see live player or dead player with not realized corpse
18771 if(pl->isAlive() || pl->m_deathTimer > 0)
18773 return isAlive() || m_deathTimer > 0;
18776 // Ghost see other friendly ghosts, that's for sure
18777 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
18778 return true;
18780 // Dead player see live players near own corpse
18781 if(isAlive())
18783 Corpse *corpse = pl->GetCorpse();
18784 if(corpse)
18786 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
18787 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO)))
18788 return true;
18792 // and not see any other
18793 return false;
18796 bool Player::IsVisibleGloballyFor( Player* u ) const
18798 if(!u)
18799 return false;
18801 // Always can see self
18802 if (u==this)
18803 return true;
18805 // Visible units, always are visible for all players
18806 if (GetVisibility() == VISIBILITY_ON)
18807 return true;
18809 // GMs are visible for higher gms (or players are visible for gms)
18810 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
18811 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
18813 // non faction visibility non-breakable for non-GMs
18814 if (GetVisibility() == VISIBILITY_OFF)
18815 return false;
18817 // non-gm stealth/invisibility not hide from global player lists
18818 return true;
18821 template<class T>
18822 inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/)
18826 template<>
18827 inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
18829 if (p->GetPetGUID()==t->GetGUID() && ((Creature*)t)->isPet())
18830 ((Pet*)t)->Remove(PET_SAVE_NOT_IN_SLOT, true);
18833 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target)
18835 if(HaveAtClient(target))
18837 if(!target->isVisibleForInState(this, viewPoint, true))
18839 if (target->GetTypeId()==TYPEID_UNIT)
18840 BeforeVisibilityDestroy<Creature>((Creature*)target,this);
18842 target->DestroyForPlayer(this);
18843 m_clientGUIDs.erase(target->GetGUID());
18845 #ifdef MANGOS_DEBUG
18846 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18847 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18848 #endif
18851 else
18853 if(target->isVisibleForInState(this, viewPoint, false))
18855 target->SendCreateUpdateToPlayer(this);
18856 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
18857 m_clientGUIDs.insert(target->GetGUID());
18859 #ifdef MANGOS_DEBUG
18860 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18861 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18862 #endif
18864 // target aura duration for caster show only if target exist at caster client
18865 // send data at target visibility change (adding to client)
18866 if(target!=this && target->isType(TYPEMASK_UNIT))
18867 SendAurasForTarget((Unit*)target);
18869 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
18870 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18875 template<class T>
18876 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
18878 s64.insert(target->GetGUID());
18881 template<>
18882 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
18884 if(!target->IsTransport())
18885 s64.insert(target->GetGUID());
18888 template<class T>
18889 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, UpdateDataMapType& /*data_updates*/, std::set<WorldObject*>& visibleNow)
18891 if(HaveAtClient(target))
18893 if(!target->isVisibleForInState(this,viewPoint,true))
18895 BeforeVisibilityDestroy<T>(target,this);
18897 target->BuildOutOfRangeUpdateBlock(&data);
18898 m_clientGUIDs.erase(target->GetGUID());
18900 #ifdef MANGOS_DEBUG
18901 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18902 sLog.outDebug("Object %u (Type: %u, Entry: %u) is out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),target->GetEntry(),GetGUIDLow(),GetDistance(target));
18903 #endif
18906 else
18908 if(target->isVisibleForInState(this,viewPoint,false))
18910 visibleNow.insert(target);
18911 target->BuildCreateUpdateBlockForPlayer(&data, this);
18912 UpdateVisibilityOf_helper(m_clientGUIDs,target);
18914 #ifdef MANGOS_DEBUG
18915 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18916 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));
18917 #endif
18922 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18923 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18924 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18925 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18926 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18928 void Player::InitPrimaryProfessions()
18930 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL));
18933 void Player::SendComboPoints()
18935 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
18936 if (combotarget)
18938 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
18939 data.append(combotarget->GetPackGUID());
18940 data << uint8(m_comboPoints);
18941 GetSession()->SendPacket(&data);
18945 void Player::AddComboPoints(Unit* target, int8 count)
18947 if(!count)
18948 return;
18950 // without combo points lost (duration checked in aura)
18951 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18953 if(target->GetGUID() == m_comboTarget)
18955 m_comboPoints += count;
18957 else
18959 if(m_comboTarget)
18960 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
18961 target2->RemoveComboPointHolder(GetGUIDLow());
18963 m_comboTarget = target->GetGUID();
18964 m_comboPoints = count;
18966 target->AddComboPointHolder(GetGUIDLow());
18969 if (m_comboPoints > 5) m_comboPoints = 5;
18970 if (m_comboPoints < 0) m_comboPoints = 0;
18972 SendComboPoints();
18975 void Player::ClearComboPoints()
18977 if(!m_comboTarget)
18978 return;
18980 // without combopoints lost (duration checked in aura)
18981 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18983 m_comboPoints = 0;
18985 SendComboPoints();
18987 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18988 target->RemoveComboPointHolder(GetGUIDLow());
18990 m_comboTarget = 0;
18993 void Player::SetGroup(Group *group, int8 subgroup)
18995 if(group == NULL)
18996 m_group.unlink();
18997 else
18999 // never use SetGroup without a subgroup unless you specify NULL for group
19000 assert(subgroup >= 0);
19001 m_group.link(group, this);
19002 m_group.setSubGroup((uint8)subgroup);
19006 void Player::SendInitialPacketsBeforeAddToMap()
19008 GetSocial()->SendSocialList();
19010 // Homebind
19011 WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
19012 data << m_homebindX << m_homebindY << m_homebindZ;
19013 data << (uint32) m_homebindMapId;
19014 data << (uint32) m_homebindAreaId;
19015 GetSession()->SendPacket(&data);
19017 // SMSG_SET_PROFICIENCY
19018 // SMSG_SET_PCT_SPELL_MODIFIER
19019 // SMSG_SET_FLAT_SPELL_MODIFIER
19021 SendTalentsInfoData(false);
19023 data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4+4);
19024 data << uint32(0);
19025 data << uint32(0);
19026 GetSession()->SendPacket(&data);
19028 SendInitialSpells();
19030 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
19031 data << uint32(0); // count, for(count) uint32;
19032 GetSession()->SendPacket(&data);
19034 SendInitialActionButtons();
19035 m_reputationMgr.SendInitialReputations();
19037 if(!isAlive())
19038 SendCorpseReclaimDelay(true);
19040 SendInitWorldStates(GetZoneId(), GetAreaId());
19042 SendEquipmentSetList();
19044 m_achievementMgr.SendAllAchievementData();
19046 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
19047 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
19048 data << (float)0.01666667f; // game speed
19049 data << uint32(0); // added in 3.1.2
19050 GetSession()->SendPacket( &data );
19052 // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
19053 // SMSG_PET_GUIDS
19054 // SMSG_POWER_UPDATE
19056 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
19057 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || HasAuraType(SPELL_AURA_FLY) || isInFlight())
19058 m_movementInfo.AddMovementFlag(MOVEFLAG_FLYING);
19060 m_mover = this;
19063 void Player::SendInitialPacketsAfterAddToMap()
19065 // update zone
19066 uint32 newzone, newarea;
19067 GetZoneAndAreaId(newzone,newarea);
19068 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
19070 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
19071 data << uint32(0x00000000); // on blizz it increments periodically
19072 GetSession()->SendPacket(&data);
19074 CastSpell(this, 836, true); // LOGINEFFECT
19076 // set some aura effects that send packet to player client after add player to map
19077 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
19078 // same auras state lost at far teleport, send it one more time in this case also
19079 static const AuraType auratypes[] =
19081 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
19082 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
19083 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
19085 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
19087 Unit::AuraList const& auraList = GetAurasByType(*itr);
19088 if(!auraList.empty())
19089 auraList.front()->ApplyModifier(true,true);
19092 if(HasAuraType(SPELL_AURA_MOD_STUN))
19093 SetMovement(MOVE_ROOT);
19095 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
19096 if(HasAuraType(SPELL_AURA_MOD_ROOT))
19098 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
19099 data2.append(GetPackGUID());
19100 data2 << (uint32)2;
19101 SendMessageToSet(&data2,true);
19104 SendAurasForTarget(this);
19105 SendEnchantmentDurations(); // must be after add to map
19106 SendItemDurations(); // must be after add to map
19109 void Player::SendUpdateToOutOfRangeGroupMembers()
19111 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
19112 return;
19113 if(Group* group = GetGroup())
19114 group->UpdatePlayerOutOfRange(this);
19116 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
19117 m_auraUpdateMask = 0;
19118 if(Pet *pet = GetPet())
19119 pet->ResetAuraUpdateMask();
19122 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
19124 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
19125 data << uint32(mapid);
19126 data << uint8(reason); // transfer abort reason
19127 switch(reason)
19129 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
19130 case TRANSFER_ABORT_DIFFICULTY:
19131 case TRANSFER_ABORT_UNIQUE_MESSAGE:
19132 data << uint8(arg);
19133 break;
19135 GetSession()->SendPacket(&data);
19138 void Player::SendInstanceResetWarning( uint32 mapid, Difficulty difficulty, uint32 time )
19140 // type of warning, based on the time remaining until reset
19141 uint32 type;
19142 if(time > 3600)
19143 type = RAID_INSTANCE_WELCOME;
19144 else if(time > 900 && time <= 3600)
19145 type = RAID_INSTANCE_WARNING_HOURS;
19146 else if(time > 300 && time <= 900)
19147 type = RAID_INSTANCE_WARNING_MIN;
19148 else
19149 type = RAID_INSTANCE_WARNING_MIN_SOON;
19151 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
19152 data << uint32(type);
19153 data << uint32(mapid);
19154 data << uint32(difficulty); // difficulty
19155 data << uint32(time);
19156 if(type == RAID_INSTANCE_WELCOME)
19158 data << uint8(0); // is your (1)
19159 data << uint8(0); // is extended (1), ignored if prev field is 0
19161 GetSession()->SendPacket(&data);
19164 void Player::ApplyEquipCooldown( Item * pItem )
19166 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
19168 _Spell const& spellData = pItem->GetProto()->Spells[i];
19170 // no spell
19171 if( !spellData.SpellId )
19172 continue;
19174 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
19175 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
19176 continue;
19178 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
19180 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
19181 data << pItem->GetGUID();
19182 data << uint32(spellData.SpellId);
19183 GetSession()->SendPacket(&data);
19187 void Player::resetSpells()
19189 // not need after this call
19190 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
19191 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
19193 // make full copy of map (spells removed and marked as deleted at another spell remove
19194 // and we can't use original map for safe iterative with visit each spell at loop end
19195 PlayerSpellMap smap = GetSpellMap();
19197 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
19198 removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
19200 learnDefaultSpells();
19201 learnQuestRewardedSpells();
19204 void Player::learnDefaultSpells()
19206 // learn default race/class spells
19207 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(),getClass());
19208 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
19210 uint32 tspell = *itr;
19211 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
19212 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
19213 addSpell(tspell,true,true,true,false);
19214 else // but send in normal spell in game learn case
19215 learnSpell(tspell,true);
19219 void Player::learnQuestRewardedSpells(Quest const* quest)
19221 uint32 spell_id = quest->GetRewSpellCast();
19223 // skip quests without rewarded spell
19224 if( !spell_id )
19225 return;
19227 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
19228 if(!spellInfo)
19229 return;
19231 // check learned spells state
19232 bool found = false;
19233 for(int i=0; i < MAX_EFFECT_INDEX; ++i)
19235 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
19237 found = true;
19238 break;
19242 // skip quests with not teaching spell or already known spell
19243 if(!found)
19244 return;
19246 // prevent learn non first rank unknown profession and second specialization for same profession)
19247 uint32 learned_0 = spellInfo->EffectTriggerSpell[EFFECT_INDEX_0];
19248 if( sSpellMgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
19250 // not have first rank learned (unlearned prof?)
19251 uint32 first_spell = sSpellMgr.GetFirstSpellInChain(learned_0);
19252 if( !HasSpell(first_spell) )
19253 return;
19255 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
19256 if(!learnedInfo)
19257 return;
19259 // specialization
19260 if (learnedInfo->Effect[EFFECT_INDEX_0] == SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[EFFECT_INDEX_1] == 0)
19262 // search other specialization for same prof
19263 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
19265 if(itr->second.state == PLAYERSPELL_REMOVED || itr->first==learned_0)
19266 continue;
19268 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
19269 if(!itrInfo)
19270 return;
19272 // compare only specializations
19273 if (itrInfo->Effect[EFFECT_INDEX_0] != SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[EFFECT_INDEX_1] != 0)
19274 continue;
19276 // compare same chain spells
19277 if(sSpellMgr.GetFirstSpellInChain(itr->first) != first_spell)
19278 continue;
19280 // now we have 2 specialization, learn possible only if found is lesser specialization rank
19281 if(!sSpellMgr.IsHighRankOfSpell(learned_0,itr->first))
19282 return;
19287 CastSpell( this, spell_id, true);
19290 void Player::learnQuestRewardedSpells()
19292 // learn spells received from quest completing
19293 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
19295 // skip no rewarded quests
19296 if(!itr->second.m_rewarded)
19297 continue;
19299 Quest const* quest = sObjectMgr.GetQuestTemplate(itr->first);
19300 if( !quest )
19301 continue;
19303 learnQuestRewardedSpells(quest);
19307 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
19309 uint32 raceMask = getRaceMask();
19310 uint32 classMask = getClassMask();
19311 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
19313 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
19314 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
19315 continue;
19316 // Check race if set
19317 if (pAbility->racemask && !(pAbility->racemask & raceMask))
19318 continue;
19319 // Check class if set
19320 if (pAbility->classmask && !(pAbility->classmask & classMask))
19321 continue;
19323 if (sSpellStore.LookupEntry(pAbility->spellId))
19325 // need unlearn spell
19326 if (skill_value < pAbility->req_skill_value)
19327 removeSpell(pAbility->spellId);
19328 // need learn
19329 else if (!IsInWorld())
19330 addSpell(pAbility->spellId,true,true,true,false);
19331 else
19332 learnSpell(pAbility->spellId,true);
19337 void Player::SendAurasForTarget(Unit *target)
19339 if(target->GetVisibleAuras()->empty()) // speedup things
19340 return;
19342 WorldPacket data(SMSG_AURA_UPDATE_ALL);
19343 data.append(target->GetPackGUID());
19345 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
19346 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
19348 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
19350 if(Aura *aura = target->GetAura(itr->second, SpellEffectIndex(j)))
19352 data << uint8(aura->GetAuraSlot());
19353 data << uint32(aura->GetId());
19355 if(aura->GetId())
19357 uint8 auraFlags = aura->GetAuraFlags();
19358 // flags
19359 data << uint8(auraFlags);
19360 // level
19361 data << uint8(aura->GetAuraLevel());
19362 // charges
19363 if (aura->GetAuraCharges())
19364 data << uint8(aura->GetAuraCharges() * aura->GetStackAmount());
19365 else
19366 data << uint8(aura->GetStackAmount());
19368 if(!(auraFlags & AFLAG_NOT_CASTER))
19370 data << uint8(0); // packed GUID of someone (caster?)
19373 if(auraFlags & AFLAG_DURATION) // include aura duration
19375 data << uint32(aura->GetAuraMaxDuration());
19376 data << uint32(aura->GetAuraDuration());
19379 break;
19384 GetSession()->SendPacket(&data);
19387 void Player::SetDailyQuestStatus( uint32 quest_id )
19389 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19391 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
19393 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
19394 m_lastDailyQuestTime = time(NULL); // last daily quest time
19395 m_DailyQuestChanged = true;
19396 break;
19401 void Player::ResetDailyQuestStatus()
19403 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19404 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
19406 // DB data deleted in caller
19407 m_DailyQuestChanged = false;
19408 m_lastDailyQuestTime = 0;
19411 BattleGround* Player::GetBattleGround() const
19413 if(GetBattleGroundId()==0)
19414 return NULL;
19416 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
19419 bool Player::InArena() const
19421 BattleGround *bg = GetBattleGround();
19422 if(!bg || !bg->isArena())
19423 return false;
19425 return true;
19428 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
19430 // get a template bg instead of running one
19431 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
19432 if(!bg)
19433 return false;
19435 // limit check leel to dbc compatible level range
19436 uint32 level = getLevel();
19437 if (level > DEFAULT_MAX_LEVEL)
19438 level = DEFAULT_MAX_LEVEL;
19440 if(level < bg->GetMinLevel() || level > bg->GetMaxLevel())
19441 return false;
19443 return true;
19446 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
19448 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
19449 if(!vendor_faction || !vendor_faction->faction)
19450 return 1.0f;
19452 ReputationRank rank = GetReputationRank(vendor_faction->faction);
19453 if(rank <= REP_NEUTRAL)
19454 return 1.0f;
19456 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
19459 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
19461 uint32 racemask = getRaceMask();
19462 uint32 classmask = getClassMask();
19464 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
19465 if (bounds.first==bounds.second)
19466 return true;
19468 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
19470 // skip wrong race skills
19471 if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
19472 continue;
19474 // skip wrong class skills
19475 if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
19476 continue;
19478 return true;
19481 return false;
19484 bool Player::HasQuestForGO(int32 GOId) const
19486 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
19488 uint32 questid = GetQuestSlotQuestId(i);
19489 if ( questid == 0 )
19490 continue;
19492 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
19493 if(qs_itr == mQuestStatus.end())
19494 continue;
19496 QuestStatusData const& qs = qs_itr->second;
19498 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
19500 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
19501 if(!qinfo)
19502 continue;
19504 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
19505 continue;
19507 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
19509 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
19510 continue;
19512 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
19513 return true;
19517 return false;
19520 void Player::UpdateForQuestWorldObjects()
19522 if(m_clientGUIDs.empty())
19523 return;
19525 UpdateData udata;
19526 WorldPacket packet;
19527 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
19529 if(IS_GAMEOBJECT_GUID(*itr))
19531 GameObject *obj = GetMap()->GetGameObject(*itr);
19532 if(obj)
19533 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
19535 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
19537 Creature *obj = GetMap()->GetCreatureOrPetOrVehicle(*itr);
19538 if(!obj)
19539 continue;
19541 // check if this unit requires quest specific flags
19542 if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
19543 continue;
19545 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(obj->GetEntry());
19546 for(SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
19548 if(_itr->second.questStart || _itr->second.questEnd)
19550 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
19551 break;
19556 udata.BuildPacket(&packet);
19557 GetSession()->SendPacket(&packet);
19560 void Player::SummonIfPossible(bool agree)
19562 if(!agree)
19564 m_summon_expire = 0;
19565 return;
19568 // expire and auto declined
19569 if(m_summon_expire < time(NULL))
19570 return;
19572 // stop taxi flight at summon
19573 if(isInFlight())
19575 GetMotionMaster()->MovementExpired();
19576 m_taxi.ClearTaxiDestinations();
19579 // drop flag at summon
19580 // 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
19581 if(BattleGround *bg = GetBattleGround())
19582 bg->EventPlayerDroppedFlag(this);
19584 m_summon_expire = 0;
19586 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
19588 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
19591 void Player::RemoveItemDurations( Item *item )
19593 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
19595 if(*itr==item)
19597 m_itemDuration.erase(itr);
19598 break;
19603 void Player::AddItemDurations( Item *item )
19605 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
19607 m_itemDuration.push_back(item);
19608 item->SendTimeUpdate(this);
19612 void Player::AutoUnequipOffhandIfNeed()
19614 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
19615 if(!offItem)
19616 return;
19618 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
19619 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
19620 return;
19622 ItemPosCountVec off_dest;
19623 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
19624 if( off_msg == EQUIP_ERR_OK )
19626 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19627 StoreItem( off_dest, offItem, true );
19629 else
19631 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19632 CharacterDatabase.BeginTransaction();
19633 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
19634 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
19635 CharacterDatabase.CommitTransaction();
19637 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
19638 MailDraft(subject).AddItem(offItem).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
19642 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
19644 if(spellInfo->EquippedItemClass < 0)
19645 return true;
19647 // scan other equipped items for same requirements (mostly 2 daggers/etc)
19648 // for optimize check 2 used cases only
19649 switch(spellInfo->EquippedItemClass)
19651 case ITEM_CLASS_WEAPON:
19653 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
19654 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19655 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19656 return true;
19657 break;
19659 case ITEM_CLASS_ARMOR:
19661 // tabard not have dependent spells
19662 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
19663 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19664 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19665 return true;
19667 // shields can be equipped to offhand slot
19668 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
19669 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19670 return true;
19672 // ranged slot can have some armor subclasses
19673 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
19674 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19675 return true;
19677 break;
19679 default:
19680 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
19681 break;
19684 return false;
19687 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
19689 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
19690 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
19691 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
19692 return true;
19694 // Check no reagent use mask
19695 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
19696 uint32 noReagentMask_2 = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+2);
19697 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
19698 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
19699 return true;
19701 return false;
19704 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
19706 AuraMap& auras = GetAuras();
19707 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
19709 Aura* aura = itr->second;
19711 // skip passive (passive item dependent spells work in another way) and not self applied auras
19712 SpellEntry const* spellInfo = aura->GetSpellProto();
19713 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
19715 ++itr;
19716 continue;
19719 // skip if not item dependent or have alternative item
19720 if(HasItemFitToSpellReqirements(spellInfo,pItem))
19722 ++itr;
19723 continue;
19726 // no alt item, remove aura, restart check
19727 RemoveAurasDueToSpell(aura->GetId());
19728 itr = auras.begin();
19731 // currently casted spells can be dependent from item
19732 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
19733 if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
19734 if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
19735 InterruptSpell(CurrentSpellTypes(i));
19738 uint32 Player::GetResurrectionSpellId()
19740 // search priceless resurrection possibilities
19741 uint32 prio = 0;
19742 uint32 spell_id = 0;
19743 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
19744 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
19746 // Soulstone Resurrection // prio: 3 (max, non death persistent)
19747 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
19749 switch((*itr)->GetId())
19751 case 20707: spell_id = 3026; break; // rank 1
19752 case 20762: spell_id = 20758; break; // rank 2
19753 case 20763: spell_id = 20759; break; // rank 3
19754 case 20764: spell_id = 20760; break; // rank 4
19755 case 20765: spell_id = 20761; break; // rank 5
19756 case 27239: spell_id = 27240; break; // rank 6
19757 case 47883: spell_id = 47882; break; // rank 7
19758 default:
19759 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
19760 continue;
19763 prio = 3;
19765 // Twisting Nether // prio: 2 (max)
19766 else if((*itr)->GetId()==23701 && roll_chance_i(10))
19768 prio = 2;
19769 spell_id = 23700;
19773 // Reincarnation (passive spell) // prio: 1
19774 // Glyph of Renewed Life remove reagent requiremnnt
19775 if (prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasItemCount(17030,1) || HasAura(58059, EFFECT_INDEX_0)))
19776 spell_id = 21169;
19778 return spell_id;
19781 // Used in triggers for check "Only to targets that grant experience or honor" req
19782 bool Player::isHonorOrXPTarget(Unit* pVictim) const
19784 uint32 v_level = pVictim->getLevel();
19785 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
19787 // Victim level less gray level
19788 if(v_level<=k_grey)
19789 return false;
19791 if(pVictim->GetTypeId() == TYPEID_UNIT)
19793 if (((Creature*)pVictim)->isTotem() ||
19794 ((Creature*)pVictim)->isPet() ||
19795 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
19796 return false;
19798 return true;
19801 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
19803 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
19805 // prepare data for near group iteration (PvP and !PvP cases)
19806 uint32 xp = 0;
19807 bool honored_kill = false;
19809 if(Group *pGroup = GetGroup())
19811 uint32 count = 0;
19812 uint32 sum_level = 0;
19813 Player* member_with_max_level = NULL;
19814 Player* not_gray_member_with_max_level = NULL;
19816 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
19818 if(member_with_max_level)
19820 /// not get Xp in PvP or no not gray players in group
19821 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
19823 /// skip in check PvP case (for speed, not used)
19824 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
19825 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
19826 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
19828 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19830 Player* pGroupGuy = itr->getSource();
19831 if(!pGroupGuy)
19832 continue;
19834 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
19835 continue; // member (alive or dead) or his corpse at req. distance
19837 // honor can be in PvP and !PvP (racial leader) cases (for alive)
19838 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
19839 honored_kill = true;
19841 // xp and reputation only in !PvP case
19842 if(!PvP)
19844 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
19846 // if is in dungeon then all receive full reputation at kill
19847 // rewarded any alive/dead/near_corpse group member
19848 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
19850 // XP updated only for alive group member
19851 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
19852 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
19854 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
19856 pGroupGuy->GiveXP(itr_xp, pVictim);
19857 if(Pet* pet = pGroupGuy->GetPet())
19858 pet->GivePetXP(itr_xp/2);
19861 // quest objectives updated only for alive group member or dead but with not released body
19862 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19864 // normal creature (not pet/etc) can be only in !PvP case
19865 if(pVictim->GetTypeId()==TYPEID_UNIT)
19866 pGroupGuy->KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19872 else // if (!pGroup)
19874 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
19876 // honor can be in PvP and !PvP (racial leader) cases
19877 if(RewardHonor(pVictim,1))
19878 honored_kill = true;
19880 // xp and reputation only in !PvP case
19881 if(!PvP)
19883 RewardReputation(pVictim,1);
19884 GiveXP(xp, pVictim);
19886 if(Pet* pet = GetPet())
19887 pet->GivePetXP(xp);
19889 // normal creature (not pet/etc) can be only in !PvP case
19890 if(pVictim->GetTypeId()==TYPEID_UNIT)
19891 KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19894 return xp || honored_kill;
19897 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
19899 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
19901 // prepare data for near group iteration
19902 if(Group *pGroup = GetGroup())
19904 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19906 Player* pGroupGuy = itr->getSource();
19907 if(!pGroupGuy)
19908 continue;
19910 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
19911 continue; // member (alive or dead) or his corpse at req. distance
19913 // quest objectives updated only for alive group member or dead but with not released body
19914 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19915 pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
19918 else // if (!pGroup)
19919 KilledMonsterCredit(creature_id, creature_guid);
19922 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
19924 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE)))
19925 return true;
19927 if (isAlive())
19928 return false;
19930 Corpse* corpse = GetCorpse();
19931 if (!corpse)
19932 return false;
19934 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE));
19937 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
19939 Item* item = GetWeaponForAttack(attType,true,true);
19941 // unarmed only with base attack
19942 if(attType != BASE_ATTACK && !item)
19943 return 0;
19945 // weapon skill or (unarmed for base attack)
19946 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
19947 return GetBaseSkillValue(skill);
19950 void Player::ResurectUsingRequestData()
19952 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
19953 if(IS_PLAYER_GUID(m_resurrectGUID))
19954 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
19956 //we cannot resurrect player when we triggered far teleport
19957 //player will be resurrected upon teleportation
19958 if(IsBeingTeleportedFar())
19960 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
19961 return;
19964 ResurrectPlayer(0.0f,false);
19966 if(GetMaxHealth() > m_resurrectHealth)
19967 SetHealth( m_resurrectHealth );
19968 else
19969 SetHealth( GetMaxHealth() );
19971 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
19972 SetPower(POWER_MANA, m_resurrectMana );
19973 else
19974 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
19976 SetPower(POWER_RAGE, 0 );
19978 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
19980 SpawnCorpseBones();
19983 void Player::SetClientControl(Unit* target, uint8 allowMove)
19985 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
19986 data.append(target->GetPackGUID());
19987 data << uint8(allowMove);
19988 GetSession()->SendPacket(&data);
19991 void Player::UpdateZoneDependentAuras( uint32 newZone )
19993 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19994 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newZone);
19995 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19996 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
19997 if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
19998 CastSpell(this,itr->second->spellId,true);
20001 void Player::UpdateAreaDependentAuras( uint32 newArea )
20003 // remove auras from spells with area limitations
20004 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
20006 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
20007 if(sSpellMgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
20008 RemoveAura(iter);
20009 else
20010 ++iter;
20013 // some auras applied at subzone enter
20014 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newArea);
20015 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
20016 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
20017 if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
20018 CastSpell(this,itr->second->spellId,true);
20021 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
20023 if ((pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
20024 (!pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
20026 return copseReclaimDelay[0];
20029 time_t now = time(NULL);
20030 // 0..2 full period
20031 uint32 count = (now < m_deathExpireTime) ? uint32((m_deathExpireTime - now)/DEATH_EXPIRE_STEP) : 0;
20032 return copseReclaimDelay[count];
20035 void Player::UpdateCorpseReclaimDelay()
20037 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
20039 if ((pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
20040 (!pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
20041 return;
20043 time_t now = time(NULL);
20044 if(now < m_deathExpireTime)
20046 // full and partly periods 1..3
20047 uint32 count = uint32((m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1);
20048 if(count < MAX_DEATH_COUNT)
20049 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
20050 else
20051 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
20053 else
20054 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
20057 void Player::SendCorpseReclaimDelay(bool load)
20059 Corpse* corpse = GetCorpse();
20060 if(!corpse)
20061 return;
20063 uint32 delay;
20064 if(load)
20066 if(corpse->GetGhostTime() > m_deathExpireTime)
20067 return;
20069 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
20071 uint32 count;
20072 if( pvp && sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
20073 !pvp && sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
20075 count = uint32(m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
20076 if(count>=MAX_DEATH_COUNT)
20077 count = MAX_DEATH_COUNT-1;
20079 else
20080 count=0;
20082 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
20084 time_t now = time(NULL);
20085 if(now >= expected_time)
20086 return;
20088 delay = uint32(expected_time-now);
20090 else
20091 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
20093 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
20094 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
20095 data << uint32(delay*IN_MILISECONDS);
20096 GetSession()->SendPacket( &data );
20099 Player* Player::GetNextRandomRaidMember(float radius)
20101 Group *pGroup = GetGroup();
20102 if(!pGroup)
20103 return NULL;
20105 std::vector<Player*> nearMembers;
20106 nearMembers.reserve(pGroup->GetMembersCount());
20108 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
20110 Player* Target = itr->getSource();
20112 // IsHostileTo check duel and controlled by enemy
20113 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
20114 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
20115 nearMembers.push_back(Target);
20118 if (nearMembers.empty())
20119 return NULL;
20121 uint32 randTarget = urand(0,nearMembers.size()-1);
20122 return nearMembers[randTarget];
20125 PartyResult Player::CanUninviteFromGroup() const
20127 const Group* grp = GetGroup();
20128 if(!grp)
20129 return PARTY_RESULT_YOU_NOT_IN_GROUP;
20131 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
20132 return PARTY_RESULT_YOU_NOT_LEADER;
20134 if(InBattleGround())
20135 return PARTY_RESULT_INVITE_RESTRICTED;
20137 return PARTY_RESULT_OK;
20140 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
20142 //we must move references from m_group to m_originalGroup
20143 SetOriginalGroup(GetGroup(), GetSubGroup());
20145 m_group.unlink();
20146 m_group.link(group, this);
20147 m_group.setSubGroup((uint8)subgroup);
20150 void Player::RemoveFromBattleGroundRaid()
20152 //remove existing reference
20153 m_group.unlink();
20154 if( Group* group = GetOriginalGroup() )
20156 m_group.link(group, this);
20157 m_group.setSubGroup(GetOriginalSubGroup());
20159 SetOriginalGroup(NULL);
20162 void Player::SetOriginalGroup(Group *group, int8 subgroup)
20164 if( group == NULL )
20165 m_originalGroup.unlink();
20166 else
20168 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
20169 assert(subgroup >= 0);
20170 m_originalGroup.link(group, this);
20171 m_originalGroup.setSubGroup((uint8)subgroup);
20175 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
20177 LiquidData liquid_status;
20178 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
20179 if (!res)
20181 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
20182 // Small hack for enable breath in WMO
20183 if (IsInWater())
20184 m_MirrorTimerFlags|=UNDERWATER_INWATER;
20185 return;
20188 // All liquids type - check under water position
20189 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
20191 if ( res & LIQUID_MAP_UNDER_WATER)
20192 m_MirrorTimerFlags |= UNDERWATER_INWATER;
20193 else
20194 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
20197 // Allow travel in dark water on taxi or transport
20198 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
20199 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
20200 else
20201 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
20203 // in lava check, anywhere in lava level
20204 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
20206 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
20207 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
20208 else
20209 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
20211 // in slime check, anywhere in slime level
20212 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
20214 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
20215 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
20216 else
20217 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
20221 void Player::SetCanParry( bool value )
20223 if(m_canParry==value)
20224 return;
20226 m_canParry = value;
20227 UpdateParryPercentage();
20230 void Player::SetCanBlock( bool value )
20232 if(m_canBlock==value)
20233 return;
20235 m_canBlock = value;
20236 UpdateBlockPercentage();
20239 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
20241 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
20242 if(itr->pos == pos)
20243 return true;
20245 return false;
20248 bool Player::CanUseBattleGroundObject()
20250 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
20251 // maybe gameobject code should handle that ForceReaction usage
20252 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
20253 return ( //InBattleGround() && // in battleground - not need, check in other cases
20254 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
20255 //player cannot use object when he is invulnerable (immune)
20256 !isTotalImmune() && // not totally immune
20257 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
20258 !HasStealthAura() && // not stealthed
20259 !HasInvisibilityAura() && // not invisible
20260 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, EFFECT_INDEX_0) &&// can't pickup
20261 isAlive() // live player
20265 bool Player::CanCaptureTowerPoint()
20267 return ( !HasStealthAura() && // not stealthed
20268 !HasInvisibilityAura() && // not invisible
20269 isAlive() // live player
20273 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
20275 uint32 level = getLevel();
20277 if(level > GT_MAX_LEVEL)
20278 level = GT_MAX_LEVEL; // max level in this dbc
20280 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
20281 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
20282 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
20284 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
20285 return 0;
20287 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
20289 if(!bsc) // shouldn't happen
20290 return 0xFFFFFFFF;
20292 float cost = 0;
20294 if(hairstyle != newhairstyle)
20295 cost += bsc->cost; // full price
20297 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
20298 cost += bsc->cost * 0.5f; // +1/2 of price
20300 if(facialhair != newfacialhair)
20301 cost += bsc->cost * 0.75f; // +3/4 of price
20303 return uint32(cost);
20306 void Player::InitGlyphsForLevel()
20308 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
20309 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
20310 if(gs->Order)
20311 SetGlyphSlot(gs->Order - 1, gs->Id);
20313 uint32 level = getLevel();
20314 uint32 value = 0;
20316 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
20317 if(level >= 15)
20318 value |= (0x01 | 0x02);
20319 if(level >= 30)
20320 value |= 0x08;
20321 if(level >= 50)
20322 value |= 0x04;
20323 if(level >= 70)
20324 value |= 0x10;
20325 if(level >= 80)
20326 value |= 0x20;
20328 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
20331 void Player::ApplyGlyph(uint8 slot, bool apply)
20333 if (uint32 glyph = GetGlyph(slot))
20335 if(GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
20337 if(apply)
20339 CastSpell(this, gp->SpellId, true);
20340 SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, glyph);
20342 else
20344 RemoveAurasDueToSpell(gp->SpellId);
20345 SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, 0);
20351 void Player::ApplyGlyphs(bool apply)
20353 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
20354 ApplyGlyph(i,apply);
20357 void Player::EnterVehicle(Vehicle *vehicle)
20359 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
20360 if(!ve)
20361 return;
20363 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
20364 if(!veSeat)
20365 return;
20367 vehicle->SetCharmerGUID(GetGUID());
20368 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20369 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20370 vehicle->setFaction(getFaction());
20372 SetCharm(vehicle); // charm
20373 SetFarSightGUID(vehicle->GetGUID()); // set view
20375 SetClientControl(vehicle, 1); // redirect controls to vehicle
20376 SetMover(vehicle);
20378 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
20379 GetSession()->SendPacket(&data);
20381 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
20382 data.append(GetPackGUID());
20383 data << uint32(0); // counter?
20384 data << uint32(MOVEFLAG_ONTRANSPORT); // transport
20385 data << uint16(0); // special flags
20386 data << uint32(getMSTime()); // time
20387 data << vehicle->GetPositionX(); // x
20388 data << vehicle->GetPositionY(); // y
20389 data << vehicle->GetPositionZ(); // z
20390 data << vehicle->GetOrientation(); // o
20391 // transport part, TODO: load/calculate seat offsets
20392 data << uint64(vehicle->GetGUID()); // transport guid
20393 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
20394 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
20395 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
20396 data << float(0); // transport orientation
20397 data << uint32(getMSTime()); // transport time
20398 data << uint8(0); // seat
20399 // end of transport part
20400 data << uint32(0); // fall time
20401 GetSession()->SendPacket(&data);
20403 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
20404 data << uint64(vehicle->GetGUID());
20405 data << uint16(0);
20406 data << uint32(0);
20407 data << uint32(0x00000101);
20409 for(uint32 i = 0; i < 10; ++i)
20410 data << uint16(0) << uint8(0) << uint8(i+8);
20412 data << uint8(0);
20413 data << uint8(0);
20414 GetSession()->SendPacket(&data);
20417 void Player::ExitVehicle(Vehicle *vehicle)
20419 vehicle->SetCharmerGUID(0);
20420 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20421 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20422 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
20424 SetCharm(NULL);
20425 SetFarSightGUID(0);
20427 SetClientControl(vehicle, 0);
20428 SetMover(NULL);
20430 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
20431 data.append(GetPackGUID());
20432 data << uint32(0); // counter?
20433 data << uint32(MOVEFLAG_ROOT); // fly unk
20434 data << uint16(MOVEFLAG2_UNK4); // special flags
20435 data << uint32(getMSTime()); // time
20436 data << vehicle->GetPositionX(); // x
20437 data << vehicle->GetPositionY(); // y
20438 data << vehicle->GetPositionZ(); // z
20439 data << vehicle->GetOrientation(); // o
20440 data << uint32(0); // fall time
20441 GetSession()->SendPacket(&data);
20443 RemovePetActionBar();
20445 // maybe called at dummy aura remove?
20446 // CastSpell(this, 45472, true); // Parachute
20449 bool Player::isTotalImmune()
20451 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
20453 uint32 immuneMask = 0;
20454 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
20456 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
20457 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
20458 return true;
20460 return false;
20463 bool Player::HasTitle(uint32 bitIndex)
20465 if (bitIndex > MAX_TITLE_INDEX)
20466 return false;
20468 uint32 fieldIndexOffset = bitIndex / 32;
20469 uint32 flag = 1 << (bitIndex % 32);
20470 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20473 void Player::SetTitle(CharTitlesEntry const* title, bool lost)
20475 uint32 fieldIndexOffset = title->bit_index / 32;
20476 uint32 flag = 1 << (title->bit_index % 32);
20478 if(lost)
20480 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20481 return;
20483 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20485 else
20487 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20488 return;
20490 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20493 WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
20494 data << uint32(title->bit_index);
20495 data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
20496 GetSession()->SendPacket(&data);
20499 void Player::ConvertRune(uint8 index, RuneType newType)
20501 SetCurrentRune(index, newType);
20503 WorldPacket data(SMSG_CONVERT_RUNE, 2);
20504 data << uint8(index);
20505 data << uint8(newType);
20506 GetSession()->SendPacket(&data);
20509 void Player::ResyncRunes(uint8 count)
20511 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
20512 for(uint32 i = 0; i < count; ++i)
20514 data << uint8(GetCurrentRune(i)); // rune type
20515 data << uint8(255 - ((GetRuneCooldown(i) / REGEN_TIME_FULL) * 51)); // passed cooldown time (0-255)
20517 GetSession()->SendPacket(&data);
20520 void Player::AddRunePower(uint8 index)
20522 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
20523 data << uint32(1 << index); // mask (0x00-0x3F probably)
20524 GetSession()->SendPacket(&data);
20527 static RuneType runeSlotTypes[MAX_RUNES] = {
20528 /*0*/ RUNE_BLOOD,
20529 /*1*/ RUNE_BLOOD,
20530 /*2*/ RUNE_UNHOLY,
20531 /*3*/ RUNE_UNHOLY,
20532 /*4*/ RUNE_FROST,
20533 /*5*/ RUNE_FROST
20536 void Player::InitRunes()
20538 if(getClass() != CLASS_DEATH_KNIGHT)
20539 return;
20541 m_runes = new Runes;
20543 m_runes->runeState = 0;
20545 for(uint32 i = 0; i < MAX_RUNES; ++i)
20547 SetBaseRune(i, runeSlotTypes[i]); // init base types
20548 SetCurrentRune(i, runeSlotTypes[i]); // init current types
20549 SetRuneCooldown(i, 0); // reset cooldowns
20550 m_runes->SetRuneState(i);
20553 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
20554 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
20558 bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType ) const
20560 for(uint32 i = 0; i < MAX_RUNES; ++i)
20561 if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
20562 return false;
20564 return true;
20567 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
20569 Loot loot;
20570 loot.FillLoot (loot_id,store,this,true);
20572 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
20573 for(uint32 i = 0; i < max_slot; ++i)
20575 LootItem* lootItem = loot.LootItemInSlot(i,this);
20577 ItemPosCountVec dest;
20578 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
20579 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
20580 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20581 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
20582 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20583 if(msg != EQUIP_ERR_OK)
20585 SendEquipError( msg, NULL, NULL, lootItem->itemid );
20586 continue;
20589 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
20590 SendNewItem(pItem, lootItem->count, false, false, broadcast);
20594 uint32 Player::CalculateTalentsPoints() const
20596 uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
20598 if(getClass() != CLASS_DEATH_KNIGHT)
20599 return uint32(base_talent * sWorld.getConfig(CONFIG_FLOAT_RATE_TALENT));
20601 uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
20602 talentPointsForLevel += m_questRewardTalentCount;
20604 if(talentPointsForLevel > base_talent)
20605 talentPointsForLevel = base_talent;
20607 return uint32(talentPointsForLevel * sWorld.getConfig(CONFIG_FLOAT_RATE_TALENT));
20610 bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
20612 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
20613 uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
20614 return v_map != 571 || HasSpell(54197); // Cold Weather Flying
20617 struct DoPlayerLearnSpell
20619 DoPlayerLearnSpell(Player& _player) : player(_player) {}
20620 void operator() (uint32 spell_id) { player.learnSpell(spell_id,false); }
20621 Player& player;
20624 void Player::learnSpellHighRank(uint32 spellid)
20626 learnSpell(spellid,false);
20628 DoPlayerLearnSpell worker(*this);
20629 sSpellMgr.doForHighRanks(spellid,worker);
20632 void Player::_LoadSkills(QueryResult *result)
20634 // 0 1 2
20635 // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
20637 uint32 count = 0;
20638 if (result)
20642 Field *fields = result->Fetch();
20644 uint16 skill = fields[0].GetUInt16();
20645 uint16 value = fields[1].GetUInt16();
20646 uint16 max = fields[2].GetUInt16();
20648 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(skill);
20649 if(!pSkill)
20651 sLog.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill);
20652 continue;
20655 // set fixed skill ranges
20656 switch(GetSkillRangeType(pSkill,false))
20658 case SKILL_RANGE_LANGUAGE: // 300..300
20659 value = max = 300;
20660 break;
20661 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
20662 value = max = 1;
20663 break;
20664 default:
20665 break;
20668 if(value == 0)
20670 sLog.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
20671 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill );
20672 continue;
20675 // enable unlearn button for primary professions only
20676 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
20677 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,1));
20678 else
20679 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,0));
20681 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),MAKE_SKILL_VALUE(value, max));
20682 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20684 mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
20686 learnSkillRewardedSpells(skill, value);
20688 ++count;
20690 if(count >= PLAYER_MAX_SKILLS) // client limit
20692 sLog.outError("Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS);
20693 break;
20695 } while (result->NextRow());
20696 delete result;
20699 for (; count < PLAYER_MAX_SKILLS; ++count)
20701 SetUInt32Value(PLAYER_SKILL_INDEX(count), 0);
20702 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),0);
20703 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20706 // special settings
20707 if(getClass()==CLASS_DEATH_KNIGHT)
20709 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL));
20710 if(base_level < 1)
20711 base_level = 1;
20712 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
20713 if(base_skill < 1)
20714 base_skill = 1; // skill mast be known and then > 0 in any case
20716 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
20717 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
20718 if(GetPureSkillValue (SKILL_AXES) < base_skill)
20719 SetSkill(SKILL_AXES, base_skill,base_skill);
20720 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
20721 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
20722 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
20723 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
20724 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
20725 SetSkill(SKILL_SWORDS, base_skill,base_skill);
20726 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
20727 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
20728 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
20729 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
20730 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
20731 SetSkill(SKILL_UNARMED, base_skill,base_skill);
20735 uint32 Player::GetPhaseMaskForSpawn() const
20737 uint32 phase = PHASEMASK_NORMAL;
20738 if(!isGameMaster())
20739 phase = GetPhaseMask();
20740 else
20742 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
20743 if(!phases.empty())
20744 phase = phases.front()->GetMiscValue();
20747 // some aura phases include 1 normal map in addition to phase itself
20748 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
20749 return n_phase;
20751 return PHASEMASK_NORMAL;
20754 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
20756 ItemPrototype const* pProto = pItem->GetProto();
20758 // proto based limitations
20759 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
20760 return res;
20762 // check unique-equipped on gems
20763 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
20765 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
20766 if(!enchant_id)
20767 continue;
20768 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
20769 if(!enchantEntry)
20770 continue;
20772 ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID);
20773 if(!pGem)
20774 continue;
20776 // include for check equip another gems with same limit category for not equipped item (and then not counted)
20777 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
20778 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
20780 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
20781 return res;
20784 return EQUIP_ERR_OK;
20787 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
20789 // check unique-equipped on item
20790 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
20792 // there is an equip limit on this item
20793 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
20794 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20797 // check unique-equipped limit
20798 if (itemProto->ItemLimitCategory)
20800 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
20801 if(!limitEntry)
20802 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
20804 // NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case
20806 if(limit_count > limitEntry->maxCount)
20807 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS;
20809 // there is an equip limit on this item
20810 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
20811 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS;
20814 return EQUIP_ERR_OK;
20817 void Player::HandleFall(MovementInfo const& movementInfo)
20819 // calculate total z distance of the fall
20820 float z_diff = m_lastFallZ - movementInfo.GetPos()->z;
20821 sLog.outDebug("zDiff = %f", z_diff);
20823 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
20824 // 14.57 can be calculated by resolving damageperc formula below to 0
20825 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
20826 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
20827 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
20829 //Safe fall, fall height reduction
20830 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
20832 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
20834 if(damageperc >0 )
20836 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getConfig(CONFIG_FLOAT_RATE_DAMAGE_FALL));
20838 float height = movementInfo.GetPos()->z;
20839 UpdateGroundPositionZ(movementInfo.GetPos()->x, movementInfo.GetPos()->y, height);
20841 if (damage > 0)
20843 //Prevent fall damage from being more than the player maximum health
20844 if (damage > GetMaxHealth())
20845 damage = GetMaxHealth();
20847 // Gust of Wind
20848 if (GetDummyAura(43621))
20849 damage = GetMaxHealth()/2;
20851 uint32 original_health = GetHealth();
20852 uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
20854 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
20855 if (isAlive() && final_damage < original_health)
20856 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
20859 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
20860 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);
20865 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
20867 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
20870 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
20872 uint32 CurTalentPoints = GetFreeTalentPoints();
20874 if(CurTalentPoints == 0)
20875 return;
20877 if (talentRank >= MAX_TALENT_RANK)
20878 return;
20880 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
20882 if(!talentInfo)
20883 return;
20885 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
20887 if(!talentTabInfo)
20888 return;
20890 // prevent learn talent for different class (cheating)
20891 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
20892 return;
20894 // find current max talent rank
20895 uint32 curtalent_maxrank = 0;
20896 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20898 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20900 curtalent_maxrank = k + 1;
20901 break;
20905 // we already have same or higher talent rank learned
20906 if(curtalent_maxrank >= (talentRank + 1))
20907 return;
20909 // check if we have enough talent points
20910 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20911 return;
20913 // Check if it requires another talent
20914 if (talentInfo->DependsOn > 0)
20916 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20918 bool hasEnoughRank = false;
20919 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20921 if (depTalentInfo->RankID[i] != 0)
20922 if (HasSpell(depTalentInfo->RankID[i]))
20923 hasEnoughRank = true;
20925 if (!hasEnoughRank)
20926 return;
20930 // Find out how many points we have in this field
20931 uint32 spentPoints = 0;
20933 uint32 tTab = talentInfo->TalentTab;
20934 if (talentInfo->Row > 0)
20936 unsigned int numRows = sTalentStore.GetNumRows();
20937 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20939 // Someday, someone needs to revamp
20940 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20941 if (tmpTalent) // the way talents are tracked
20943 if (tmpTalent->TalentTab == tTab)
20945 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20947 if (tmpTalent->RankID[j] != 0)
20949 if (HasSpell(tmpTalent->RankID[j]))
20951 spentPoints += j + 1;
20960 // not have required min points spent in talent tree
20961 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
20962 return;
20964 // spell not set in talent.dbc
20965 uint32 spellid = talentInfo->RankID[talentRank];
20966 if( spellid == 0 )
20968 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20969 return;
20972 // already known
20973 if(HasSpell(spellid))
20974 return;
20976 // learn! (other talent ranks will unlearned at learning)
20977 learnSpell(spellid, false);
20978 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20980 // update free talent points
20981 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20984 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
20986 Pet *pet = GetPet();
20988 if(!pet)
20989 return;
20991 if(petGuid != pet->GetGUID())
20992 return;
20994 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
20996 if(CurTalentPoints == 0)
20997 return;
20999 if (talentRank >= MAX_PET_TALENT_RANK)
21000 return;
21002 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
21004 if(!talentInfo)
21005 return;
21007 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
21009 if(!talentTabInfo)
21010 return;
21012 CreatureInfo const *ci = pet->GetCreatureInfo();
21014 if(!ci)
21015 return;
21017 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
21019 if(!pet_family)
21020 return;
21022 if(pet_family->petTalentType < 0) // not hunter pet
21023 return;
21025 // prevent learn talent for different family (cheating)
21026 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
21027 return;
21029 // find current max talent rank
21030 int32 curtalent_maxrank = 0;
21031 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
21033 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
21035 curtalent_maxrank = k + 1;
21036 break;
21040 // we already have same or higher talent rank learned
21041 if(curtalent_maxrank >= int32(talentRank + 1))
21042 return;
21044 // check if we have enough talent points
21045 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
21046 return;
21048 // Check if it requires another talent
21049 if (talentInfo->DependsOn > 0)
21051 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
21053 bool hasEnoughRank = false;
21054 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
21056 if (depTalentInfo->RankID[i] != 0)
21057 if (pet->HasSpell(depTalentInfo->RankID[i]))
21058 hasEnoughRank = true;
21060 if (!hasEnoughRank)
21061 return;
21065 // Find out how many points we have in this field
21066 uint32 spentPoints = 0;
21068 uint32 tTab = talentInfo->TalentTab;
21069 if (talentInfo->Row > 0)
21071 unsigned int numRows = sTalentStore.GetNumRows();
21072 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
21074 // Someday, someone needs to revamp
21075 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
21076 if (tmpTalent) // the way talents are tracked
21078 if (tmpTalent->TalentTab == tTab)
21080 for (int j = 0; j < MAX_TALENT_RANK; ++j)
21082 if (tmpTalent->RankID[j] != 0)
21084 if (pet->HasSpell(tmpTalent->RankID[j]))
21086 spentPoints += j + 1;
21095 // not have required min points spent in talent tree
21096 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
21097 return;
21099 // spell not set in talent.dbc
21100 uint32 spellid = talentInfo->RankID[talentRank];
21101 if( spellid == 0 )
21103 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
21104 return;
21107 // already known
21108 if(pet->HasSpell(spellid))
21109 return;
21111 // learn! (other talent ranks will unlearned at learning)
21112 pet->learnSpell(spellid);
21113 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
21115 // update free talent points
21116 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
21119 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
21121 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
21123 if(apply)
21124 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
21125 else
21126 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
21130 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
21132 if (m_lastFallTime >= minfo.GetFallTime() || m_lastFallZ <= minfo.GetPos()->z || opcode == MSG_MOVE_FALL_LAND)
21133 SetFallInformation(minfo.GetFallTime(), minfo.GetPos()->z);
21136 void Player::UnsummonPetTemporaryIfAny()
21138 Pet* pet = GetPet();
21139 if(!pet)
21140 return;
21142 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
21144 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
21145 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
21148 RemovePet(pet, PET_SAVE_AS_CURRENT);
21151 void Player::ResummonPetTemporaryUnSummonedIfAny()
21153 if(!m_temporaryUnsummonedPetNumber)
21154 return;
21156 // not resummon in not appropriate state
21157 if(IsPetNeedBeTemporaryUnsummoned())
21158 return;
21160 if(GetPetGUID())
21161 return;
21163 Pet* NewPet = new Pet;
21164 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
21165 delete NewPet;
21167 m_temporaryUnsummonedPetNumber = 0;
21170 bool Player::canSeeSpellClickOn(Creature const *c) const
21172 if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
21173 return false;
21175 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(c->GetEntry());
21176 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
21177 if(itr->second.IsFitToRequirements(this))
21178 return true;
21180 return false;
21183 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
21185 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
21186 *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
21187 *data << uint8(m_activeSpec); // talent group index (0 or 1)
21189 if(m_specsCount)
21191 // loop through all specs (only 1 for now)
21192 for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
21194 uint8 talentIdCount = 0;
21195 size_t pos = data->wpos();
21196 *data << uint8(talentIdCount); // [PH], talentIdCount
21198 // find class talent tabs (all players have 3 talent tabs)
21199 uint32 const* talentTabIds = GetTalentTabPages(getClass());
21201 for(uint32 i = 0; i < 3; ++i)
21203 uint32 talentTabId = talentTabIds[i];
21205 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
21207 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
21208 if(!talentInfo)
21209 continue;
21211 // skip another tab talents
21212 if(talentInfo->TalentTab != talentTabId)
21213 continue;
21215 // find max talent rank
21216 int32 curtalent_maxrank = -1;
21217 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
21219 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
21221 curtalent_maxrank = k;
21222 break;
21226 // not learned talent
21227 if(curtalent_maxrank < 0)
21228 continue;
21230 *data << uint32(talentInfo->TalentID); // Talent.dbc
21231 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
21233 ++talentIdCount;
21237 data->put<uint8>(pos, talentIdCount); // put real count
21239 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
21241 // GlyphProperties.dbc
21242 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
21243 *data << uint16(m_glyphs[specIdx][i].GetId());
21248 void Player::BuildPetTalentsInfoData(WorldPacket *data)
21250 uint32 unspentTalentPoints = 0;
21251 size_t pointsPos = data->wpos();
21252 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
21254 uint8 talentIdCount = 0;
21255 size_t countPos = data->wpos();
21256 *data << uint8(talentIdCount); // [PH], talentIdCount
21258 Pet *pet = GetPet();
21259 if(!pet)
21260 return;
21262 unspentTalentPoints = pet->GetFreeTalentPoints();
21264 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
21266 CreatureInfo const *ci = pet->GetCreatureInfo();
21267 if(!ci)
21268 return;
21270 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
21271 if(!pet_family || pet_family->petTalentType < 0)
21272 return;
21274 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
21276 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
21277 if(!talentTabInfo)
21278 continue;
21280 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
21281 continue;
21283 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
21285 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
21286 if(!talentInfo)
21287 continue;
21289 // skip another tab talents
21290 if(talentInfo->TalentTab != talentTabId)
21291 continue;
21293 // find max talent rank
21294 int32 curtalent_maxrank = -1;
21295 for(int32 k = 4; k > -1; --k)
21297 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
21299 curtalent_maxrank = k;
21300 break;
21304 // not learned talent
21305 if(curtalent_maxrank < 0)
21306 continue;
21308 *data << uint32(talentInfo->TalentID); // Talent.dbc
21309 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
21311 ++talentIdCount;
21314 data->put<uint8>(countPos, talentIdCount); // put real count
21316 break;
21320 void Player::SendTalentsInfoData(bool pet)
21322 WorldPacket data(SMSG_TALENTS_INFO, 50);
21323 data << uint8(pet ? 1 : 0);
21324 if(pet)
21325 BuildPetTalentsInfoData(&data);
21326 else
21327 BuildPlayerTalentsInfoData(&data);
21328 GetSession()->SendPacket(&data);
21331 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
21333 uint32 slotUsedMask = 0;
21334 size_t slotUsedMaskPos = data->wpos();
21335 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
21337 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21339 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
21341 if(!item)
21342 continue;
21344 slotUsedMask |= (1 << i);
21346 *data << uint32(item->GetEntry()); // item entry
21348 uint16 enchantmentMask = 0;
21349 size_t enchantmentMaskPos = data->wpos();
21350 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
21352 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
21354 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
21356 if(!enchId)
21357 continue;
21359 enchantmentMask |= (1 << j);
21361 *data << uint16(enchId); // enchantmentId?
21364 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
21366 *data << uint16(0); // ?
21367 *data << uint8(0); // PGUID!
21368 *data << uint32(0); // seed?
21371 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
21374 void Player::SendEquipmentSetList()
21376 uint32 count = 0;
21377 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
21378 size_t count_pos = data.wpos();
21379 data << uint32(count); // count placeholder
21380 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21382 if(itr->second.state==EQUIPMENT_SET_DELETED)
21383 continue;
21384 data.appendPackGUID(itr->second.Guid);
21385 data << uint32(itr->first);
21386 data << itr->second.Name;
21387 data << itr->second.IconName;
21388 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21389 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
21391 ++count; // client have limit but it checked at loading and set
21393 data.put<uint32>(count_pos, count);
21394 GetSession()->SendPacket(&data);
21397 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
21399 if(eqset.Guid != 0)
21401 bool found = false;
21403 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21405 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
21407 found = true;
21408 break;
21412 if(!found) // something wrong...
21414 sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
21415 return;
21419 EquipmentSet& eqslot = m_EquipmentSets[index];
21421 EquipmentSetUpdateState old_state = eqslot.state;
21423 eqslot = eqset;
21425 if(eqset.Guid == 0)
21427 eqslot.Guid = sObjectMgr.GenerateEquipmentSetGuid();
21429 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
21430 data << uint32(index);
21431 data.appendPackGUID(eqslot.Guid);
21432 GetSession()->SendPacket(&data);
21435 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
21438 void Player::_SaveEquipmentSets()
21440 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
21442 uint32 index = itr->first;
21443 EquipmentSet& eqset = itr->second;
21444 switch(eqset.state)
21446 case EQUIPMENT_SET_UNCHANGED:
21447 ++itr;
21448 break; // nothing do
21449 case EQUIPMENT_SET_CHANGED:
21450 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'",
21451 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],
21452 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);
21453 eqset.state = EQUIPMENT_SET_UNCHANGED;
21454 ++itr;
21455 break;
21456 case EQUIPMENT_SET_NEW:
21457 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')",
21458 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],
21459 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]);
21460 eqset.state = EQUIPMENT_SET_UNCHANGED;
21461 ++itr;
21462 break;
21463 case EQUIPMENT_SET_DELETED:
21464 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
21465 m_EquipmentSets.erase(itr++);
21466 break;
21471 void Player::_SaveBGData()
21473 CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
21474 if (m_bgData.bgInstanceID)
21476 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
21477 CharacterDatabase.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
21478 GetGUIDLow(), m_bgData.bgInstanceID, m_bgData.bgTeam, m_bgData.joinPos.coord_x, m_bgData.joinPos.coord_y, m_bgData.joinPos.coord_z,
21479 m_bgData.joinPos.orientation, m_bgData.joinPos.mapid, m_bgData.taxiPath[0], m_bgData.taxiPath[1], m_bgData.mountSpell);
21483 void Player::DeleteEquipmentSet(uint64 setGuid)
21485 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21487 if(itr->second.Guid == setGuid)
21489 if(itr->second.state == EQUIPMENT_SET_NEW)
21490 m_EquipmentSets.erase(itr);
21491 else
21492 itr->second.state = EQUIPMENT_SET_DELETED;
21493 break;
21498 void Player::ActivateSpec(uint8 specNum)
21500 if(GetActiveSpec() == specNum)
21501 return;
21503 if(specNum >= GetSpecsCount())
21504 return;
21506 // unlearn GetActiveSpec() talents (not learned in specNum);
21507 // learn specNum talents
21509 ApplyGlyphs(false);
21511 SetActiveSpec(specNum);
21513 // recheck action buttons (not checked at loading/spec copy)
21514 ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
21515 for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); ++itr)
21516 if (itr->second.uState != ACTIONBUTTON_DELETED)
21517 // remove broken without any output (it can be not correct because talents not copied at spec creating)
21518 if (!IsActionButtonDataValid(itr->first,itr->second.GetAction(),itr->second.GetType(), this, false))
21519 removeActionButton(m_activeSpec,itr->first);
21521 ApplyGlyphs(true);
21523 SendInitialActionButtons();
21525 InitTalentForLevel();
21528 void Player::UpdateSpecCount(uint8 count)
21530 uint8 curCount = GetSpecsCount();
21531 if (curCount == count)
21532 return;
21534 // maybe current spec data must be copied to 0 spec?
21535 if (m_activeSpec >= count)
21536 ActivateSpec(0);
21538 // copy spec data from new specs
21539 if (count > curCount)
21541 // copy action buttons from active spec (more easy in this case iterate first by button)
21542 ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
21544 for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); ++itr)
21546 if (itr->second.uState != ACTIONBUTTON_DELETED)
21548 for(uint8 spec = curCount; spec < count; ++spec)
21549 addActionButton(spec,itr->first,itr->second.GetAction(),itr->second.GetType());
21553 // delete spec data for removed specs
21554 else if (count < curCount)
21556 // delete action buttons for removed spec
21557 for(uint8 spec = count; spec < curCount; ++spec)
21559 // delete action buttons for removed spec
21560 for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button)
21561 removeActionButton(spec,button);
21565 SetSpecsCount(count);
21567 SendTalentsInfoData(false);
21570 void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
21572 m_atLoginFlags &= ~f;
21574 if(in_db_also)
21575 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
21578 void Player::SendClearCooldown( uint32 spell_id, Unit* target )
21580 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
21581 data << uint32(spell_id);
21582 data << uint64(target->GetGUID());
21583 SendDirectMessage(&data);
21586 void Player::BuildTeleportAckMsg( WorldPacket *data, float x, float y, float z, float ang ) const
21588 data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
21589 data->append(GetPackGUID());
21590 *data << uint32(0); // this value increments every time
21591 *data << uint32(m_movementInfo.GetMovementFlags()); // movement flags
21592 *data << uint16(0); // 2.3.0
21593 *data << uint32(getMSTime()); // time
21594 *data << x;
21595 *data << y;
21596 *data << z;
21597 *data << ang;
21598 *data << uint32(0);
21601 bool Player::HasMovementFlag( MovementFlags f ) const
21603 return m_movementInfo.HasMovementFlag(f);
21606 void Player::SetFarSightGUID( uint64 guid )
21608 if(GetFarSight() == guid)
21609 return;
21611 SetUInt64Value(PLAYER_FARSIGHT, guid);
21613 // need triggering load grids around new view point
21614 UpdateVisibilityForPlayer();
21617 void Player::UpdateVisibilityForPlayer()
21619 WorldObject const* viewPoint = GetViewPoint();
21620 Map* m = GetMap();
21622 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
21623 Cell cell(p);
21625 m->UpdatePlayerVisibility(this, cell, p);
21627 if (this != viewPoint)
21629 CellPair pView(MaNGOS::ComputeCellPair(viewPoint->GetPositionX(), viewPoint->GetPositionY()));
21630 Cell cellView(pView);
21632 m->UpdateObjectsVisibilityFor(this, cellView, pView);
21634 else
21635 m->UpdateObjectsVisibilityFor(this, cell, p);
21638 void Player::SendDuelCountdown(uint32 counter)
21640 WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
21641 data << uint32(counter); // seconds
21642 GetSession()->SendPacket(&data);
21645 bool Player::IsImmunedToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const
21647 switch(spellInfo->Effect[index])
21649 case SPELL_EFFECT_ATTACK_ME:
21650 return true;
21651 default:
21652 break;
21654 switch(spellInfo->EffectApplyAuraName[index])
21656 case SPELL_AURA_MOD_TAUNT:
21657 return true;
21658 default:
21659 break;
21661 return Unit::IsImmunedToSpellEffect(spellInfo, index);
21664 void Player::SetHomebindToLocation(WorldLocation const& loc, uint32 area_id)
21666 m_homebindMapId = loc.mapid;
21667 m_homebindAreaId = area_id;
21668 m_homebindX = loc.coord_x;
21669 m_homebindY = loc.coord_y;
21670 m_homebindZ = loc.coord_z;
21672 // update sql homebind
21673 CharacterDatabase.PExecute("UPDATE character_homebind SET map = '%u', zone = '%u', position_x = '%f', position_y = '%f', position_z = '%f' WHERE guid = '%u'",
21674 m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ, GetGUIDLow());