Use PVPDificulty.dbc for bg/arena bracket selection (levels and difficulty)
[getmangos.git] / src / game / Player.cpp
blob7201caa4ffe844cd1676f8dc2b0adb05cec60307
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, uint8 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_INTERVAL_SAVE);
351 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_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 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
519 delete itr->second;
521 //all mailed items should be deleted, also all mail should be deallocated
522 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
523 delete *itr;
525 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
526 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
528 delete PlayerTalkClass;
530 if (m_transport)
532 m_transport->RemovePassenger(this);
535 for(size_t x = 0; x < ItemSetEff.size(); x++)
536 if(ItemSetEff[x])
537 delete ItemSetEff[x];
539 // clean up player-instance binds, may unload some instance saves
540 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
541 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
542 itr->second.save->RemovePlayer(this);
544 delete m_declinedname;
545 delete m_runes;
548 void Player::CleanupsBeforeDelete()
550 if(m_uint32Values) // only for fully created Object
552 TradeCancel(false);
553 DuelComplete(DUEL_INTERUPTED);
555 Unit::CleanupsBeforeDelete();
558 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 )
560 //FIXME: outfitId not used in player creating
562 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
564 m_name = name;
566 PlayerInfo const* info = sObjectMgr.GetPlayerInfo(race, class_);
567 if(!info)
569 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
570 return false;
573 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
574 m_items[i] = NULL;
576 SetLocationMapId(info->mapId);
577 Relocate(info->positionX,info->positionY,info->positionZ);
579 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
580 if(!cEntry)
582 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
583 return false;
586 SetMap(sMapMgr.CreateMap(info->mapId, this));
588 uint8 powertype = cEntry->powerType;
590 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
591 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
593 setFactionForRace(race);
595 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
597 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
598 InitDisplayIds();
599 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
600 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
601 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
602 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
603 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
605 // -1 is default value
606 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
608 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
609 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
610 SetByteValue(PLAYER_BYTES_3, 0, gender);
612 SetUInt32Value( PLAYER_GUILDID, 0 );
613 SetUInt32Value( PLAYER_GUILDRANK, 0 );
614 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
616 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
617 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
618 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 0 ); // 0=disabled
619 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
620 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
621 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
622 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
623 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
625 // set starting level
626 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
627 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
628 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
630 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
632 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
633 if(gm_level > start_level)
634 start_level = gm_level;
637 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
639 InitRunes();
641 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
642 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
643 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
645 // Played time
646 m_Last_tick = time(NULL);
647 m_Played_time[PLAYED_TIME_TOTAL] = 0;
648 m_Played_time[PLAYED_TIME_LEVEL] = 0;
650 // base stats and related field values
651 InitStatsForLevel();
652 InitTaxiNodesForLevel();
653 InitGlyphsForLevel();
654 InitTalentForLevel();
655 InitPrimaryProfessions(); // to max set before any spell added
657 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
658 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
659 SetHealth(GetMaxHealth());
660 if (getPowerType()==POWER_MANA)
662 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
663 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
666 if(getPowerType() == POWER_RUNIC_POWER)
668 SetPower(POWER_RUNE, 8);
669 SetMaxPower(POWER_RUNE, 8);
670 SetPower(POWER_RUNIC_POWER, 0);
671 SetMaxPower(POWER_RUNIC_POWER, 1000);
674 // original spells
675 learnDefaultSpells();
677 // original action bar
678 for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
679 addActionButton(action_itr->button,action_itr->action,action_itr->type);
681 // original items
682 CharStartOutfitEntry const* oEntry = NULL;
683 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
685 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
687 if(entry->RaceClassGender == RaceClassGender)
689 oEntry = entry;
690 break;
695 if(oEntry)
697 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
699 if(oEntry->ItemId[j] <= 0)
700 continue;
702 uint32 item_id = oEntry->ItemId[j];
704 // Hack for not existed item id in dbc 3.0.3
705 if(item_id==40582)
706 continue;
708 ItemPrototype const* iProto = ObjectMgr::GetItemPrototype(item_id);
709 if(!iProto)
711 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
712 continue;
715 // BuyCount by default
716 uint32 count = iProto->BuyCount;
718 // special amount for foor/drink
719 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
721 switch(iProto->Spells[0].SpellCategory)
723 case 11: // food
724 count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4;
725 break;
726 case 59: // drink
727 count = 2;
728 break;
730 if(iProto->Stackable < count)
731 count = iProto->Stackable;
734 StoreNewItemInBestSlots(item_id, count);
738 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
739 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
741 // bags and main-hand weapon must equipped at this moment
742 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
743 // or ammo not equipped in special bag
744 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
746 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
748 uint16 eDest;
749 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
750 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
751 if( msg == EQUIP_ERR_OK )
753 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
754 EquipItem( eDest, pItem, true);
756 // move other items to more appropriate slots (ammo not equipped in special bag)
757 else
759 ItemPosCountVec sDest;
760 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
761 if( msg == EQUIP_ERR_OK )
763 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
764 pItem = StoreItem( sDest, pItem, true);
767 // if this is ammo then use it
768 msg = CanUseAmmo( pItem->GetEntry() );
769 if( msg == EQUIP_ERR_OK )
770 SetAmmo( pItem->GetEntry() );
774 // all item positions resolved
776 return true;
779 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
781 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
783 // attempt equip by one
784 while(titem_amount > 0)
786 uint16 eDest;
787 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
788 if( msg != EQUIP_ERR_OK )
789 break;
791 EquipNewItem( eDest, titem_id, true);
792 AutoUnequipOffhandIfNeed();
793 --titem_amount;
796 if(titem_amount == 0)
797 return true; // equipped
799 // attempt store
800 ItemPosCountVec sDest;
801 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
802 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
803 if( msg == EQUIP_ERR_OK )
805 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
806 return true; // stored
809 // item can't be added
810 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
811 return false;
814 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
816 if (int(MaxValue) == DISABLED_MIRROR_TIMER)
818 if (int(CurrentValue) != DISABLED_MIRROR_TIMER)
819 StopMirrorTimer(Type);
820 return;
822 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
823 data << (uint32)Type;
824 data << CurrentValue;
825 data << MaxValue;
826 data << Regen;
827 data << (uint8)0;
828 data << (uint32)0; // spell id
829 GetSession()->SendPacket( &data );
832 void Player::StopMirrorTimer(MirrorTimerType Type)
834 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
835 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
836 data << (uint32)Type;
837 GetSession()->SendPacket( &data );
840 uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
842 if(!isAlive() || isGameMaster())
843 return 0;
845 // Absorb, resist some environmental damage type
846 uint32 absorb = 0;
847 uint32 resist = 0;
848 if (type == DAMAGE_LAVA)
849 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
850 else if (type == DAMAGE_SLIME)
851 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
853 damage-=absorb+resist;
855 DealDamageMods(this,damage,&absorb);
857 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
858 data << uint64(GetGUID());
859 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
860 data << uint32(damage);
861 data << uint32(absorb);
862 data << uint32(resist);
863 SendMessageToSet(&data, true);
865 uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
867 if(!isAlive())
869 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
871 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
872 DurabilityLossAll(0.10f,false);
873 // durability lost message
874 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
875 GetSession()->SendPacket(&data2);
878 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
881 return final_damage;
884 int32 Player::getMaxTimer(MirrorTimerType timer)
886 switch (timer)
888 case FATIGUE_TIMER:
889 if (GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_TIMERBAR_FATIGUE_GMLEVEL))
890 return DISABLED_MIRROR_TIMER;
891 return sWorld.getConfig(CONFIG_TIMERBAR_FATIGUE_MAX)*IN_MILISECONDS;
892 case BREATH_TIMER:
894 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) ||
895 GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_TIMERBAR_BREATH_GMLEVEL))
896 return DISABLED_MIRROR_TIMER;
897 int32 UnderWaterTime = sWorld.getConfig(CONFIG_TIMERBAR_BREATH_MAX)*IN_MILISECONDS;
898 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
899 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
900 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
901 return UnderWaterTime;
903 case FIRE_TIMER:
905 if (!isAlive() || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_TIMERBAR_FIRE_GMLEVEL))
906 return DISABLED_MIRROR_TIMER;
907 return sWorld.getConfig(CONFIG_TIMERBAR_FIRE_MAX)*IN_MILISECONDS;
909 default:
910 return 0;
912 return 0;
915 void Player::UpdateMirrorTimers()
917 // Desync flags for update on next HandleDrowning
918 if (m_MirrorTimerFlags)
919 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
922 void Player::HandleDrowning(uint32 time_diff)
924 if (!m_MirrorTimerFlags)
925 return;
927 // In water
928 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
930 // Breath timer not activated - activate it
931 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
933 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
934 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
936 else // If activated - do tick
938 m_MirrorTimer[BREATH_TIMER]-=time_diff;
939 // Timer limit - need deal damage
940 if (m_MirrorTimer[BREATH_TIMER] < 0)
942 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
943 // Calculate and deal damage
944 // TODO: Check this formula
945 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
946 EnvironmentalDamage(DAMAGE_DROWNING, damage);
948 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
949 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
952 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
954 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
955 // Need breath regen
956 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
957 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
958 StopMirrorTimer(BREATH_TIMER);
959 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
960 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
963 // In dark water
964 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
966 // Fatigue timer not activated - activate it
967 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
969 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
970 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
972 else
974 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
975 // Timer limit - need deal damage or teleport ghost to graveyard
976 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
978 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
979 if (isAlive()) // Calculate and deal damage
981 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
982 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
984 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
985 RepopAtGraveyard();
987 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
988 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
991 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
993 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
994 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
995 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
996 StopMirrorTimer(FATIGUE_TIMER);
997 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
998 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
1001 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
1003 // Breath timer not activated - activate it
1004 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
1005 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
1006 else
1008 m_MirrorTimer[FIRE_TIMER]-=time_diff;
1009 if (m_MirrorTimer[FIRE_TIMER] < 0)
1011 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
1012 // Calculate and deal damage
1013 // TODO: Check this formula
1014 uint32 damage = urand(600, 700);
1015 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
1016 EnvironmentalDamage(DAMAGE_LAVA, damage);
1017 else
1018 EnvironmentalDamage(DAMAGE_SLIME, damage);
1022 else
1023 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
1025 // Recheck timers flag
1026 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1027 for (int i = 0; i< MAX_TIMERS; ++i)
1028 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1030 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1031 break;
1033 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1036 ///The player sobers by 256 every 10 seconds
1037 void Player::HandleSobering()
1039 m_drunkTimer = 0;
1041 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1042 SetDrunkValue(drunk);
1045 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1047 if(value >= 23000)
1048 return DRUNKEN_SMASHED;
1049 if(value >= 12800)
1050 return DRUNKEN_DRUNK;
1051 if(value & 0xFFFE)
1052 return DRUNKEN_TIPSY;
1053 return DRUNKEN_SOBER;
1056 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1058 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1060 m_drunk = newDrunkenValue;
1061 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1063 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1065 // special drunk invisibility detection
1066 if(newDrunkenState >= DRUNKEN_DRUNK)
1067 m_detectInvisibilityMask |= (1<<6);
1068 else
1069 m_detectInvisibilityMask &= ~(1<<6);
1071 if(newDrunkenState == oldDrunkenState)
1072 return;
1074 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1075 data << uint64(GetGUID());
1076 data << uint32(newDrunkenState);
1077 data << uint32(itemId);
1079 SendMessageToSet(&data, true);
1082 void Player::Update( uint32 p_time )
1084 if(!IsInWorld())
1085 return;
1087 // undelivered mail
1088 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1090 SendNewMail();
1091 ++unReadMails;
1093 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1094 m_nextMailDelivereTime = 0;
1097 //used to implement delayed far teleports
1098 SetCanDelayTeleport(true);
1099 Unit::Update( p_time );
1100 SetCanDelayTeleport(false);
1102 // update player only attacks
1103 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1105 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1108 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1110 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1113 time_t now = time (NULL);
1115 UpdatePvPFlag(now);
1117 UpdateContestedPvP(p_time);
1119 UpdateDuelFlag(now);
1121 CheckDuelDistance(now);
1123 UpdateAfkReport(now);
1125 // Update items that have just a limited lifetime
1126 if (now>m_Last_tick)
1127 UpdateItemDuration(uint32(now- m_Last_tick));
1129 if (!m_timedquests.empty())
1131 std::set<uint32>::iterator iter = m_timedquests.begin();
1132 while (iter != m_timedquests.end())
1134 QuestStatusData& q_status = mQuestStatus[*iter];
1135 if( q_status.m_timer <= p_time )
1137 uint32 quest_id = *iter;
1138 ++iter; // current iter will be removed in FailQuest
1139 FailQuest(quest_id);
1141 else
1143 q_status.m_timer -= p_time;
1144 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1145 ++iter;
1150 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1152 Unit *pVictim = getVictim();
1153 if (pVictim && !IsNonMeleeSpellCasted(false))
1155 // default combat reach 10
1156 // TODO add weapon,skill check
1158 float pldistance = ATTACK_DISTANCE;
1160 if (isAttackReady(BASE_ATTACK))
1162 if(!IsWithinDistInMap(pVictim, pldistance))
1164 setAttackTimer(BASE_ATTACK,100);
1165 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1167 SendAttackSwingNotInRange();
1168 m_swingErrorMsg = 1;
1171 //120 degrees of radiant range
1172 else if( !HasInArc( 2*M_PI/3, pVictim ))
1174 setAttackTimer(BASE_ATTACK,100);
1175 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1177 SendAttackSwingBadFacingAttack();
1178 m_swingErrorMsg = 2;
1181 else
1183 m_swingErrorMsg = 0; // reset swing error state
1185 // prevent base and off attack in same time, delay attack at 0.2 sec
1186 if(haveOffhandWeapon())
1188 uint32 off_att = getAttackTimer(OFF_ATTACK);
1189 if(off_att < ATTACK_DISPLAY_DELAY)
1190 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1192 AttackerStateUpdate(pVictim, BASE_ATTACK);
1193 resetAttackTimer(BASE_ATTACK);
1197 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1199 if(!IsWithinDistInMap(pVictim, pldistance))
1201 setAttackTimer(OFF_ATTACK,100);
1203 else if( !HasInArc( 2*M_PI/3, pVictim ))
1205 setAttackTimer(OFF_ATTACK,100);
1207 else
1209 // prevent base and off attack in same time, delay attack at 0.2 sec
1210 uint32 base_att = getAttackTimer(BASE_ATTACK);
1211 if(base_att < ATTACK_DISPLAY_DELAY)
1212 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1213 // do attack
1214 AttackerStateUpdate(pVictim, OFF_ATTACK);
1215 resetAttackTimer(OFF_ATTACK);
1219 Unit *owner = pVictim->GetOwner();
1220 Unit *u = owner ? owner : pVictim;
1221 if(u->IsPvP() && (!duel || duel->opponent != u))
1223 UpdatePvP(true);
1224 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1229 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1231 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1233 int time_inn = time(NULL)-GetTimeInnEnter();
1234 if (time_inn >= 10) //freeze update
1236 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1237 //speed collect rest bonus (section/in hour)
1238 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1239 UpdateInnerTime(time(NULL));
1244 if (m_regenTimer)
1246 if(p_time >= m_regenTimer)
1247 m_regenTimer = 0;
1248 else
1249 m_regenTimer -= p_time;
1252 if (m_weaponChangeTimer > 0)
1254 if(p_time >= m_weaponChangeTimer)
1255 m_weaponChangeTimer = 0;
1256 else
1257 m_weaponChangeTimer -= p_time;
1260 if (m_zoneUpdateTimer > 0)
1262 if(p_time >= m_zoneUpdateTimer)
1264 uint32 newzone, newarea;
1265 GetZoneAndAreaId(newzone,newarea);
1267 if( m_zoneUpdateId != newzone )
1268 UpdateZone(newzone,newarea); // also update area
1269 else
1271 // use area updates as well
1272 // needed for free far all arenas for example
1273 if( m_areaUpdateId != newarea )
1274 UpdateArea(newarea);
1276 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1279 else
1280 m_zoneUpdateTimer -= p_time;
1283 if (isAlive())
1285 // if no longer casting, set regen power as soon as it is up.
1286 if (!IsUnderLastManaUseEffect())
1287 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
1289 if (!m_regenTimer)
1290 RegenerateAll();
1293 if (m_deathState == JUST_DIED)
1295 KillPlayer();
1298 if(m_nextSave > 0)
1300 if(p_time >= m_nextSave)
1302 // m_nextSave reseted in SaveToDB call
1303 SaveToDB();
1304 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1306 else
1308 m_nextSave -= p_time;
1312 //Handle Water/drowning
1313 HandleDrowning(p_time);
1315 //Handle detect stealth players
1316 if (m_DetectInvTimer > 0)
1318 if (p_time >= m_DetectInvTimer)
1320 HandleStealthedUnitsDetection();
1321 m_DetectInvTimer = 3000;
1323 else
1324 m_DetectInvTimer -= p_time;
1327 // Played time
1328 if (now > m_Last_tick)
1330 uint32 elapsed = uint32(now - m_Last_tick);
1331 m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
1332 m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
1333 m_Last_tick = now;
1336 if (m_drunk)
1338 m_drunkTimer += p_time;
1340 if (m_drunkTimer > 10*IN_MILISECONDS)
1341 HandleSobering();
1344 // not auto-free ghost from body in instances
1345 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1347 if(p_time >= m_deathTimer)
1349 m_deathTimer = 0;
1350 BuildPlayerRepop();
1351 RepopAtGraveyard();
1353 else
1354 m_deathTimer -= p_time;
1357 UpdateEnchantTime(p_time);
1358 UpdateHomebindTime(p_time);
1360 // group update
1361 SendUpdateToOutOfRangeGroupMembers();
1363 Pet* pet = GetPet();
1364 if(pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1366 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1369 //we should execute delayed teleports only for alive(!) players
1370 //because we don't want player's ghost teleported from graveyard
1371 if(IsHasDelayedTeleport() && isAlive())
1372 TeleportTo(m_teleport_dest, m_teleport_options);
1375 void Player::setDeathState(DeathState s)
1377 uint32 ressSpellId = 0;
1379 bool cur = isAlive();
1381 if(s == JUST_DIED && cur)
1383 // drunken state is cleared on death
1384 SetDrunkValue(0);
1385 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1386 ClearComboPoints();
1388 clearResurrectRequestData();
1390 // remove form before other mods to prevent incorrect stats calculation
1391 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1393 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1394 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1396 // remove uncontrolled pets
1397 RemoveMiniPet();
1399 // save value before aura remove in Unit::setDeathState
1400 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1402 // passive spell
1403 if(!ressSpellId)
1404 ressSpellId = GetResurrectionSpellId();
1405 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1406 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1407 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1409 Unit::setDeathState(s);
1411 // restore resurrection spell id for player after aura remove
1412 if(s == JUST_DIED && cur && ressSpellId)
1413 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1415 if(isAlive() && !cur)
1417 //clear aura case after resurrection by another way (spells will be applied before next death)
1418 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1420 // restore default warrior stance
1421 if(getClass()== CLASS_WARRIOR)
1422 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1426 bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1428 // 0 1 2 3 4 5 6 7
1429 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
1430 // 8 9 10 11 12 13 14
1431 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
1432 // 15 16 17 18 19 20
1433 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive "
1435 Field *fields = result->Fetch();
1437 uint32 guid = fields[0].GetUInt32();
1438 uint8 pRace = fields[2].GetUInt8();
1439 uint8 pClass = fields[3].GetUInt8();
1441 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(pRace, pClass);
1442 if(!info)
1444 sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
1445 return false;
1448 *p_data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
1449 *p_data << fields[1].GetString(); // name
1450 *p_data << uint8(pRace); // race
1451 *p_data << uint8(pClass); // class
1452 *p_data << uint8(fields[4].GetUInt8()); // gender
1454 uint32 playerBytes = fields[5].GetUInt32();
1455 *p_data << uint8(playerBytes); // skin
1456 *p_data << uint8(playerBytes >> 8); // face
1457 *p_data << uint8(playerBytes >> 16); // hair style
1458 *p_data << uint8(playerBytes >> 24); // hair color
1460 uint32 playerBytes2 = fields[6].GetUInt32();
1461 *p_data << uint8(playerBytes2 & 0xFF); // facial hair
1463 *p_data << uint8(fields[7].GetUInt8()); // level
1464 *p_data << uint32(fields[8].GetUInt32()); // zone
1465 *p_data << uint32(fields[9].GetUInt32()); // map
1467 *p_data << fields[10].GetFloat(); // x
1468 *p_data << fields[11].GetFloat(); // y
1469 *p_data << fields[12].GetFloat(); // z
1471 *p_data << uint32(fields[13].GetUInt32()); // guild id
1473 uint32 char_flags = 0;
1474 uint32 playerFlags = fields[14].GetUInt32();
1475 uint32 atLoginFlags = fields[15].GetUInt32();
1476 if(playerFlags & PLAYER_FLAGS_HIDE_HELM)
1477 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1478 if(playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
1479 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1480 if(playerFlags & PLAYER_FLAGS_GHOST)
1481 char_flags |= CHARACTER_FLAG_GHOST;
1482 if(atLoginFlags & AT_LOGIN_RENAME)
1483 char_flags |= CHARACTER_FLAG_RENAME;
1484 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
1486 if(!fields[20].GetCppString().empty())
1487 char_flags |= CHARACTER_FLAG_DECLINED;
1489 else
1490 char_flags |= CHARACTER_FLAG_DECLINED;
1492 *p_data << uint32(char_flags); // character flags
1493 // character customize flags
1494 *p_data << uint32(atLoginFlags & AT_LOGIN_CUSTOMIZE ? CHAR_CUSTOMIZE_FLAG_CUSTOMIZE : CHAR_CUSTOMIZE_FLAG_NONE);
1495 *p_data << uint8(1); // unknown
1497 // Pets info
1499 uint32 petDisplayId = 0;
1500 uint32 petLevel = 0;
1501 uint32 petFamily = 0;
1503 // show pet at selection character in character list only for non-ghost character
1504 if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1506 uint32 entry = fields[16].GetUInt32();
1507 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1508 if(cInfo)
1510 petDisplayId = fields[17].GetUInt32();
1511 petLevel = fields[18].GetUInt32();
1512 petFamily = cInfo->family;
1516 *p_data << uint32(petDisplayId);
1517 *p_data << uint32(petLevel);
1518 *p_data << uint32(petFamily);
1521 // TODO: do not access data field here
1522 Tokens data = StrSplit(fields[19].GetCppString(), " ");
1524 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1526 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1527 uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
1528 const ItemPrototype * proto = ObjectMgr::GetItemPrototype(item_id);
1529 if(!proto)
1531 *p_data << uint32(0);
1532 *p_data << uint8(0);
1533 *p_data << uint32(0);
1534 continue;
1537 SpellItemEnchantmentEntry const *enchant = NULL;
1539 uint32 enchants = GetUInt32ValueFromArray(data, visualbase + 1);
1540 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1542 // values stored in 2 uint16
1543 uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16);
1544 if(!enchantId)
1545 continue;
1547 if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId)))
1548 break;
1551 *p_data << uint32(proto->DisplayInfoID);
1552 *p_data << uint8(proto->InventoryType);
1553 *p_data << uint32(enchant ? enchant->aura_id : 0);
1555 *p_data << uint32(0); // first bag display id
1556 *p_data << uint8(0); // first bag inventory type
1557 *p_data << uint32(0); // enchant?
1559 return true;
1562 bool Player::ToggleAFK()
1564 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1566 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1568 // afk player not allowed in battleground
1569 if(state && InBattleGround())
1570 LeaveBattleground();
1572 return state;
1575 bool Player::ToggleDND()
1577 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1579 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1582 uint8 Player::chatTag() const
1584 // it's bitmask
1585 // 0x8 - ??
1586 // 0x4 - gm
1587 // 0x2 - dnd
1588 // 0x1 - afk
1589 if(isGMChat())
1590 return 4;
1591 else if(isDND())
1592 return 3;
1593 if(isAFK())
1594 return 1;
1595 else
1596 return 0;
1599 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1601 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1603 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1604 return false;
1607 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1608 Pet* pet = GetPet();
1610 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1612 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1613 // don't let gm level > 1 either
1614 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1615 return false;
1617 // client without expansion support
1618 if(GetSession()->Expansion() < mEntry->Expansion())
1620 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1622 if(GetTransport())
1623 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1625 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1627 return false; // normal client can't teleport to this map...
1629 else
1631 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1634 // if we were on a transport, leave
1635 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1637 m_transport->RemovePassenger(this);
1638 m_transport = NULL;
1639 m_movementInfo.t_x = 0.0f;
1640 m_movementInfo.t_y = 0.0f;
1641 m_movementInfo.t_z = 0.0f;
1642 m_movementInfo.t_o = 0.0f;
1643 m_movementInfo.t_seat = -1;
1644 m_movementInfo.t_time = 0;
1647 // The player was ported to another map and looses the duel immediately.
1648 // We have to perform this check before the teleport, otherwise the
1649 // ObjectAccessor won't find the flag.
1650 if (duel && GetMapId()!=mapid)
1652 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1653 if (obj)
1654 DuelComplete(DUEL_FLED);
1657 // reset movement flags at teleport, because player will continue move with these flags after teleport
1658 m_movementInfo.SetMovementFlags(MOVEMENTFLAG_NONE);
1660 if ((GetMapId() == mapid) && (!m_transport))
1662 //lets reset far teleport flag if it wasn't reset during chained teleports
1663 SetSemaphoreTeleportFar(false);
1664 //setup delayed teleport flag
1665 SetDelayedTeleportFlag(IsCanDelayTeleport());
1666 //if teleport spell is casted in Unit::Update() func
1667 //then we need to delay it until update process will be finished
1668 if(IsHasDelayedTeleport())
1670 SetSemaphoreTeleportNear(true);
1671 //lets save teleport destination for player
1672 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1673 m_teleport_options = options;
1674 return true;
1677 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1679 //same map, only remove pet if out of range for new position
1680 if(pet && !pet->IsWithinDist3d(x,y,z,GetMap()->GetVisibilityDistance()))
1681 UnsummonPetTemporaryIfAny();
1684 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1685 CombatStop();
1687 // this will be used instead of the current location in SaveToDB
1688 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1689 SetFallInformation(0, z);
1691 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1692 // at client packet MSG_MOVE_TELEPORT_ACK
1693 SetSemaphoreTeleportNear(true);
1694 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1695 if(!GetSession()->PlayerLogout())
1697 WorldPacket data;
1698 BuildTeleportAckMsg(&data, x, y, z, orientation);
1699 GetSession()->SendPacket(&data);
1702 else
1704 // far teleport to another map
1705 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1706 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1708 // Check enter rights before map getting to avoid creating instance copy for player
1709 // this check not dependent from map instance copy and same for all instance copies of selected map
1710 if (!sMapMgr.CanPlayerEnter(mapid, this))
1711 return false;
1713 // If the map is not created, assume it is possible to enter it.
1714 // It will be created in the WorldPortAck.
1715 Map *map = sMapMgr.FindMap(mapid);
1716 if (!map || map->CanEnter(this))
1718 //lets reset near teleport flag if it wasn't reset during chained teleports
1719 SetSemaphoreTeleportNear(false);
1720 //setup delayed teleport flag
1721 SetDelayedTeleportFlag(IsCanDelayTeleport());
1722 //if teleport spell is casted in Unit::Update() func
1723 //then we need to delay it until update process will be finished
1724 if(IsHasDelayedTeleport())
1726 SetSemaphoreTeleportFar(true);
1727 //lets save teleport destination for player
1728 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1729 m_teleport_options = options;
1730 return true;
1733 SetSelection(0);
1735 CombatStop();
1737 ResetContestedPvP();
1739 // remove player from battleground on far teleport (when changing maps)
1740 if(BattleGround const* bg = GetBattleGround())
1742 // Note: at battleground join battleground id set before teleport
1743 // and we already will found "current" battleground
1744 // just need check that this is targeted map or leave
1745 if(bg->GetMapId() != mapid)
1746 LeaveBattleground(false); // don't teleport to entry point
1749 // remove pet on map change
1750 if (pet)
1751 UnsummonPetTemporaryIfAny();
1753 // remove all dyn objects
1754 RemoveAllDynObjects();
1756 // stop spellcasting
1757 // not attempt interrupt teleportation spell at caster teleport
1758 if(!(options & TELE_TO_SPELL))
1759 if(IsNonMeleeSpellCasted(true))
1760 InterruptNonMeleeSpells(true);
1762 //remove auras before removing from map...
1763 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1765 if(!GetSession()->PlayerLogout())
1767 // send transfer packets
1768 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1769 data << uint32(mapid);
1770 if (m_transport)
1772 data << m_transport->GetEntry() << GetMapId();
1774 GetSession()->SendPacket(&data);
1776 data.Initialize(SMSG_NEW_WORLD, (20));
1777 if (m_transport)
1779 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1781 else
1783 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1785 GetSession()->SendPacket( &data );
1786 SendSavedInstances();
1789 // remove from old map now
1790 if(oldmap)
1791 oldmap->Remove(this, false);
1793 // new final coordinates
1794 float final_x = x;
1795 float final_y = y;
1796 float final_z = z;
1797 float final_o = orientation;
1799 if(m_transport)
1801 final_x += m_movementInfo.t_x;
1802 final_y += m_movementInfo.t_y;
1803 final_z += m_movementInfo.t_z;
1804 final_o += m_movementInfo.t_o;
1807 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1808 SetFallInformation(0, final_z);
1809 // if the player is saved before worldportack (at logout for example)
1810 // this will be used instead of the current location in SaveToDB
1812 // move packet sent by client always after far teleport
1813 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1814 SetSemaphoreTeleportFar(true);
1816 else
1817 return false;
1819 return true;
1822 bool Player::TeleportToBGEntryPoint()
1824 ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
1825 ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
1826 return TeleportTo(m_bgData.joinPos);
1829 void Player::ProcessDelayedOperations()
1831 if(m_DelayedOperations == 0)
1832 return;
1834 if(m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
1836 ResurrectPlayer(0.0f, false);
1838 if(GetMaxHealth() > m_resurrectHealth)
1839 SetHealth( m_resurrectHealth );
1840 else
1841 SetHealth( GetMaxHealth() );
1843 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
1844 SetPower(POWER_MANA, m_resurrectMana );
1845 else
1846 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
1848 SetPower(POWER_RAGE, 0 );
1849 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
1851 SpawnCorpseBones();
1854 if(m_DelayedOperations & DELAYED_SAVE_PLAYER)
1856 SaveToDB();
1859 if(m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
1861 CastSpell(this, 26013, true); // Deserter
1864 if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
1866 if (m_bgData.mountSpell)
1868 CastSpell(this, m_bgData.mountSpell, true);
1869 m_bgData.mountSpell = 0;
1873 if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
1875 if (m_bgData.HasTaxiPath())
1877 m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
1878 m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
1879 m_bgData.ClearTaxiPath();
1881 ContinueTaxiFlight();
1885 //we have executed ALL delayed ops, so clear the flag
1886 m_DelayedOperations = 0;
1889 void Player::AddToWorld()
1891 ///- Do not add/remove the player from the object storage
1892 ///- It will crash when updating the ObjectAccessor
1893 ///- The player should only be added when logging in
1894 Unit::AddToWorld();
1896 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1898 if(m_items[i])
1899 m_items[i]->AddToWorld();
1903 void Player::RemoveFromWorld()
1905 // cleanup
1906 if(IsInWorld())
1908 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1909 UnsummonAllTotems();
1910 RemoveMiniPet();
1913 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1915 if(m_items[i])
1916 m_items[i]->RemoveFromWorld();
1919 ///- Do not add/remove the player from the object storage
1920 ///- It will crash when updating the ObjectAccessor
1921 ///- The player should only be removed when logging out
1922 Unit::RemoveFromWorld();
1925 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1927 float addRage;
1929 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1931 if(attacker)
1933 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1935 // talent who gave more rage on attack
1936 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1938 else
1940 addRage = damage/rageconversion*2.5;
1942 // Berserker Rage effect
1943 if(HasAura(18499,0))
1944 addRage *= 1.3;
1947 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1949 ModifyPower(POWER_RAGE, uint32(addRage*10));
1952 void Player::RegenerateAll(uint32 diff)
1954 // Not in combat or they have regeneration
1955 if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1956 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1958 RegenerateHealth(diff);
1959 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1961 Regenerate(POWER_RAGE, diff);
1962 if(getClass() == CLASS_DEATH_KNIGHT)
1963 Regenerate(POWER_RUNIC_POWER, diff);
1967 Regenerate(POWER_ENERGY, diff);
1969 Regenerate(POWER_MANA, diff);
1971 if (getClass() == CLASS_DEATH_KNIGHT)
1972 Regenerate(POWER_RUNE, diff);
1974 m_regenTimer = REGEN_TIME_FULL;
1977 // diff contains the time in milliseconds since last regen.
1978 void Player::Regenerate(Powers power, uint32 diff)
1980 uint32 curValue = GetPower(power);
1981 uint32 maxValue = GetMaxPower(power);
1983 float addvalue = 0.0f;
1985 switch (power)
1987 case POWER_MANA:
1989 bool recentCast = IsUnderLastManaUseEffect();
1990 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1991 if (recentCast)
1993 // Mangos Updates Mana in intervals of 2s, which is correct
1994 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1996 else
1998 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
2000 } break;
2001 case POWER_RAGE: // Regenerate rage
2003 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
2004 addvalue = 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
2005 } break;
2006 case POWER_ENERGY: // Regenerate energy (rogue)
2007 addvalue = 20;
2008 break;
2009 case POWER_RUNIC_POWER:
2011 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
2012 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
2013 } break;
2014 case POWER_RUNE:
2016 if (getClass() != CLASS_DEATH_KNIGHT)
2017 break;
2019 for(uint32 i = 0; i < MAX_RUNES; ++i)
2021 if(uint16 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
2022 SetRuneCooldown(i, (cd < diff) ? 0 : cd - diff);
2024 } break;
2025 case POWER_FOCUS:
2026 case POWER_HAPPINESS:
2027 case POWER_HEALTH:
2028 break;
2031 // Mana regen calculated in Player::UpdateManaRegen()
2032 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
2033 if(power != POWER_MANA)
2035 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
2036 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
2037 if ((*i)->GetModifier()->m_miscvalue == power)
2038 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
2041 // addvalue computed on a 2sec basis. => update to diff time
2042 addvalue *= float(diff) / REGEN_TIME_FULL;
2044 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
2046 curValue += uint32(addvalue);
2047 if (curValue > maxValue)
2048 curValue = maxValue;
2050 else
2052 if(curValue <= uint32(addvalue))
2053 curValue = 0;
2054 else
2055 curValue -= uint32(addvalue);
2057 SetPower(power, curValue);
2060 void Player::RegenerateHealth(uint32 diff)
2062 uint32 curValue = GetHealth();
2063 uint32 maxValue = GetMaxHealth();
2065 if (curValue >= maxValue) return;
2067 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
2069 float addvalue = 0.0f;
2071 // polymorphed case
2072 if ( IsPolymorphed() )
2073 addvalue = GetMaxHealth()/3;
2074 // normal regen case (maybe partly in combat case)
2075 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
2077 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
2078 if (!isInCombat())
2080 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
2081 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
2082 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
2084 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
2085 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
2087 if(!IsStandState())
2088 addvalue *= 1.5;
2091 // always regeneration bonus (including combat)
2092 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
2094 if(addvalue < 0)
2095 addvalue = 0;
2097 addvalue *= (float)diff / REGEN_TIME_FULL;
2099 ModifyHealth(int32(addvalue));
2102 Creature* Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
2104 // unit checks
2105 if (!guid || !IsInWorld() || isInFlight())
2106 return NULL;
2108 // exist (we need look pets also for some interaction (quest/etc)
2109 Creature *unit = GetMap()->GetCreatureOrPetOrVehicle(guid);
2110 if (!unit)
2111 return NULL;
2113 // appropriate npc type
2114 if (npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
2115 return NULL;
2117 if (npcflagmask == UNIT_NPC_FLAG_STABLEMASTER)
2119 if (getClass() != CLASS_HUNTER)
2120 return NULL;
2123 // if a dead unit should be able to talk - the creature must be alive and have special flags
2124 if (!unit->isAlive())
2125 return NULL;
2127 if (isAlive() && unit->isInvisibleForAlive())
2128 return NULL;
2130 // not allow interaction under control, but allow with own pets
2131 if (unit->GetCharmerGUID())
2132 return NULL;
2134 // not enemy
2135 if (unit->IsHostileTo(this))
2136 return NULL;
2138 // not unfriendly
2139 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
2140 if(factionTemplate->faction)
2141 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
2142 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
2143 return NULL;
2145 // not too far
2146 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
2147 return NULL;
2149 return unit;
2152 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, uint32 gameobject_type) const
2154 if (GameObject *go = GetMap()->GetGameObject(guid))
2156 if (uint32(go->GetGoType()) == gameobject_type || gameobject_type == MAX_GAMEOBJECT_TYPE)
2158 float maxdist;
2159 switch(go->GetGoType())
2161 // TODO: find out how the client calculates the maximal usage distance to spellless working
2162 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2163 case GAMEOBJECT_TYPE_GUILD_BANK:
2164 case GAMEOBJECT_TYPE_MAILBOX:
2165 maxdist = 10.0f;
2166 break;
2167 case GAMEOBJECT_TYPE_FISHINGHOLE:
2168 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2169 break;
2170 default:
2171 maxdist = INTERACTION_DISTANCE;
2172 break;
2175 if (go->IsWithinDistInMap(this, maxdist) && go->isSpawned())
2176 return go;
2178 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,
2179 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2182 return NULL;
2185 bool Player::IsUnderWater() const
2187 return IsInWater() &&
2188 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2191 void Player::SetInWater(bool apply)
2193 if(m_isInWater==apply)
2194 return;
2196 //define player in water by opcodes
2197 //move player's guid into HateOfflineList of those mobs
2198 //which can't swim and move guid back into ThreatList when
2199 //on surface.
2200 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2201 m_isInWater = apply;
2203 // remove auras that need water/land
2204 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2206 getHostileRefManager().updateThreatTables();
2209 void Player::SetGameMaster(bool on)
2211 if(on)
2213 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2214 setFaction(35);
2215 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2217 if (Pet* pet = GetPet())
2219 pet->setFaction(35);
2220 pet->getHostileRefManager().setOnlineOfflineState(false);
2223 for (int8 i = 0; i < MAX_TOTEM; ++i)
2224 if(m_TotemSlot[i])
2225 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2226 totem->setFaction(35);
2228 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2229 ResetContestedPvP();
2231 getHostileRefManager().setOnlineOfflineState(false);
2232 CombatStopWithPets();
2234 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2236 else
2238 // restore phase
2239 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2240 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2242 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2243 setFactionForRace(getRace());
2244 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2246 if (Pet* pet = GetPet())
2248 pet->setFaction(getFaction());
2249 pet->getHostileRefManager().setOnlineOfflineState(true);
2252 for (int8 i = 0; i < MAX_TOTEM; ++i)
2253 if(m_TotemSlot[i])
2254 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2255 totem->setFaction(getFaction());
2257 // restore FFA PvP Server state
2258 if(sWorld.IsFFAPvPRealm())
2259 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2261 // restore FFA PvP area state, remove not allowed for GM mounts
2262 UpdateArea(m_areaUpdateId);
2264 getHostileRefManager().setOnlineOfflineState(true);
2267 UpdateVisibilityForPlayer();
2270 void Player::SetGMVisible(bool on)
2272 if(on)
2274 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2276 // Reapply stealth/invisibility if active or show if not any
2277 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2278 SetVisibility(VISIBILITY_GROUP_STEALTH);
2279 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2280 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2281 else
2282 SetVisibility(VISIBILITY_ON);
2284 else
2286 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2288 SetAcceptWhispers(false);
2289 SetGameMaster(true);
2291 SetVisibility(VISIBILITY_OFF);
2295 bool Player::IsGroupVisibleFor(Player* p) const
2297 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2299 default: return IsInSameGroupWith(p);
2300 case 1: return IsInSameRaidWith(p);
2301 case 2: return GetTeam()==p->GetTeam();
2305 bool Player::IsInSameGroupWith(Player const* p) const
2307 return (p==this || (GetGroup() != NULL &&
2308 GetGroup()->SameSubGroup((Player*)this, (Player*)p)));
2311 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2312 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2313 void Player::UninviteFromGroup()
2315 Group* group = GetGroupInvite();
2316 if(!group)
2317 return;
2319 group->RemoveInvite(this);
2321 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2323 if(group->IsCreated())
2325 group->Disband(true);
2326 sObjectMgr.RemoveGroup(group);
2328 else
2329 group->RemoveAllInvites();
2331 delete group;
2335 void Player::RemoveFromGroup(Group* group, uint64 guid)
2337 if(group)
2339 if (group->RemoveMember(guid, 0) <= 1)
2341 // group->Disband(); already disbanded in RemoveMember
2342 sObjectMgr.RemoveGroup(group);
2343 delete group;
2344 // removemember sets the player's group pointer to NULL
2349 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2351 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2352 data << uint64(victim ? victim->GetGUID() : 0); // guid
2353 data << uint32(GivenXP+RestXP); // given experience
2354 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2355 if(victim)
2357 data << uint32(GivenXP); // experience without rested bonus
2358 data << float(1); // 1 - none 0 - 100% group bonus output
2360 data << uint8(0); // new 2.4.0
2361 GetSession()->SendPacket(&data);
2364 void Player::GiveXP(uint32 xp, Unit* victim)
2366 if ( xp < 1 )
2367 return;
2369 if(!isAlive())
2370 return;
2372 uint32 level = getLevel();
2374 // XP to money conversion processed in Player::RewardQuest
2375 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2376 return;
2378 if(victim)
2380 // handle SPELL_AURA_MOD_KILL_XP_PCT auras
2381 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT);
2382 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2383 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2385 else
2387 // handle SPELL_AURA_MOD_QUEST_XP_PCT auras
2388 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT);
2389 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2390 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2393 // XP resting bonus for kill
2394 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2396 SendLogXPGain(xp,victim,rested_bonus_xp);
2398 uint32 curXP = GetUInt32Value(PLAYER_XP);
2399 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2400 uint32 newXP = curXP + xp + rested_bonus_xp;
2402 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2404 newXP -= nextLvlXP;
2406 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2407 GiveLevel(level + 1);
2409 level = getLevel();
2410 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2413 SetUInt32Value(PLAYER_XP, newXP);
2416 // Update player to next level
2417 // Current player experience not update (must be update by caller)
2418 void Player::GiveLevel(uint32 level)
2420 if ( level == getLevel() )
2421 return;
2423 PlayerLevelInfo info;
2424 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2426 PlayerClassLevelInfo classInfo;
2427 sObjectMgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2429 // send levelup info to client
2430 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2431 data << uint32(level);
2432 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2433 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2434 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2435 data << uint32(0);
2436 data << uint32(0);
2437 data << uint32(0);
2438 data << uint32(0);
2439 data << uint32(0);
2440 data << uint32(0);
2441 // end for
2442 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2443 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2445 GetSession()->SendPacket(&data);
2447 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(level));
2449 //update level, max level of skills
2450 m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
2452 _ApplyAllLevelScaleItemMods(false);
2454 SetLevel(level);
2456 UpdateSkillsForLevel ();
2458 // save base values (bonuses already included in stored stats
2459 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2460 SetCreateStat(Stats(i), info.stats[i]);
2462 SetCreateHealth(classInfo.basehealth);
2463 SetCreateMana(classInfo.basemana);
2465 InitTalentForLevel();
2466 InitTaxiNodesForLevel();
2467 InitGlyphsForLevel();
2469 UpdateAllStats();
2471 // set current level health and mana/energy to maximum after applying all mods.
2472 SetHealth(GetMaxHealth());
2473 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2474 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2475 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2476 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2477 SetPower(POWER_FOCUS, 0);
2478 SetPower(POWER_HAPPINESS, 0);
2480 _ApplyAllLevelScaleItemMods(true);
2482 // update level to hunter/summon pet
2483 if (Pet* pet = GetPet())
2484 pet->SynchronizeLevelWithOwner();
2486 if (MailLevelReward const* mailReward = sObjectMgr.GetMailLevelReward(level,getRaceMask()))
2487 MailDraft(mailReward->mailTemplateId).SendMailTo(this,MailSender(MAIL_CREATURE,mailReward->senderEntry));
2489 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2492 void Player::InitTalentForLevel()
2494 uint32 level = getLevel();
2495 // talents base at level diff ( talents = level - 9 but some can be used already)
2496 if(level < 10)
2498 // Remove all talent points
2499 if(m_usedTalentCount > 0) // Free any used talents
2501 resetTalents(true);
2502 SetFreeTalentPoints(0);
2505 else
2507 uint32 talentPointsForLevel = CalculateTalentsPoints();
2509 // if used more that have then reset
2510 if(m_usedTalentCount > talentPointsForLevel)
2512 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2513 resetTalents(true);
2514 else
2515 SetFreeTalentPoints(0);
2517 // else update amount of free points
2518 else
2519 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2522 if(!GetSession()->PlayerLoading())
2523 SendTalentsInfoData(false); // update at client
2526 void Player::InitStatsForLevel(bool reapplyMods)
2528 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2529 _RemoveAllStatBonuses();
2531 PlayerClassLevelInfo classInfo;
2532 sObjectMgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2534 PlayerLevelInfo info;
2535 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2537 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2538 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(getLevel()));
2540 // reset before any aura state sources (health set/aura apply)
2541 SetUInt32Value(UNIT_FIELD_AURASTATE, 0);
2543 UpdateSkillsForLevel ();
2545 // set default cast time multiplier
2546 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2548 // reset size before reapply auras
2549 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2551 // save base values (bonuses already included in stored stats
2552 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2553 SetCreateStat(Stats(i), info.stats[i]);
2555 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2556 SetStat(Stats(i), info.stats[i]);
2558 SetCreateHealth(classInfo.basehealth);
2560 //set create powers
2561 SetCreateMana(classInfo.basemana);
2563 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2565 InitStatBuffMods();
2567 //reset rating fields values
2568 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2569 SetUInt32Value(index, 0);
2571 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2572 for (int i = 0; i < 7; ++i)
2574 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2575 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2576 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2579 //reset attack power, damage and attack speed fields
2580 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2581 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2582 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2584 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2585 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2586 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2587 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2588 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2589 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2591 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2592 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2593 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2594 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2595 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2596 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2598 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2599 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2600 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2601 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2603 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2604 for (uint8 i = 0; i < 7; ++i)
2605 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2607 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2608 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2609 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2611 // Dodge percentage
2612 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2614 // set armor (resistance 0) to original value (create_agility*2)
2615 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2616 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2617 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2618 // set other resistance to original value (0)
2619 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2621 SetResistance(SpellSchools(i), 0);
2622 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2623 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2626 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2627 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2628 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2630 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2631 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2633 // Reset no reagent cost field
2634 for(int i = 0; i < 3; ++i)
2635 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2636 // Init data for form but skip reapply item mods for form
2637 InitDataForForm(reapplyMods);
2639 // save new stats
2640 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2641 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2643 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2645 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2646 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2648 // cleanup unit flags (will be re-applied if need at aura load).
2649 RemoveFlag( UNIT_FIELD_FLAGS,
2650 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2651 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2652 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2653 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2654 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2655 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2657 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2659 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2660 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2662 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2663 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2665 // restore if need some important flags
2666 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2668 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2669 _ApplyAllStatBonuses();
2671 // set current level health and mana/energy to maximum after applying all mods.
2672 SetHealth(GetMaxHealth());
2673 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2674 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2675 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2676 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2677 SetPower(POWER_FOCUS, 0);
2678 SetPower(POWER_HAPPINESS, 0);
2679 SetPower(POWER_RUNIC_POWER, 0);
2681 // update level to hunter/summon pet
2682 if (Pet* pet = GetPet())
2683 pet->SynchronizeLevelWithOwner();
2686 void Player::SendInitialSpells()
2688 time_t curTime = time(NULL);
2689 time_t infTime = curTime + infinityCooldownDelayCheck;
2691 uint16 spellCount = 0;
2693 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2694 data << uint8(0);
2696 size_t countPos = data.wpos();
2697 data << uint16(spellCount); // spell count placeholder
2699 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2701 if(itr->second->state == PLAYERSPELL_REMOVED)
2702 continue;
2704 if(!itr->second->active || itr->second->disabled)
2705 continue;
2707 data << uint32(itr->first);
2708 data << uint16(0); // it's not slot id
2710 spellCount +=1;
2713 data.put<uint16>(countPos,spellCount); // write real count value
2715 uint16 spellCooldowns = m_spellCooldowns.size();
2716 data << uint16(spellCooldowns);
2717 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2719 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2720 if(!sEntry)
2721 continue;
2723 data << uint32(itr->first);
2725 data << uint16(itr->second.itemid); // cast item id
2726 data << uint16(sEntry->Category); // spell category
2728 // send infinity cooldown in special format
2729 if(itr->second.end >= infTime)
2731 data << uint32(1); // cooldown
2732 data << uint32(0x80000000); // category cooldown
2733 continue;
2736 time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILISECONDS : 0;
2738 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2740 data << uint32(0); // cooldown
2741 data << uint32(cooldown); // category cooldown
2743 else
2745 data << uint32(cooldown); // cooldown
2746 data << uint32(0); // category cooldown
2750 GetSession()->SendPacket(&data);
2752 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2755 void Player::RemoveMail(uint32 id)
2757 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2759 if ((*itr)->messageID == id)
2761 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2762 m_mail.erase(itr);
2763 return;
2768 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2770 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2771 data << (uint32) mailId;
2772 data << (uint32) mailAction;
2773 data << (uint32) mailError;
2774 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2775 data << (uint32) equipError;
2776 else if( mailAction == MAIL_ITEM_TAKEN )
2778 data << (uint32) item_guid; // item guid low?
2779 data << (uint32) item_count; // item count?
2781 GetSession()->SendPacket(&data);
2784 void Player::SendNewMail()
2786 // deliver undelivered mail
2787 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2788 data << (uint32) 0;
2789 GetSession()->SendPacket(&data);
2792 void Player::UpdateNextMailTimeAndUnreads()
2794 // calculate next delivery time (min. from non-delivered mails
2795 // and recalculate unReadMail
2796 time_t cTime = time(NULL);
2797 m_nextMailDelivereTime = 0;
2798 unReadMails = 0;
2799 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2801 if((*itr)->deliver_time > cTime)
2803 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2804 m_nextMailDelivereTime = (*itr)->deliver_time;
2806 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2807 ++unReadMails;
2811 void Player::AddNewMailDeliverTime(time_t deliver_time)
2813 if(deliver_time <= time(NULL)) // ready now
2815 ++unReadMails;
2816 SendNewMail();
2818 else // not ready and no have ready mails
2820 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2821 m_nextMailDelivereTime = deliver_time;
2825 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2827 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2828 if (!spellInfo)
2830 // do character spell book cleanup (all characters)
2831 if(!IsInWorld() && !learning) // spell load case
2833 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2834 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2836 else
2837 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2839 return false;
2842 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2844 // do character spell book cleanup (all characters)
2845 if(!IsInWorld() && !learning) // spell load case
2847 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2848 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2850 else
2851 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2853 return false;
2856 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2858 bool dependent_set = false;
2859 bool disabled_case = false;
2860 bool superceded_old = false;
2862 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2863 if (itr != m_spells.end())
2865 uint32 next_active_spell_id = 0;
2866 // fix activate state for non-stackable low rank (and find next spell for !active case)
2867 if(!SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
2869 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
2870 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2872 if(HasSpell(next_itr->second))
2874 // high rank already known so this must !active
2875 active = false;
2876 next_active_spell_id = next_itr->second;
2877 break;
2882 // not do anything if already known in expected state
2883 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2884 itr->second->dependent == dependent && itr->second->disabled == disabled)
2886 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2887 itr->second->state = PLAYERSPELL_UNCHANGED;
2889 return false;
2892 // dependent spell known as not dependent, overwrite state
2893 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2895 itr->second->dependent = dependent;
2896 if (itr->second->state != PLAYERSPELL_NEW)
2897 itr->second->state = PLAYERSPELL_CHANGED;
2898 dependent_set = true;
2901 // update active state for known spell
2902 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2904 itr->second->active = active;
2906 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2907 itr->second->state = PLAYERSPELL_UNCHANGED;
2908 else if(itr->second->state != PLAYERSPELL_NEW)
2909 itr->second->state = PLAYERSPELL_CHANGED;
2911 if(active)
2913 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2914 CastSpell (this,spell_id,true);
2916 else if(IsInWorld())
2918 if(next_active_spell_id)
2920 // update spell ranks in spellbook and action bar
2921 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2922 data << uint32(spell_id);
2923 data << uint32(next_active_spell_id);
2924 GetSession()->SendPacket( &data );
2926 else
2928 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2929 data << uint32(spell_id);
2930 GetSession()->SendPacket(&data);
2934 return active; // learn (show in spell book if active now)
2937 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2939 if(itr->second->state != PLAYERSPELL_NEW)
2940 itr->second->state = PLAYERSPELL_CHANGED;
2941 itr->second->disabled = disabled;
2943 if(disabled)
2944 return false;
2946 disabled_case = true;
2948 else switch(itr->second->state)
2950 case PLAYERSPELL_UNCHANGED: // known saved spell
2951 return false;
2952 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2954 delete itr->second;
2955 m_spells.erase(itr);
2956 state = PLAYERSPELL_CHANGED;
2957 break; // need re-add
2959 default: // known not saved yet spell (new or modified)
2961 // can be in case spell loading but learned at some previous spell loading
2962 if(!IsInWorld() && !learning && !dependent_set)
2963 itr->second->state = PLAYERSPELL_UNCHANGED;
2965 return false;
2970 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2972 // talent: unlearn all other talent ranks (high and low)
2973 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2975 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2977 for(int i=0; i < MAX_TALENT_RANK; ++i)
2979 // skip learning spell and no rank spell case
2980 uint32 rankSpellId = talentInfo->RankID[i];
2981 if(!rankSpellId || rankSpellId==spell_id)
2982 continue;
2984 removeSpell(rankSpellId,false,false);
2988 // non talent spell: learn low ranks (recursive call)
2989 else if(uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id))
2991 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2992 addSpell(prev_spell,active,true,true,disabled);
2993 else // at normal learning
2994 learnSpell(prev_spell,true);
2997 PlayerSpell *newspell = new PlayerSpell;
2998 newspell->state = state;
2999 newspell->active = active;
3000 newspell->dependent = dependent;
3001 newspell->disabled = disabled;
3003 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
3004 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
3006 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
3008 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
3009 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
3010 if(!i_spellInfo) continue;
3012 if( sSpellMgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
3014 if(itr2->second->active)
3016 if(sSpellMgr.IsHighRankOfSpell(spell_id,itr2->first))
3018 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3020 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3021 data << uint32(itr2->first);
3022 data << uint32(spell_id);
3023 GetSession()->SendPacket( &data );
3026 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
3027 itr2->second->active = false;
3028 if(itr2->second->state != PLAYERSPELL_NEW)
3029 itr2->second->state = PLAYERSPELL_CHANGED;
3030 superceded_old = true; // new spell replace old in action bars and spell book.
3032 else if(sSpellMgr.IsHighRankOfSpell(itr2->first,spell_id))
3034 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3036 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3037 data << uint32(spell_id);
3038 data << uint32(itr2->first);
3039 GetSession()->SendPacket( &data );
3042 // mark new spell as disable (not learned yet for client and will not learned)
3043 newspell->active = false;
3044 if(newspell->state != PLAYERSPELL_NEW)
3045 newspell->state = PLAYERSPELL_CHANGED;
3052 m_spells[spell_id] = newspell;
3054 // return false if spell disabled
3055 if (newspell->disabled)
3056 return false;
3059 uint32 talentCost = GetTalentSpellCost(spell_id);
3061 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3062 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3063 if (talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
3065 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3066 CastSpell(this, spell_id, true);
3068 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3069 else if (IsPassiveSpell(spell_id))
3071 if (IsNeedCastPassiveSpellAtLearn(spellInfo))
3072 CastSpell(this, spell_id, true);
3074 else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
3076 CastSpell(this, spell_id, true);
3077 return false;
3080 // update used talent points count
3081 m_usedTalentCount += talentCost;
3083 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3084 if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
3086 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3087 SetFreePrimaryProfessions(freeProfs-1);
3090 // add dependent skills
3091 uint16 maxskill = GetMaxSkillValueForLevel();
3093 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3095 SkillLineAbilityMapBounds skill_bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3097 if (spellLearnSkill)
3099 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
3100 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
3102 if (skill_value < spellLearnSkill->value)
3103 skill_value = spellLearnSkill->value;
3105 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
3107 if (skill_max_value < new_skill_max_value)
3108 skill_max_value = new_skill_max_value;
3110 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
3112 else
3114 // not ranked skills
3115 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3117 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3118 if (!pSkill)
3119 continue;
3121 if (HasSkill(pSkill->id))
3122 continue;
3124 if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3125 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3126 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3128 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
3130 case SKILL_RANGE_LANGUAGE:
3131 SetSkill(pSkill->id, 300, 300 );
3132 break;
3133 case SKILL_RANGE_LEVEL:
3134 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
3135 break;
3136 case SKILL_RANGE_MONO:
3137 SetSkill(pSkill->id, 1, 1 );
3138 break;
3139 default:
3140 break;
3146 // learn dependent spells
3147 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3149 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3151 if (!itr2->second.autoLearned)
3153 if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
3154 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
3155 else // at normal learning
3156 learnSpell(itr2->second.spell,true);
3160 if (!GetSession()->PlayerLoading())
3162 // not ranked skills
3163 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3165 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3166 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3169 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3172 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3173 return active && !disabled && !superceded_old;
3176 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3178 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3179 // talent dependent passives activated at form apply have proper stance data
3180 bool need_cast = (!spellInfo->Stances || (m_form != 0 && (spellInfo->Stances & (1<<(m_form-1)))));
3182 //Check CasterAuraStates
3183 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3186 void Player::learnSpell(uint32 spell_id, bool dependent)
3188 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3190 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3191 bool active = disabled ? itr->second->active : true;
3193 bool learning = addSpell(spell_id,active,true,dependent,false);
3195 // learn all disabled higher ranks (recursive)
3196 if(disabled)
3198 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3199 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3201 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3202 if (iter != m_spells.end() && iter->second->disabled)
3203 learnSpell(i->second,false);
3207 // prevent duplicated entires in spell book, also not send if not in world (loading)
3208 if(!learning || !IsInWorld ())
3209 return;
3211 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3212 data << uint32(spell_id);
3213 GetSession()->SendPacket(&data);
3216 void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bool sendUpdate)
3218 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3219 if (itr == m_spells.end())
3220 return;
3222 if (itr->second->state == PLAYERSPELL_REMOVED || (disabled && itr->second->disabled))
3223 return;
3225 // unlearn non talent higher ranks (recursive)
3226 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3227 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3228 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3229 removeSpell(itr2->second,disabled,false);
3231 // re-search, it can be corrupted in prev loop
3232 itr = m_spells.find(spell_id);
3233 if (itr == m_spells.end())
3234 return; // already unleared
3236 bool cur_active = itr->second->active;
3237 bool cur_dependent = itr->second->dependent;
3239 if (disabled)
3241 itr->second->disabled = disabled;
3242 if(itr->second->state != PLAYERSPELL_NEW)
3243 itr->second->state = PLAYERSPELL_CHANGED;
3245 else
3247 if(itr->second->state == PLAYERSPELL_NEW)
3249 delete itr->second;
3250 m_spells.erase(itr);
3252 else
3253 itr->second->state = PLAYERSPELL_REMOVED;
3256 RemoveAurasDueToSpell(spell_id);
3258 // remove pet auras
3259 for(int i = 0; i < 3; ++i)
3260 if(PetAura const* petSpell = sSpellMgr.GetPetAura(spell_id, i))
3261 RemovePetAura(petSpell);
3263 // free talent points
3264 uint32 talentCosts = GetTalentSpellCost(spell_id);
3265 if(talentCosts > 0)
3267 if(talentCosts < m_usedTalentCount)
3268 m_usedTalentCount -= talentCosts;
3269 else
3270 m_usedTalentCount = 0;
3273 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3274 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3276 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3277 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3278 SetFreePrimaryProfessions(freeProfs);
3281 // remove dependent skill
3282 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3283 if(spellLearnSkill)
3285 uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id);
3286 if(!prev_spell) // first rank, remove skill
3287 SetSkill(spellLearnSkill->skill,0,0);
3288 else
3290 // search prev. skill setting by spell ranks chain
3291 SpellLearnSkillNode const* prevSkill = sSpellMgr.GetSpellLearnSkill(prev_spell);
3292 while(!prevSkill && prev_spell)
3294 prev_spell = sSpellMgr.GetPrevSpellInChain(prev_spell);
3295 prevSkill = sSpellMgr.GetSpellLearnSkill(sSpellMgr.GetFirstSpellInChain(prev_spell));
3298 if (!prevSkill) // not found prev skill setting, remove skill
3299 SetSkill(spellLearnSkill->skill,0,0);
3300 else // set to prev. skill setting values
3302 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3303 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3305 if (skill_value > prevSkill->value)
3306 skill_value = prevSkill->value;
3308 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3310 if (skill_max_value > new_skill_max_value)
3311 skill_max_value = new_skill_max_value;
3313 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3318 else
3320 // not ranked skills
3321 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3323 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
3325 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3326 if (!pSkill)
3327 continue;
3329 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
3330 pSkill->categoryId != SKILL_CATEGORY_CLASS ||// not unlearn class skills (spellbook/talent pages)
3331 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3332 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3334 // not reset skills for professions and racial abilities
3335 if ((pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3336 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0))
3337 continue;
3339 SetSkill(pSkill->id, 0, 0 );
3344 // remove dependent spells
3345 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3347 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3348 removeSpell(itr2->second.spell, disabled);
3350 // activate lesser rank in spellbook/action bar, and cast it if need
3351 bool prev_activate = false;
3353 if (uint32 prev_id = sSpellMgr.GetPrevSpellInChain (spell_id))
3355 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3357 // if talent then lesser rank also talent and need learn
3358 if (talentCosts)
3360 if(learn_low_rank)
3361 learnSpell (prev_id,false);
3363 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3364 else if (cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
3366 // need manually update dependence state (learn spell ignore like attempts)
3367 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3368 if (prev_itr != m_spells.end())
3370 if (prev_itr->second->dependent != cur_dependent)
3372 prev_itr->second->dependent = cur_dependent;
3373 if (prev_itr->second->state != PLAYERSPELL_NEW)
3374 prev_itr->second->state = PLAYERSPELL_CHANGED;
3377 // now re-learn if need re-activate
3378 if (cur_active && !prev_itr->second->active && learn_low_rank)
3380 if (addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3382 // downgrade spell ranks in spellbook and action bar
3383 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3384 data << uint32(spell_id);
3385 data << uint32(prev_id);
3386 GetSession()->SendPacket( &data );
3387 prev_activate = true;
3394 // remove from spell book if not replaced by lesser rank
3395 if (!prev_activate && sendUpdate)
3397 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3398 data << uint32(spell_id);
3399 GetSession()->SendPacket(&data);
3403 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3405 m_spellCooldowns.erase(spell_id);
3407 if(update)
3408 SendClearCooldown(spell_id, this);
3411 void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
3413 SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
3414 if (ct == sSpellCategoryStore.end())
3415 return;
3417 const SpellCategorySet& ct_set = ct->second;
3418 for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
3420 if (ct_set.find(i->first) != ct_set.end())
3421 RemoveSpellCooldown((i++)->first, update);
3422 else
3423 ++i;
3427 void Player::RemoveArenaSpellCooldowns()
3429 // remove cooldowns on spells that has < 15 min CD
3430 SpellCooldowns::iterator itr, next;
3431 // iterate spell cooldowns
3432 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3434 next = itr;
3435 ++next;
3436 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3437 // check if spellentry is present and if the cooldown is less than 15 mins
3438 if( entry &&
3439 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3440 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3442 // remove & notify
3443 RemoveSpellCooldown(itr->first, true);
3448 void Player::RemoveAllSpellCooldown()
3450 if(!m_spellCooldowns.empty())
3452 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3453 SendClearCooldown(itr->first, this);
3455 m_spellCooldowns.clear();
3459 void Player::_LoadSpellCooldowns(QueryResult *result)
3461 // some cooldowns can be already set at aura loading...
3463 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3465 if(result)
3467 time_t curTime = time(NULL);
3471 Field *fields = result->Fetch();
3473 uint32 spell_id = fields[0].GetUInt32();
3474 uint32 item_id = fields[1].GetUInt32();
3475 time_t db_time = (time_t)fields[2].GetUInt64();
3477 if(!sSpellStore.LookupEntry(spell_id))
3479 sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3480 continue;
3483 // skip outdated cooldown
3484 if(db_time <= curTime)
3485 continue;
3487 AddSpellCooldown(spell_id, item_id, db_time);
3489 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3491 while( result->NextRow() );
3493 delete result;
3497 void Player::_SaveSpellCooldowns()
3499 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3501 time_t curTime = time(NULL);
3502 time_t infTime = curTime + infinityCooldownDelayCheck;
3504 /* copied following sql-code partly from achievementmgr */
3505 bool first_round = true;
3506 std::ostringstream ss;
3508 // remove outdated and save active
3509 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3511 if(itr->second.end <= curTime)
3512 m_spellCooldowns.erase(itr++);
3513 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3515 if (first_round)
3517 ss << "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ";
3518 first_round = false;
3520 // next new/changed record prefix
3521 else
3522 ss << ", ";
3523 ss << "(" << GetGUIDLow() << "," << itr->first << "," << itr->second.itemid << "," << uint64(itr->second.end) << ")";
3524 ++itr;
3526 else
3527 ++itr;
3530 // if something changed execute
3531 if (!first_round)
3532 CharacterDatabase.Execute( ss.str().c_str() );
3535 uint32 Player::resetTalentsCost() const
3537 // The first time reset costs 1 gold
3538 if(m_resetTalentsCost < 1*GOLD)
3539 return 1*GOLD;
3540 // then 5 gold
3541 else if(m_resetTalentsCost < 5*GOLD)
3542 return 5*GOLD;
3543 // After that it increases in increments of 5 gold
3544 else if(m_resetTalentsCost < 10*GOLD)
3545 return 10*GOLD;
3546 else
3548 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3549 if(months > 0)
3551 // This cost will be reduced by a rate of 5 gold per month
3552 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3553 // to a minimum of 10 gold.
3554 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3556 else
3558 // After that it increases in increments of 5 gold
3559 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3560 // until it hits a cap of 50 gold.
3561 if(new_cost > 50*GOLD)
3562 new_cost = 50*GOLD;
3563 return new_cost;
3568 bool Player::resetTalents(bool no_cost)
3570 // not need after this call
3571 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3572 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
3574 uint32 talentPointsForLevel = CalculateTalentsPoints();
3576 if (m_usedTalentCount == 0)
3578 SetFreeTalentPoints(talentPointsForLevel);
3579 return false;
3582 uint32 cost = 0;
3584 if(!no_cost)
3586 cost = resetTalentsCost();
3588 if (GetMoney() < cost)
3590 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3591 return false;
3595 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3597 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3599 if (!talentInfo) continue;
3601 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3603 if(!talentTabInfo)
3604 continue;
3606 // unlearn only talents for character class
3607 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3608 // to prevent unexpected lost normal learned spell skip another class talents
3609 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3610 continue;
3612 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3614 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3616 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3618 ++itr;
3619 continue;
3622 // remove learned spells (all ranks)
3623 uint32 itrFirstId = sSpellMgr.GetFirstSpellInChain(itr->first);
3625 // unlearn if first rank is talent or learned by talent
3626 if (itrFirstId == talentInfo->RankID[j])
3628 removeSpell(itr->first,!IsPassiveSpell(itr->first),false);
3629 itr = GetSpellMap().begin();
3630 continue;
3632 else if (sSpellMgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3634 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3635 itr = GetSpellMap().begin();
3636 continue;
3638 else
3639 ++itr;
3644 SetFreeTalentPoints(talentPointsForLevel);
3646 if(!no_cost)
3648 ModifyMoney(-(int32)cost);
3649 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3650 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3652 m_resetTalentsCost = cost;
3653 m_resetTalentsTime = time(NULL);
3656 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3657 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3658 /* when prev line will dropped use next line
3659 if(Pet* pet = GetPet())
3661 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3662 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3667 if(m_canTitanGrip)
3669 m_canTitanGrip = false;
3670 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3671 AutoUnequipOffhandIfNeed();
3674 return true;
3677 Mail* Player::GetMail(uint32 id)
3679 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3681 if ((*itr)->messageID == id)
3683 return (*itr);
3686 return NULL;
3689 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3691 if(target == this)
3693 Object::_SetCreateBits(updateMask, target);
3695 else
3697 for(uint16 index = 0; index < m_valuesCount; index++)
3699 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3700 updateMask->SetBit(index);
3705 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3707 if(target == this)
3709 Object::_SetUpdateBits(updateMask, target);
3711 else
3713 Object::_SetUpdateBits(updateMask, target);
3714 *updateMask &= updateVisualBits;
3718 void Player::InitVisibleBits()
3720 updateVisualBits.SetCount(PLAYER_END);
3722 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3723 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3724 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3725 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3726 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3727 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3728 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3729 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3730 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3731 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3732 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3733 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3734 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3735 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3736 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3737 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3738 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3739 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3740 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3741 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3742 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3743 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3744 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3745 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3746 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3747 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3748 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3749 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3750 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3751 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3752 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3753 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3754 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3755 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3756 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3757 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3758 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3759 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3760 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3761 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3762 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3763 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3764 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3765 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3766 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3767 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3768 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3769 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3770 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3771 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3772 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3773 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3774 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3775 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3776 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3778 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3779 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3780 updateVisualBits.SetBit(PLAYER_FLAGS);
3781 updateVisualBits.SetBit(PLAYER_GUILDID);
3782 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3783 updateVisualBits.SetBit(PLAYER_BYTES);
3784 updateVisualBits.SetBit(PLAYER_BYTES_2);
3785 updateVisualBits.SetBit(PLAYER_BYTES_3);
3786 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3787 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3789 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3790 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += MAX_QUEST_OFFSET)
3791 updateVisualBits.SetBit(i);
3793 // Players visible items are not inventory stuff
3794 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3796 uint32 offset = i * 2;
3798 // item entry
3799 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3800 // enchant
3801 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3804 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3807 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3809 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3811 if(m_items[i] == NULL)
3812 continue;
3814 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3817 if(target == this)
3819 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3821 if(m_items[i] == NULL)
3822 continue;
3824 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3826 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3828 if(m_items[i] == NULL)
3829 continue;
3831 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3835 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3838 void Player::DestroyForPlayer( Player *target, bool anim ) const
3840 Unit::DestroyForPlayer( target, anim );
3842 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3844 if(m_items[i] == NULL)
3845 continue;
3847 m_items[i]->DestroyForPlayer( target );
3850 if(target == this)
3852 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3854 if(m_items[i] == NULL)
3855 continue;
3857 m_items[i]->DestroyForPlayer( target );
3859 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3861 if(m_items[i] == NULL)
3862 continue;
3864 m_items[i]->DestroyForPlayer( target );
3869 bool Player::HasSpell(uint32 spell) const
3871 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3872 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3873 !itr->second->disabled);
3876 bool Player::HasActiveSpell(uint32 spell) const
3878 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3879 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3880 itr->second->active && !itr->second->disabled);
3883 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3885 if (!trainer_spell)
3886 return TRAINER_SPELL_RED;
3888 if (!trainer_spell->learnedSpell)
3889 return TRAINER_SPELL_RED;
3891 // known spell
3892 if(HasSpell(trainer_spell->learnedSpell))
3893 return TRAINER_SPELL_GRAY;
3895 // check race/class requirement
3896 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3897 return TRAINER_SPELL_RED;
3899 // check level requirement
3900 if(getLevel() < trainer_spell->reqLevel)
3901 return TRAINER_SPELL_RED;
3903 if(SpellChainNode const* spell_chain = sSpellMgr.GetSpellChainNode(trainer_spell->learnedSpell))
3905 // check prev.rank requirement
3906 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3907 return TRAINER_SPELL_RED;
3909 // check additional spell requirement
3910 if(spell_chain->req && !HasSpell(spell_chain->req))
3911 return TRAINER_SPELL_RED;
3914 // check skill requirement
3915 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3916 return TRAINER_SPELL_RED;
3918 // exist, already checked at loading
3919 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3921 // secondary prof. or not prof. spell
3922 uint32 skill = spell->EffectMiscValue[1];
3924 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3925 return TRAINER_SPELL_GREEN;
3927 // check primary prof. limit
3928 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
3929 return TRAINER_SPELL_GREEN_DISABLED;
3931 return TRAINER_SPELL_GREEN;
3934 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3936 uint32 guid = GUID_LOPART(playerguid);
3938 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3939 // bones will be deleted by corpse/bones deleting thread shortly
3940 sObjectAccessor.ConvertCorpseForPlayer(playerguid);
3942 // remove from guild
3943 uint32 guildId = GetGuildIdFromDB(playerguid);
3944 if(guildId != 0)
3946 Guild* guild = sObjectMgr.GetGuildById(guildId);
3947 if(guild)
3948 guild->DelMember(guid);
3951 // remove from arena teams
3952 LeaveAllArenaTeams(playerguid);
3954 // the player was uninvited already on logout so just remove from group
3955 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3956 if(resultGroup)
3958 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3959 delete resultGroup;
3960 Group* group = sObjectMgr.GetGroupByLeader(leaderGuid);
3961 if(group)
3963 RemoveFromGroup(group, playerguid);
3967 // remove signs from petitions (also remove petitions if owner);
3968 RemovePetitionsAndSigns(playerguid, 10);
3970 // return back all mails with COD and Item 0 1 2 3 4 5 6 7
3971 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);
3972 if(resultMail)
3976 Field *fields = resultMail->Fetch();
3978 uint32 mail_id = fields[0].GetUInt32();
3979 uint16 mailType = fields[1].GetUInt16();
3980 uint16 mailTemplateId= fields[2].GetUInt16();
3981 uint32 sender = fields[3].GetUInt32();
3982 std::string subject = fields[4].GetCppString();
3983 uint32 itemTextId = fields[5].GetUInt32();
3984 uint32 money = fields[6].GetUInt32();
3985 bool has_items = fields[7].GetBool();
3987 //we can return mail now
3988 //so firstly delete the old one
3989 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3991 // mail not from player
3992 if (mailType != MAIL_NORMAL)
3994 if(has_items)
3995 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3996 continue;
3999 MailDraft draft(subject, itemTextId);
4000 if (mailTemplateId)
4001 draft = MailDraft(mailTemplateId,false); // itesm already included
4003 if(has_items)
4005 // data needs to be at first place for Item::LoadFromDB
4006 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);
4007 if(resultItems)
4011 Field *fields2 = resultItems->Fetch();
4013 uint32 item_guidlow = fields2[1].GetUInt32();
4014 uint32 item_template = fields2[2].GetUInt32();
4016 ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_template);
4017 if(!itemProto)
4019 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
4020 continue;
4023 Item *pItem = NewItemOrBag(itemProto);
4024 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
4026 pItem->FSetState(ITEM_REMOVED);
4027 pItem->SaveToDB(); // it also deletes item object !
4028 continue;
4031 draft.AddItem(pItem);
4033 while (resultItems->NextRow());
4035 delete resultItems;
4039 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
4041 uint32 pl_account = sObjectMgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
4043 draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender);
4045 while (resultMail->NextRow());
4047 delete resultMail;
4050 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
4051 // Get guids of character's pets, will deleted in transaction
4052 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
4054 // NOW we can finally clear other DB data related to character
4055 CharacterDatabase.BeginTransaction();
4056 if (resultPets)
4060 Field *fields3 = resultPets->Fetch();
4061 uint32 petguidlow = fields3[0].GetUInt32();
4062 Pet::DeleteFromDB(petguidlow);
4063 } while (resultPets->NextRow());
4064 delete resultPets;
4067 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
4068 CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid);
4069 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
4070 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
4071 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
4072 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
4073 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
4074 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
4075 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
4076 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
4077 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
4078 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
4079 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u'",guid);
4080 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
4081 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
4082 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
4083 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
4084 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
4085 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
4086 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
4087 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
4088 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
4089 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
4090 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
4091 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
4092 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u'",guid);
4093 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid);
4094 CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid);
4095 CharacterDatabase.CommitTransaction();
4097 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4098 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
4101 void Player::SetMovement(PlayerMovementType pType)
4103 WorldPacket data;
4104 switch(pType)
4106 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
4107 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
4108 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
4109 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
4110 default:
4111 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
4112 return;
4114 data.append(GetPackGUID());
4115 data << uint32(0);
4116 GetSession()->SendPacket( &data );
4119 /* Preconditions:
4120 - a resurrectable corpse must not be loaded for the player (only bones)
4121 - the player must be in world
4123 void Player::BuildPlayerRepop()
4125 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
4126 data.append(GetPackGUID());
4127 GetSession()->SendPacket(&data);
4129 if(getRace() == RACE_NIGHTELF)
4130 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)
4131 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4133 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4134 // there must be SMSG.STOP_MIRROR_TIMER
4135 // there we must send 888 opcode
4137 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4138 if(GetCorpse())
4140 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4141 assert(false);
4144 // create a corpse and place it at the player's location
4145 CreateCorpse();
4146 Corpse *corpse = GetCorpse();
4147 if(!corpse)
4149 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4150 return;
4152 GetMap()->Add(corpse);
4154 // convert player body to ghost
4155 SetHealth( 1 );
4157 SetMovement(MOVE_WATER_WALK);
4158 if(!GetSession()->isLogingOut())
4159 SetMovement(MOVE_UNROOT);
4161 // BG - remove insignia related
4162 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
4164 SendCorpseReclaimDelay();
4166 // to prevent cheating
4167 corpse->ResetGhostTime();
4169 StopMirrorTimers(); //disable timers(bars)
4171 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
4173 // set and clear other
4174 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
4177 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
4179 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
4180 data << uint32(-1);
4181 data << float(0);
4182 data << float(0);
4183 data << float(0);
4184 GetSession()->SendPacket(&data);
4186 // speed change, land walk
4188 // remove death flag + set aura
4189 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4190 if(getRace() == RACE_NIGHTELF)
4191 RemoveAurasDueToSpell(20584); // speed bonuses
4192 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4194 setDeathState(ALIVE);
4196 SetMovement(MOVE_LAND_WALK);
4197 SetMovement(MOVE_UNROOT);
4199 m_deathTimer = 0;
4201 // set health/powers (0- will be set in caller)
4202 if(restore_percent>0.0f)
4204 SetHealth(uint32(GetMaxHealth()*restore_percent));
4205 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4206 SetPower(POWER_RAGE, 0);
4207 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4210 // trigger update zone for alive state zone updates
4211 uint32 newzone, newarea;
4212 GetZoneAndAreaId(newzone,newarea);
4213 UpdateZone(newzone,newarea);
4215 // update visibility
4216 UpdateVisibilityForPlayer();
4218 if(!applySickness)
4219 return;
4221 //Characters from level 1-10 are not affected by resurrection sickness.
4222 //Characters from level 11-19 will suffer from one minute of sickness
4223 //for each level they are above 10.
4224 //Characters level 20 and up suffer from ten minutes of sickness.
4225 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
4227 if(int32(getLevel()) >= startLevel)
4229 // set resurrection sickness
4230 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4232 // not full duration
4233 if(int32(getLevel()) < startLevel+9)
4235 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4237 for(int i =0; i < 3; ++i)
4239 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4241 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4242 Aur->SendAuraUpdate(false);
4249 void Player::KillPlayer()
4251 SetMovement(MOVE_ROOT);
4253 StopMirrorTimers(); //disable timers(bars)
4255 setDeathState(CORPSE);
4256 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4258 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4259 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4261 // 6 minutes until repop at graveyard
4262 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4264 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4266 // don't create corpse at this moment, player might be falling
4268 // update visibility
4269 UpdateObjectVisibility();
4272 void Player::CreateCorpse()
4274 // prevent existence 2 corpse for player
4275 SpawnCorpseBones();
4277 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4279 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4280 SetPvPDeath(false);
4282 if(!corpse->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4284 delete corpse;
4285 return;
4288 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4289 _pb = GetUInt32Value(PLAYER_BYTES);
4290 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4292 uint8 race = (uint8)(_uf);
4293 uint8 skin = (uint8)(_pb);
4294 uint8 face = (uint8)(_pb >> 8);
4295 uint8 hairstyle = (uint8)(_pb >> 16);
4296 uint8 haircolor = (uint8)(_pb >> 24);
4297 uint8 facialhair = (uint8)(_pb2);
4299 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4300 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4302 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4303 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4305 uint32 flags = CORPSE_FLAG_UNK2;
4306 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4307 flags |= CORPSE_FLAG_HIDE_HELM;
4308 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4309 flags |= CORPSE_FLAG_HIDE_CLOAK;
4310 if(InBattleGround() && !InArena())
4311 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4312 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4314 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4316 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4318 uint32 iDisplayID;
4319 uint32 iIventoryType;
4320 uint32 _cfi;
4321 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4323 if(m_items[i])
4325 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4326 iIventoryType = m_items[i]->GetProto()->InventoryType;
4328 _cfi = iDisplayID | (iIventoryType << 24);
4329 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi);
4333 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4334 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4335 assert(entry);
4336 if(entry->map_type != MAP_BATTLEGROUND)
4337 corpse->SaveToDB();
4339 // register for player, but not show
4340 sObjectAccessor.AddCorpse(corpse);
4343 void Player::SpawnCorpseBones()
4345 if(sObjectAccessor.ConvertCorpseForPlayer(GetGUID()))
4346 if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
4347 SaveToDB(); // prevent loading as ghost without corpse
4350 Corpse* Player::GetCorpse() const
4352 return sObjectAccessor.GetCorpseForPlayerGUID(GetGUID());
4355 void Player::DurabilityLossAll(double percent, bool inventory)
4357 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4358 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4359 DurabilityLoss(pItem,percent);
4361 if(inventory)
4363 // bags not have durability
4364 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4366 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4367 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4368 DurabilityLoss(pItem,percent);
4370 // keys not have durability
4371 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4373 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4374 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4375 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4376 if(Item* pItem = GetItemByPos( i, j ))
4377 DurabilityLoss(pItem,percent);
4381 void Player::DurabilityLoss(Item* item, double percent)
4383 if(!item )
4384 return;
4386 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4388 if(!pMaxDurability)
4389 return;
4391 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4393 if(pDurabilityLoss < 1 )
4394 pDurabilityLoss = 1;
4396 DurabilityPointsLoss(item,pDurabilityLoss);
4399 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4401 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4402 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4403 DurabilityPointsLoss(pItem,points);
4405 if(inventory)
4407 // bags not have durability
4408 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4410 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4411 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4412 DurabilityPointsLoss(pItem,points);
4414 // keys not have durability
4415 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4417 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4418 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4419 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4420 if(Item* pItem = GetItemByPos( i, j ))
4421 DurabilityPointsLoss(pItem,points);
4425 void Player::DurabilityPointsLoss(Item* item, int32 points)
4427 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4428 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4429 int32 pNewDurability = pOldDurability - points;
4431 if (pNewDurability < 0)
4432 pNewDurability = 0;
4433 else if (pNewDurability > pMaxDurability)
4434 pNewDurability = pMaxDurability;
4436 if (pOldDurability != pNewDurability)
4438 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4439 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4440 _ApplyItemMods(item,item->GetSlot(), false);
4442 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4444 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4445 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4446 _ApplyItemMods(item,item->GetSlot(), true);
4448 item->SetState(ITEM_CHANGED, this);
4452 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4454 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4455 DurabilityPointsLoss(pItem,1);
4458 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4460 uint32 TotalCost = 0;
4461 // equipped, backpack, bags itself
4462 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4463 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4465 // bank, buyback and keys not repaired
4467 // items in inventory bags
4468 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4469 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4470 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4471 return TotalCost;
4474 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4476 Item* item = GetItemByPos(pos);
4478 uint32 TotalCost = 0;
4479 if(!item)
4480 return TotalCost;
4482 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4483 if(!maxDurability)
4484 return TotalCost;
4486 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4488 if(cost)
4490 uint32 LostDurability = maxDurability - curDurability;
4491 if(LostDurability>0)
4493 ItemPrototype const *ditemProto = item->GetProto();
4495 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4496 if(!dcost)
4498 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4499 return TotalCost;
4502 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4503 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4504 if(!dQualitymodEntry)
4506 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4507 return TotalCost;
4510 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4511 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4513 costs = uint32(costs * discountMod);
4515 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4516 costs = 1;
4518 if (guildBank)
4520 if (GetGuildId()==0)
4522 DEBUG_LOG("You are not member of a guild");
4523 return TotalCost;
4526 Guild *pGuild = sObjectMgr.GetGuildById(GetGuildId());
4527 if (!pGuild)
4528 return TotalCost;
4530 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4532 DEBUG_LOG("You do not have rights to withdraw for repairs");
4533 return TotalCost;
4536 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4538 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4539 return TotalCost;
4542 if (pGuild->GetGuildBankMoney() < costs)
4544 DEBUG_LOG("There is not enough money in bank");
4545 return TotalCost;
4548 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4549 TotalCost = costs;
4551 else if (GetMoney() < costs)
4553 DEBUG_LOG("You do not have enough money");
4554 return TotalCost;
4556 else
4557 ModifyMoney( -int32(costs) );
4561 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4562 item->SetState(ITEM_CHANGED, this);
4564 // reapply mods for total broken and repaired item if equipped
4565 if(IsEquipmentPos(pos) && !curDurability)
4566 _ApplyItemMods(item,pos & 255, true);
4567 return TotalCost;
4570 void Player::RepopAtGraveyard()
4572 // note: this can be called also when the player is alive
4573 // for example from WorldSession::HandleMovementOpcodes
4575 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4577 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4578 if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport())
4580 ResurrectPlayer(0.5f);
4581 SpawnCorpseBones();
4584 WorldSafeLocsEntry const *ClosestGrave = NULL;
4586 // Special handle for battleground maps
4587 if( BattleGround *bg = GetBattleGround() )
4588 ClosestGrave = bg->GetClosestGraveYard(this);
4589 else
4590 ClosestGrave = sObjectMgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4592 // stop countdown until repop
4593 m_deathTimer = 0;
4595 // if no grave found, stay at the current location
4596 // and don't show spirit healer location
4597 if(ClosestGrave)
4599 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4600 if(isDead()) // not send if alive, because it used in TeleportTo()
4602 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4603 data << ClosestGrave->map_id;
4604 data << ClosestGrave->x;
4605 data << ClosestGrave->y;
4606 data << ClosestGrave->z;
4607 GetSession()->SendPacket(&data);
4612 void Player::JoinedChannel(Channel *c)
4614 m_channels.push_back(c);
4617 void Player::LeftChannel(Channel *c)
4619 m_channels.remove(c);
4622 void Player::CleanupChannels()
4624 while(!m_channels.empty())
4626 Channel* ch = *m_channels.begin();
4627 m_channels.erase(m_channels.begin()); // remove from player's channel list
4628 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4629 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4630 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4633 sLog.outDebug("Player: channels cleaned up!");
4636 void Player::UpdateLocalChannels(uint32 newZone )
4638 if(m_channels.empty())
4639 return;
4641 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4642 if(!current_zone)
4643 return;
4645 ChannelMgr* cMgr = channelMgr(GetTeam());
4646 if(!cMgr)
4647 return;
4649 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4651 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4653 next = i; ++next;
4655 // skip non built-in channels
4656 if(!(*i)->IsConstant())
4657 continue;
4659 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4660 if(!ch)
4661 continue;
4663 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4664 continue;
4666 // new channel
4667 char new_channel_name_buf[100];
4668 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4669 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4671 if((*i)!=new_channel)
4673 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4675 // leave old channel
4676 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4677 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4678 LeftChannel(*i); // remove from player's channel list
4679 cMgr->LeftChannel(name); // delete if empty
4682 sLog.outDebug("Player: channels cleaned up!");
4685 void Player::LeaveLFGChannel()
4687 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4689 if((*i)->IsLFG())
4691 (*i)->Leave(GetGUID());
4692 break;
4697 void Player::UpdateDefense()
4699 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4701 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4703 // update dependent from defense skill part
4704 UpdateDefenseBonusesMod();
4708 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4710 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4712 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4713 return;
4716 float val = 1.0f;
4718 switch(modType)
4720 case FLAT_MOD:
4721 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4722 break;
4723 case PCT_MOD:
4724 if(amount <= -100.0f)
4725 amount = -200.0f;
4727 val = (100.0f + amount) / 100.0f;
4728 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4729 break;
4732 if(!CanModifyStats())
4733 return;
4735 switch(modGroup)
4737 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4738 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4739 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4740 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4741 default: break;
4745 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4747 if(modGroup >= BASEMOD_END || modType > MOD_END)
4749 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4750 return 0.0f;
4753 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4754 return 0.0f;
4756 return m_auraBaseMod[modGroup][modType];
4759 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4761 if(modGroup >= BASEMOD_END)
4763 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4764 return 0.0f;
4767 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4768 return 0.0f;
4770 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4773 uint32 Player::GetShieldBlockValue() const
4775 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4777 value = (value < 0) ? 0 : value;
4779 return uint32(value);
4782 float Player::GetMeleeCritFromAgility()
4784 uint32 level = getLevel();
4785 uint32 pclass = getClass();
4787 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4789 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4790 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4791 if (critBase==NULL || critRatio==NULL)
4792 return 0.0f;
4794 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4795 return crit*100.0f;
4798 float Player::GetDodgeFromAgility()
4800 // Table for base dodge values
4801 float dodge_base[MAX_CLASSES] = {
4802 0.0075f, // Warrior
4803 0.00652f, // Paladin
4804 -0.0545f, // Hunter
4805 -0.0059f, // Rogue
4806 0.03183f, // Priest
4807 0.0114f, // DK
4808 0.0167f, // Shaman
4809 0.034575f, // Mage
4810 0.02011f, // Warlock
4811 0.0f, // ??
4812 -0.0187f // Druid
4814 // Crit/agility to dodge/agility coefficient multipliers
4815 float crit_to_dodge[MAX_CLASSES] = {
4816 1.1f, // Warrior
4817 1.0f, // Paladin
4818 1.6f, // Hunter
4819 2.0f, // Rogue
4820 1.0f, // Priest
4821 1.0f, // DK?
4822 1.0f, // Shaman
4823 1.0f, // Mage
4824 1.0f, // Warlock
4825 0.0f, // ??
4826 1.7f // Druid
4829 uint32 level = getLevel();
4830 uint32 pclass = getClass();
4832 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4834 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4835 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4836 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4837 return 0.0f;
4839 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4840 return dodge*100.0f;
4843 float Player::GetSpellCritFromIntellect()
4845 uint32 level = getLevel();
4846 uint32 pclass = getClass();
4848 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4850 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4851 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4852 if (critBase==NULL || critRatio==NULL)
4853 return 0.0f;
4855 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4856 return crit*100.0f;
4859 float Player::GetRatingCoefficient(CombatRating cr) const
4861 uint32 level = getLevel();
4863 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4865 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4866 if (Rating == NULL)
4867 return 1.0f; // By default use minimum coefficient (not must be called)
4869 return Rating->ratio;
4872 float Player::GetRatingBonusValue(CombatRating cr) const
4874 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4877 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4879 switch (attType)
4881 case BASE_ATTACK:
4882 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4883 case OFF_ATTACK:
4884 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4885 default:
4886 break;
4888 return 0.0f;
4891 float Player::OCTRegenHPPerSpirit()
4893 uint32 level = getLevel();
4894 uint32 pclass = getClass();
4896 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4898 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4899 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4900 if (baseRatio==NULL || moreRatio==NULL)
4901 return 0.0f;
4903 // Formula from PaperDollFrame script
4904 float spirit = GetStat(STAT_SPIRIT);
4905 float baseSpirit = spirit;
4906 if (baseSpirit>50) baseSpirit = 50;
4907 float moreSpirit = spirit - baseSpirit;
4908 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4909 return regen;
4912 float Player::OCTRegenMPPerSpirit()
4914 uint32 level = getLevel();
4915 uint32 pclass = getClass();
4917 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4919 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4920 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4921 if (moreRatio==NULL)
4922 return 0.0f;
4924 // Formula get from PaperDollFrame script
4925 float spirit = GetStat(STAT_SPIRIT);
4926 float regen = spirit * moreRatio->ratio;
4927 return regen;
4930 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4932 m_baseRatingValue[cr]+=(apply ? value : -value);
4934 int32 amount = uint32(m_baseRatingValue[cr]);
4935 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4936 // stat used stored in miscValueB for this aura
4937 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4938 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4939 if ((*i)->GetMiscValue() & (1<<cr))
4940 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4941 if (amount < 0)
4942 amount = 0;
4943 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4945 float RatingCoeffecient = GetRatingCoefficient(cr);
4946 float RatingChange = 0.0f;
4948 bool affectStats = CanModifyStats();
4950 switch (cr)
4952 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4953 case CR_DEFENSE_SKILL:
4954 UpdateDefenseBonusesMod();
4955 break;
4956 case CR_DODGE:
4957 UpdateDodgePercentage();
4958 break;
4959 case CR_PARRY:
4960 UpdateParryPercentage();
4961 break;
4962 case CR_BLOCK:
4963 UpdateBlockPercentage();
4964 break;
4965 case CR_HIT_MELEE:
4966 UpdateMeleeHitChances();
4967 break;
4968 case CR_HIT_RANGED:
4969 UpdateRangedHitChances();
4970 break;
4971 case CR_HIT_SPELL:
4972 UpdateSpellHitChances();
4973 break;
4974 case CR_CRIT_MELEE:
4975 if(affectStats)
4977 UpdateCritPercentage(BASE_ATTACK);
4978 UpdateCritPercentage(OFF_ATTACK);
4980 break;
4981 case CR_CRIT_RANGED:
4982 if(affectStats)
4983 UpdateCritPercentage(RANGED_ATTACK);
4984 break;
4985 case CR_CRIT_SPELL:
4986 if(affectStats)
4987 UpdateAllSpellCritChances();
4988 break;
4989 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4990 case CR_HIT_TAKEN_RANGED:
4991 break;
4992 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4993 break;
4994 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4995 case CR_CRIT_TAKEN_RANGED:
4996 break;
4997 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4998 break;
4999 case CR_HASTE_MELEE:
5000 RatingChange = value / RatingCoeffecient;
5001 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
5002 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
5003 break;
5004 case CR_HASTE_RANGED:
5005 RatingChange = value / RatingCoeffecient;
5006 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
5007 break;
5008 case CR_HASTE_SPELL:
5009 RatingChange = value / RatingCoeffecient;
5010 ApplyCastTimePercentMod(RatingChange,apply);
5011 break;
5012 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
5013 case CR_WEAPON_SKILL_OFFHAND:
5014 case CR_WEAPON_SKILL_RANGED:
5015 break;
5016 case CR_EXPERTISE:
5017 if(affectStats)
5019 UpdateExpertise(BASE_ATTACK);
5020 UpdateExpertise(OFF_ATTACK);
5022 break;
5023 case CR_ARMOR_PENETRATION:
5024 if(affectStats)
5025 UpdateArmorPenetration();
5026 break;
5030 void Player::SetRegularAttackTime()
5032 for(int i = 0; i < MAX_ATTACK; ++i)
5034 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i),true,false);
5035 if (tmpitem)
5037 ItemPrototype const *proto = tmpitem->GetProto();
5038 if(proto->Delay)
5039 SetAttackTime(WeaponAttackType(i), proto->Delay);
5040 else
5041 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
5046 //skill+step, checking for max value
5047 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
5049 if(!skill_id)
5050 return false;
5052 SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
5053 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5054 return false;
5056 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5057 uint32 data = GetUInt32Value(valueIndex);
5058 uint32 value = SKILL_VALUE(data);
5059 uint32 max = SKILL_MAX(data);
5061 if ((!max) || (!value) || (value >= max))
5062 return false;
5064 if (value*512 < max*urand(0,512))
5066 uint32 new_value = value+step;
5067 if(new_value > max)
5068 new_value = max;
5070 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,max));
5071 if(itr->second.uState != SKILL_NEW)
5072 itr->second.uState = SKILL_CHANGED;
5073 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
5074 return true;
5077 return false;
5080 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
5082 if ( SkillValue >= GrayLevel )
5083 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
5084 if ( SkillValue >= GreenLevel )
5085 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
5086 if ( SkillValue >= YellowLevel )
5087 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
5088 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
5091 bool Player::UpdateCraftSkill(uint32 spellid)
5093 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
5095 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spellid);
5097 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
5099 if (_spell_idx->second->skillId)
5101 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
5103 // Alchemy Discoveries here
5104 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
5105 if (spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
5107 if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
5108 learnSpell(discoveredSpell,false);
5111 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
5113 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
5114 _spell_idx->second->max_value,
5115 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
5116 _spell_idx->second->min_value),
5117 craft_skill_gain);
5120 return false;
5123 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
5125 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
5127 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5129 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5130 switch (SkillId)
5132 case SKILL_HERBALISM:
5133 case SKILL_LOCKPICKING:
5134 case SKILL_JEWELCRAFTING:
5135 case SKILL_INSCRIPTION:
5136 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5137 case SKILL_SKINNING:
5138 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
5139 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5140 else
5141 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
5142 case SKILL_MINING:
5143 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
5144 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5145 else
5146 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
5148 return false;
5151 bool Player::UpdateFishingSkill()
5153 sLog.outDebug("UpdateFishingSkill");
5155 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5157 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5159 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5161 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5164 // levels sync. with spell requirement for skill levels to learn
5165 // bonus abilities in sSkillLineAbilityStore
5166 // Used only to avoid scan DBC at each skill grow
5167 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5169 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5171 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5172 if ( !SkillId )
5173 return false;
5175 if(Chance <= 0) // speedup in 0 chance case
5177 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5178 return false;
5181 SkillStatusMap::iterator itr = mSkillStatus.find(SkillId);
5182 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5183 return false;
5185 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5187 uint32 data = GetUInt32Value(valueIndex);
5188 uint16 SkillValue = SKILL_VALUE(data);
5189 uint16 MaxValue = SKILL_MAX(data);
5191 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5192 return false;
5194 int32 Roll = irand(1,1000);
5196 if ( Roll <= Chance )
5198 uint32 new_value = SkillValue+step;
5199 if(new_value > MaxValue)
5200 new_value = MaxValue;
5202 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,MaxValue));
5203 if(itr->second.uState != SKILL_NEW)
5204 itr->second.uState = SKILL_CHANGED;
5205 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5207 if((SkillValue < *bsl && new_value >= *bsl))
5209 learnSkillRewardedSpells( SkillId, new_value);
5210 break;
5213 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5214 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5215 return true;
5218 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5219 return false;
5222 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5224 // no skill gain in pvp
5225 Unit *pVictim = getVictim();
5226 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5227 return;
5229 if(IsInFeralForm())
5230 return; // always maximized SKILL_FERAL_COMBAT in fact
5232 if(m_form == FORM_TREE)
5233 return; // use weapon but not skill up
5235 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5237 switch(attType)
5239 case BASE_ATTACK:
5241 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5243 if (!tmpitem)
5244 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5245 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5246 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5247 break;
5249 case OFF_ATTACK:
5250 case RANGED_ATTACK:
5252 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5253 if (tmpitem)
5254 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5255 break;
5258 UpdateAllCritPercentages();
5261 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5263 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5264 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5265 uint32 moblevel = pVictim->getLevelForTarget(this);
5266 if(moblevel < greylevel)
5267 return;
5269 if (moblevel > plevel + 5)
5270 moblevel = plevel + 5;
5272 uint32 lvldif = moblevel - greylevel;
5273 if(lvldif < 3)
5274 lvldif = 3;
5276 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5277 if(skilldif <= 0)
5278 return;
5280 float chance = float(3 * lvldif * skilldif) / plevel;
5281 if(!defence)
5283 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5284 chance *= 0.1f * GetStat(STAT_INTELLECT);
5287 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5289 if(roll_chance_f(chance))
5291 if(defence)
5292 UpdateDefense();
5293 else
5294 UpdateWeaponSkill(attType);
5296 else
5297 return;
5300 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5302 SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid);
5303 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5304 return;
5306 uint32 bonusIndex = PLAYER_SKILL_BONUS_INDEX(itr->second.pos);
5308 uint32 bonus_val = GetUInt32Value(bonusIndex);
5309 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5310 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5312 if(talent) // permanent bonus stored in high part
5313 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5314 else // temporary/item bonus stored in low part
5315 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5318 void Player::UpdateSkillsForLevel()
5320 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5321 uint32 maxSkill = GetMaxSkillValueForLevel();
5323 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5325 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5327 if(itr->second.uState == SKILL_DELETED)
5328 continue;
5330 uint32 pskill = itr->first;
5332 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5333 if(!pSkill)
5334 continue;
5336 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5337 continue;
5339 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5340 uint32 data = GetUInt32Value(valueIndex);
5341 uint32 max = SKILL_MAX(data);
5342 uint32 val = SKILL_VALUE(data);
5344 /// update only level dependent max skill values
5345 if(max!=1)
5347 /// maximize skill always
5348 if(alwaysMaxSkill)
5350 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(maxSkill,maxSkill));
5351 if(itr->second.uState != SKILL_NEW)
5352 itr->second.uState = SKILL_CHANGED;
5354 else if(max != maxconfskill) /// update max skill value if current max skill not maximized
5356 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(val,maxSkill));
5357 if(itr->second.uState != SKILL_NEW)
5358 itr->second.uState = SKILL_CHANGED;
5364 void Player::UpdateSkillsToMaxSkillsForLevel()
5366 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5368 if(itr->second.uState == SKILL_DELETED)
5369 continue;
5371 uint32 pskill = itr->first;
5372 if( IsProfessionOrRidingSkill(pskill))
5373 continue;
5374 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5375 uint32 data = GetUInt32Value(valueIndex);
5377 uint32 max = SKILL_MAX(data);
5379 if(max > 1)
5381 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(max,max));
5382 if(itr->second.uState != SKILL_NEW)
5383 itr->second.uState = SKILL_CHANGED;
5386 if(pskill == SKILL_DEFENSE)
5387 UpdateDefenseBonusesMod();
5391 // This functions sets a skill line value (and adds if doesn't exist yet)
5392 // To "remove" a skill line, set it's values to zero
5393 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5395 if(!id)
5396 return;
5398 SkillStatusMap::iterator itr = mSkillStatus.find(id);
5400 //has skill
5401 if(itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED)
5403 if(currVal)
5405 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),MAKE_SKILL_VALUE(currVal,maxVal));
5406 if(itr->second.uState != SKILL_NEW)
5407 itr->second.uState = SKILL_CHANGED;
5408 learnSkillRewardedSpells(id, currVal);
5409 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5410 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5412 else //remove
5414 // clear skill fields
5415 SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos),0);
5416 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),0);
5417 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos),0);
5419 // mark as deleted or simply remove from map if not saved yet
5420 if(itr->second.uState != SKILL_NEW)
5421 itr->second.uState = SKILL_DELETED;
5422 else
5423 mSkillStatus.erase(itr);
5425 // remove all spells that related to this skill
5426 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5427 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5428 if (pAbility->skillId==id)
5429 removeSpell(sSpellMgr.GetFirstSpellInChain(pAbility->spellId));
5432 else if(currVal) //add
5434 for (int i=0; i < PLAYER_MAX_SKILLS; ++i)
5435 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5437 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5438 if(!pSkill)
5440 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5441 return;
5443 // enable unlearn button for primary professions only
5444 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5445 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5446 else
5447 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5448 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5449 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5450 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5452 // insert new entry or update if not deleted old entry yet
5453 if(itr != mSkillStatus.end())
5455 itr->second.pos = i;
5456 itr->second.uState = SKILL_CHANGED;
5458 else
5459 mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW)));
5461 // apply skill bonuses
5462 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5464 // temporary bonuses
5465 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5466 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5467 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5468 (*j)->ApplyModifier(true);
5470 // permanent bonuses
5471 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5472 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5473 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5474 (*j)->ApplyModifier(true);
5476 // Learn all spells for skill
5477 learnSkillRewardedSpells(id, currVal);
5478 return;
5483 bool Player::HasSkill(uint32 skill) const
5485 if(!skill)
5486 return false;
5488 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5489 return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED);
5492 uint16 Player::GetSkillValue(uint32 skill) const
5494 if(!skill)
5495 return 0;
5497 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5498 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5499 return 0;
5501 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5503 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5504 result += SKILL_TEMP_BONUS(bonus);
5505 result += SKILL_PERM_BONUS(bonus);
5506 return result < 0 ? 0 : result;
5509 uint16 Player::GetMaxSkillValue(uint32 skill) const
5511 if(!skill)
5512 return 0;
5514 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5515 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5516 return 0;
5518 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5520 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5521 result += SKILL_TEMP_BONUS(bonus);
5522 result += SKILL_PERM_BONUS(bonus);
5523 return result < 0 ? 0 : result;
5526 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5528 if(!skill)
5529 return 0;
5531 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5532 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5533 return 0;
5535 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5538 uint16 Player::GetBaseSkillValue(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 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5548 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5549 return result < 0 ? 0 : result;
5552 uint16 Player::GetPureSkillValue(uint32 skill) const
5554 if(!skill)
5555 return 0;
5557 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5558 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5559 return 0;
5561 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5564 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5566 if(!skill)
5567 return 0;
5569 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5570 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5571 return 0;
5573 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5576 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5578 if(!skill)
5579 return 0;
5581 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5582 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5583 return 0;
5585 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5588 void Player::SendInitialActionButtons() const
5590 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5592 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5593 data << uint8(0); // can be 0, 1, 2 (talent spec)
5594 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5596 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5597 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5598 data << uint32(itr->second.packedData);
5599 else
5600 data << uint32(0);
5603 GetSession()->SendPacket( &data );
5604 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5607 bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Player* player)
5609 if(button >= MAX_ACTION_BUTTONS)
5611 if (player)
5612 sLog.outError( "Action %u not added into button %u for player %s: button must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTONS );
5613 else
5614 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action, button, MAX_ACTION_BUTTONS );
5615 return false;
5618 if(action >= MAX_ACTION_BUTTON_ACTION_VALUE)
5620 if (player)
5621 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 );
5622 else
5623 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action, button, MAX_ACTION_BUTTON_ACTION_VALUE );
5624 return false;
5627 switch(type)
5629 case ACTION_BUTTON_SPELL:
5630 if(!sSpellStore.LookupEntry(action))
5632 if (player)
5633 sLog.outError( "Spell action %u not added into button %u for player %s: spell not exist", action, button, player->GetName() );
5634 else
5635 sLog.outError( "Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action, button );
5636 return false;
5639 if(player && !player->HasSpell(action))
5641 sLog.outError( "Spell action %u not added into button %u for player %s: player don't known this spell", action, button, player->GetName() );
5642 return false;
5644 break;
5645 case ACTION_BUTTON_ITEM:
5646 if(!ObjectMgr::GetItemPrototype(action))
5648 if (player)
5649 sLog.outError( "Item action %u not added into button %u for player %s: item not exist", action, button, player->GetName() );
5650 else
5651 sLog.outError( "Table `playercreateinfo_action` have item action %u into button %u: item not exist", action, button );
5652 return false;
5654 break;
5655 default:
5656 break; // other cases not checked at this moment
5659 return true;
5662 ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type)
5665 if (!IsActionButtonDataValid(button,action,type,this))
5666 return NULL;
5668 // it create new button (NEW state) if need or return existed
5669 ActionButton& ab = m_actionButtons[button];
5671 // set data and update to CHANGED if not NEW
5672 ab.SetActionAndType(action,ActionButtonType(type));
5674 sLog.outDetail( "Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUIDLow(), action, uint32(type), button );
5675 return &ab;
5678 void Player::removeActionButton(uint8 button)
5680 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5681 if (buttonItr==m_actionButtons.end())
5682 return;
5684 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5685 m_actionButtons.erase(buttonItr); // new and not saved
5686 else
5687 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5689 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5692 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5694 // prevent crash when a bad coord is sent by the client
5695 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5697 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5698 return false;
5701 Map *m = GetMap();
5703 const float old_x = GetPositionX();
5704 const float old_y = GetPositionY();
5705 const float old_z = GetPositionZ();
5706 const float old_r = GetOrientation();
5708 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5710 if (teleport || old_x != x || old_y != y || old_z != z)
5711 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5712 else
5713 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5715 // move and update visible state if need
5716 m->PlayerRelocation(this, x, y, z, orientation);
5718 // reread after Map::Relocation
5719 m = GetMap();
5720 x = GetPositionX();
5721 y = GetPositionY();
5722 z = GetPositionZ();
5724 // group update
5725 if(GetGroup() && (old_x != x || old_y != y))
5726 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5729 // code block for underwater state update
5730 UpdateUnderwaterState(m, x, y, z);
5732 CheckExploreSystem();
5734 return true;
5737 void Player::SaveRecallPosition()
5739 m_recallMap = GetMapId();
5740 m_recallX = GetPositionX();
5741 m_recallY = GetPositionY();
5742 m_recallZ = GetPositionZ();
5743 m_recallO = GetOrientation();
5746 void Player::SendMessageToSet(WorldPacket *data, bool self)
5748 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5749 if(_map)
5751 _map->MessageBroadcast(this, data, self);
5752 return;
5755 //if player is not in world and map in not created/already destroyed
5756 //no need to create one, just send packet for itself!
5757 if(self)
5758 GetSession()->SendPacket(data);
5761 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5763 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5764 if(_map)
5766 _map->MessageDistBroadcast(this, data, dist, self);
5767 return;
5770 if(self)
5771 GetSession()->SendPacket(data);
5774 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5776 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5777 if(_map)
5779 _map->MessageDistBroadcast(this, data, dist, self, own_team_only);
5780 return;
5783 if(self)
5784 GetSession()->SendPacket(data);
5787 void Player::SendDirectMessage(WorldPacket *data)
5789 GetSession()->SendPacket(data);
5792 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5794 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5795 data << uint32(CinematicSequenceId);
5796 SendDirectMessage(&data);
5799 void Player::SendMovieStart(uint32 MovieId)
5801 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5802 data << uint32(MovieId);
5803 SendDirectMessage(&data);
5806 void Player::CheckExploreSystem()
5808 if (!isAlive())
5809 return;
5811 if (isInFlight())
5812 return;
5814 uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5815 if(areaFlag==0xffff)
5816 return;
5817 int offset = areaFlag / 32;
5819 if(offset >= 128)
5821 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);
5822 return;
5825 uint32 val = (uint32)(1 << (areaFlag % 32));
5826 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5828 if( !(currFields & val) )
5830 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5832 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5834 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5835 if(!p)
5837 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5839 else if(p->area_level > 0)
5841 uint32 area = p->ID;
5842 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5844 SendExplorationExperience(area,0);
5846 else
5848 int32 diff = int32(getLevel()) - p->area_level;
5849 uint32 XP = 0;
5850 if (diff < -5)
5852 XP = uint32(sObjectMgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5854 else if (diff > 5)
5856 int32 exploration_percent = (100-((diff-5)*5));
5857 if (exploration_percent > 100)
5858 exploration_percent = 100;
5859 else if (exploration_percent < 0)
5860 exploration_percent = 0;
5862 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5864 else
5866 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5869 GiveXP( XP, NULL );
5870 SendExplorationExperience(area,XP);
5872 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5877 uint32 Player::TeamForRace(uint8 race)
5879 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5880 if(!rEntry)
5882 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5883 return ALLIANCE;
5886 switch(rEntry->TeamID)
5888 case 7: return ALLIANCE;
5889 case 1: return HORDE;
5892 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5893 return ALLIANCE;
5896 uint32 Player::getFactionForRace(uint8 race)
5898 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5899 if(!rEntry)
5901 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5902 return 0;
5905 return rEntry->FactionID;
5908 void Player::setFactionForRace(uint8 race)
5910 m_team = TeamForRace(race);
5911 setFaction( getFactionForRace(race) );
5914 ReputationRank Player::GetReputationRank(uint32 faction) const
5916 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5917 return GetReputationMgr().GetRank(factionEntry);
5920 //Calculate total reputation percent player gain with quest/creature level
5921 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5923 float percent = 100.0f;
5925 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5927 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5928 percent *= rate;
5930 float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5932 if (!for_quest)
5933 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
5935 percent += rep > 0 ? repMod : -repMod;
5937 if (percent <= 0.0f)
5938 return 0;
5940 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100.0f);
5943 //Calculates how many reputation points player gains in victim's enemy factions
5944 void Player::RewardReputation(Unit *pVictim, float rate)
5946 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5947 return;
5949 ReputationOnKillEntry const* Rep = sObjectMgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5951 if(!Rep)
5952 return;
5954 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5956 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
5957 donerep1 = int32(donerep1*rate);
5958 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5959 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5960 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5961 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5963 // Wiki: Team factions value divided by 2
5964 if (factionEntry1 && Rep->is_teamaward1)
5966 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5967 if(team1_factionEntry)
5968 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5972 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5974 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
5975 donerep2 = int32(donerep2*rate);
5976 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5977 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5978 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5979 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5981 // Wiki: Team factions value divided by 2
5982 if (factionEntry2 && Rep->is_teamaward2)
5984 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5985 if(team2_factionEntry)
5986 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5991 //Calculate how many reputation points player gain with the quest
5992 void Player::RewardReputation(Quest const *pQuest)
5994 // quest reputation reward/loss
5995 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5997 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5999 int32 rep = CalculateReputationGain(GetQuestLevelForPlayer(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
6000 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
6001 if(factionEntry)
6002 GetReputationMgr().ModifyReputation(factionEntry, rep);
6006 // TODO: implement reputation spillover
6009 void Player::UpdateArenaFields(void)
6011 /* arena calcs go here */
6014 void Player::UpdateHonorFields()
6016 /// called when rewarding honor and at each save
6017 uint64 now = time(NULL);
6018 uint64 today = uint64(time(NULL) / DAY) * DAY;
6020 if(m_lastHonorUpdateTime < today)
6022 uint64 yesterday = today - DAY;
6024 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
6026 // update yesterday's contribution
6027 if(m_lastHonorUpdateTime >= yesterday )
6029 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
6031 // this is the first update today, reset today's contribution
6032 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
6033 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
6035 else
6037 // no honor/kills yesterday or today, reset
6038 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
6039 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
6043 m_lastHonorUpdateTime = now;
6046 ///Calculate the amount of honor gained based on the victim
6047 ///and the size of the group for which the honor is divided
6048 ///An exact honor value can also be given (overriding the calcs)
6049 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
6051 // do not reward honor in arenas, but enable onkill spellproc
6052 if(InArena())
6054 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
6055 return false;
6057 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
6058 return false;
6060 return true;
6063 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6064 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
6065 return false;
6067 uint64 victim_guid = 0;
6068 uint32 victim_rank = 0;
6070 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6071 UpdateHonorFields();
6073 if(honor <= 0)
6075 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
6076 return false;
6078 victim_guid = uVictim->GetGUID();
6080 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6082 Player *pVictim = (Player *)uVictim;
6084 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6085 return false;
6087 float f = 1; //need for total kills (?? need more info)
6088 uint32 k_grey = 0;
6089 uint32 k_level = getLevel();
6090 uint32 v_level = pVictim->getLevel();
6093 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6094 // [0] Just name
6095 // [1..14] Alliance honor titles and player name
6096 // [15..28] Horde honor titles and player name
6097 // [29..38] Other title and player name
6098 // [39+] Nothing
6099 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6100 // Get Killer titles, CharTitlesEntry::bit_index
6101 // Ranks:
6102 // title[1..14] -> rank[5..18]
6103 // title[15..28] -> rank[5..18]
6104 // title[other] -> 0
6105 if (victim_title == 0)
6106 victim_guid = 0; // Don't show HK: <rank> message, only log.
6107 else if (victim_title < 15)
6108 victim_rank = victim_title + 4;
6109 else if (victim_title < 29)
6110 victim_rank = victim_title - 14 + 4;
6111 else
6112 victim_guid = 0; // Don't show HK: <rank> message, only log.
6115 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6117 if(v_level<=k_grey)
6118 return false;
6120 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6122 int32 v_rank =1; //need more info
6124 honor = ((f * diff_level * (190 + v_rank*10))/6);
6125 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6127 // count the number of playerkills in one day
6128 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6129 // and those in a lifetime
6130 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6131 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
6132 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
6133 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
6135 else
6137 Creature *cVictim = (Creature *)uVictim;
6139 if (!cVictim->isRacialLeader())
6140 return false;
6142 honor = 100; // ??? need more info
6143 victim_rank = 19; // HK: Leader
6147 if (uVictim != NULL)
6149 honor *= sWorld.getRate(RATE_HONOR);
6150 honor *= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN) + 100.0f)/100.0f;
6152 if(groupsize > 1)
6153 honor /= groupsize;
6155 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6158 // honor - for show honor points in log
6159 // victim_guid - for show victim name in log
6160 // victim_rank [1..4] HK: <dishonored rank>
6161 // victim_rank [5..19] HK: <alliance\horde rank>
6162 // victim_rank [0,20+] HK: <>
6163 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6164 data << (uint32) honor;
6165 data << (uint64) victim_guid;
6166 data << (uint32) victim_rank;
6168 GetSession()->SendPacket(&data);
6170 // add honor points
6171 ModifyHonorPoints(int32(honor));
6173 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6174 return true;
6177 void Player::ModifyHonorPoints( int32 value )
6179 if(value < 0)
6181 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6182 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6183 else
6184 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6186 else
6187 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6190 void Player::ModifyArenaPoints( int32 value )
6192 if(value < 0)
6194 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6195 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6196 else
6197 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6199 else
6200 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6203 uint32 Player::GetGuildIdFromDB(uint64 guid)
6205 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6206 if(!result)
6207 return 0;
6209 uint32 id = result->Fetch()[0].GetUInt32();
6210 delete result;
6211 return id;
6214 uint32 Player::GetRankFromDB(uint64 guid)
6216 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6217 if( result )
6219 uint32 v = result->Fetch()[0].GetUInt32();
6220 delete result;
6221 return v;
6223 else
6224 return 0;
6227 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6229 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);
6230 if(!result)
6231 return 0;
6233 uint32 id = (*result)[0].GetUInt32();
6234 delete result;
6235 return id;
6238 uint32 Player::GetZoneIdFromDB(uint64 guid)
6240 uint32 guidLow = GUID_LOPART(guid);
6241 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6242 if (!result)
6243 return 0;
6244 Field* fields = result->Fetch();
6245 uint32 zone = fields[0].GetUInt32();
6246 delete result;
6248 if (!zone)
6250 // stored zone is zero, use generic and slow zone detection
6251 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6252 if( !result )
6253 return 0;
6254 fields = result->Fetch();
6255 uint32 map = fields[0].GetUInt32();
6256 float posx = fields[1].GetFloat();
6257 float posy = fields[2].GetFloat();
6258 float posz = fields[3].GetFloat();
6259 delete result;
6261 zone = sMapMgr.GetZoneId(map,posx,posy,posz);
6263 if (zone > 0)
6264 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6267 return zone;
6270 uint32 Player::GetLevelFromDB(uint64 guid)
6272 QueryResult *result = CharacterDatabase.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid) );
6273 if (!result)
6274 return 0;
6276 Field* fields = result->Fetch();
6277 uint32 level = fields[0].GetUInt32();
6278 delete result;
6280 return level;
6283 void Player::UpdateArea(uint32 newArea)
6285 // FFA_PVP flags are area and not zone id dependent
6286 // so apply them accordingly
6287 m_areaUpdateId = newArea;
6289 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6291 if(area && (area->flags & AREA_FLAG_ARENA))
6293 if(!isGameMaster())
6294 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6296 else
6298 // remove ffa flag only if not ffapvp realm
6299 // removal in sanctuaries and capitals is handled in zone update
6300 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6301 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6304 UpdateAreaDependentAuras(newArea);
6307 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6309 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6310 if(!zone)
6311 return;
6313 if(m_zoneUpdateId != newZone)
6315 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6317 if (sWorld.getConfig(CONFIG_WEATHER))
6319 if(Weather *wth = sWorld.FindWeather(zone->ID))
6320 wth->SendWeatherUpdateToPlayer(this);
6321 else if(!sWorld.AddWeather(zone->ID))
6323 // send fine weather packet to remove old zone's weather
6324 Weather::SendFineWeatherUpdateToPlayer(this);
6329 m_zoneUpdateId = newZone;
6330 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6332 // zone changed, so area changed as well, update it
6333 UpdateArea(newArea);
6335 // in PvP, any not controlled zone (except zone->team == 6, default case)
6336 // in PvE, only opposition team capital
6337 switch(zone->team)
6339 case AREATEAM_ALLY:
6340 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6341 break;
6342 case AREATEAM_HORDE:
6343 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6344 break;
6345 case AREATEAM_NONE:
6346 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6347 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6348 break;
6349 default: // 6 in fact
6350 pvpInfo.inHostileArea = false;
6351 break;
6354 if(pvpInfo.inHostileArea) // in hostile area
6356 if(!IsPvP() || pvpInfo.endTimer != 0)
6357 UpdatePvP(true, true);
6359 else // in friendly area
6361 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6362 pvpInfo.endTimer = time(0); // start toggle-off
6365 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6367 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6368 if(sWorld.IsFFAPvPRealm())
6369 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6371 else
6373 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6376 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6378 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6379 SetRestType(REST_TYPE_IN_CITY);
6380 InnEnter(time(0),GetMapId(),0,0,0);
6382 if(sWorld.IsFFAPvPRealm())
6383 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6385 else // anywhere else
6387 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6389 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6391 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6393 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6394 SetRestType(REST_TYPE_NO);
6396 if(sWorld.IsFFAPvPRealm())
6397 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6400 else // not in tavern (leave city then)
6402 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6403 SetRestType(REST_TYPE_NO);
6405 // Set player to FFA PVP when not in rested environment.
6406 if(sWorld.IsFFAPvPRealm())
6407 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6412 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6413 // if player resurrected at teleport this will be applied in resurrect code
6414 if(isAlive())
6415 DestroyZoneLimitedItem( true, newZone );
6417 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6418 AutoUnequipOffhandIfNeed();
6420 // recent client version not send leave/join channel packets for built-in local channels
6421 UpdateLocalChannels( newZone );
6423 // group update
6424 if(GetGroup())
6425 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6427 UpdateZoneDependentAuras(newZone);
6430 //If players are too far way of duel flag... then player loose the duel
6431 void Player::CheckDuelDistance(time_t currTime)
6433 if(!duel)
6434 return;
6436 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6437 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6438 if(!obj)
6439 return;
6441 if(duel->outOfBound == 0)
6443 if(!IsWithinDistInMap(obj, 50))
6445 duel->outOfBound = currTime;
6447 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6448 GetSession()->SendPacket(&data);
6451 else
6453 if(IsWithinDistInMap(obj, 40))
6455 duel->outOfBound = 0;
6457 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6458 GetSession()->SendPacket(&data);
6460 else if(currTime >= (duel->outOfBound+10))
6462 DuelComplete(DUEL_FLED);
6467 void Player::DuelComplete(DuelCompleteType type)
6469 // duel not requested
6470 if(!duel)
6471 return;
6473 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6474 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6475 GetSession()->SendPacket(&data);
6476 duel->opponent->GetSession()->SendPacket(&data);
6478 if(type != DUEL_INTERUPTED)
6480 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6481 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6482 data << duel->opponent->GetName();
6483 data << GetName();
6484 SendMessageToSet(&data,true);
6487 if (type == DUEL_WON)
6489 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6490 if (duel->opponent)
6491 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6494 //Remove Duel Flag object
6495 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6496 if(obj)
6497 duel->initiator->RemoveGameObject(obj,true);
6499 /* remove auras */
6500 std::vector<uint32> auras2remove;
6501 AuraMap const& vAuras = duel->opponent->GetAuras();
6502 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6504 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6505 auras2remove.push_back(i->second->GetId());
6508 for(size_t i=0; i<auras2remove.size(); ++i)
6509 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6511 auras2remove.clear();
6512 AuraMap const& auras = GetAuras();
6513 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6515 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6516 auras2remove.push_back(i->second->GetId());
6518 for(size_t i=0; i<auras2remove.size(); ++i)
6519 RemoveAurasDueToSpell(auras2remove[i]);
6521 // cleanup combo points
6522 if(GetComboTarget()==duel->opponent->GetGUID())
6523 ClearComboPoints();
6524 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6525 ClearComboPoints();
6527 if(duel->opponent->GetComboTarget()==GetGUID())
6528 duel->opponent->ClearComboPoints();
6529 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6530 duel->opponent->ClearComboPoints();
6532 //cleanups
6533 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6534 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6535 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6536 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6538 delete duel->opponent->duel;
6539 duel->opponent->duel = NULL;
6540 delete duel;
6541 duel = NULL;
6544 //---------------------------------------------------------//
6546 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6548 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6549 return;
6551 // not apply/remove mods for broken item
6552 if(item->IsBroken())
6553 return;
6555 ItemPrototype const *proto = item->GetProto();
6557 if(!proto)
6558 return;
6560 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6562 uint32 attacktype = Player::GetAttackBySlot(slot);
6563 if(attacktype < MAX_ATTACK)
6564 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6566 _ApplyItemBonuses(proto,slot,apply);
6568 if( slot==EQUIPMENT_SLOT_RANGED )
6569 _ApplyAmmoBonuses();
6571 ApplyItemEquipSpell(item,apply);
6572 ApplyEnchantment(item, apply);
6574 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6575 CorrectMetaGemEnchants(slot, apply);
6577 sLog.outDebug("_ApplyItemMods complete.");
6580 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
6582 if (slot >= INVENTORY_SLOT_BAG_END || !proto)
6583 return;
6585 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
6586 if (only_level_scale && !ssd)
6587 return;
6589 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6590 uint32 ssd_level = getLevel();
6591 if (ssd && ssd_level > ssd->MaxLevel)
6592 ssd_level = ssd->MaxLevel;
6594 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
6595 if (only_level_scale && !ssv)
6596 return;
6598 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6600 uint32 statType = 0;
6601 int32 val = 0;
6602 // If set ScalingStatDistribution need get stats and values from it
6603 if (ssd && ssv)
6605 if (ssd->StatMod[i] < 0)
6606 continue;
6607 statType = ssd->StatMod[i];
6608 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6610 else
6612 if (i >= proto->StatsCount)
6613 continue;
6614 statType = proto->ItemStat[i].ItemStatType;
6615 val = proto->ItemStat[i].ItemStatValue;
6618 if(val == 0)
6619 continue;
6621 switch (statType)
6623 case ITEM_MOD_MANA:
6624 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6625 break;
6626 case ITEM_MOD_HEALTH: // modify HP
6627 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6628 break;
6629 case ITEM_MOD_AGILITY: // modify agility
6630 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6631 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6632 break;
6633 case ITEM_MOD_STRENGTH: //modify strength
6634 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6635 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6636 break;
6637 case ITEM_MOD_INTELLECT: //modify intellect
6638 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6639 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6640 break;
6641 case ITEM_MOD_SPIRIT: //modify spirit
6642 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6643 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6644 break;
6645 case ITEM_MOD_STAMINA: //modify stamina
6646 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6647 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6648 break;
6649 case ITEM_MOD_DEFENSE_SKILL_RATING:
6650 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6651 break;
6652 case ITEM_MOD_DODGE_RATING:
6653 ApplyRatingMod(CR_DODGE, int32(val), apply);
6654 break;
6655 case ITEM_MOD_PARRY_RATING:
6656 ApplyRatingMod(CR_PARRY, int32(val), apply);
6657 break;
6658 case ITEM_MOD_BLOCK_RATING:
6659 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6660 break;
6661 case ITEM_MOD_HIT_MELEE_RATING:
6662 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6663 break;
6664 case ITEM_MOD_HIT_RANGED_RATING:
6665 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6666 break;
6667 case ITEM_MOD_HIT_SPELL_RATING:
6668 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6669 break;
6670 case ITEM_MOD_CRIT_MELEE_RATING:
6671 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6672 break;
6673 case ITEM_MOD_CRIT_RANGED_RATING:
6674 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6675 break;
6676 case ITEM_MOD_CRIT_SPELL_RATING:
6677 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6678 break;
6679 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6680 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6681 break;
6682 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6683 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6684 break;
6685 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6686 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6687 break;
6688 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6689 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6690 break;
6691 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6692 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6693 break;
6694 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6695 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6696 break;
6697 case ITEM_MOD_HASTE_MELEE_RATING:
6698 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6699 break;
6700 case ITEM_MOD_HASTE_RANGED_RATING:
6701 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6702 break;
6703 case ITEM_MOD_HASTE_SPELL_RATING:
6704 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6705 break;
6706 case ITEM_MOD_HIT_RATING:
6707 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6708 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6709 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6710 break;
6711 case ITEM_MOD_CRIT_RATING:
6712 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6713 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6714 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6715 break;
6716 case ITEM_MOD_HIT_TAKEN_RATING:
6717 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6718 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6719 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6720 break;
6721 case ITEM_MOD_CRIT_TAKEN_RATING:
6722 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6723 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6724 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6725 break;
6726 case ITEM_MOD_RESILIENCE_RATING:
6727 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6728 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6729 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6730 break;
6731 case ITEM_MOD_HASTE_RATING:
6732 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6733 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6734 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6735 break;
6736 case ITEM_MOD_EXPERTISE_RATING:
6737 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6738 break;
6739 case ITEM_MOD_ATTACK_POWER:
6740 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6741 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6742 break;
6743 case ITEM_MOD_RANGED_ATTACK_POWER:
6744 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6745 break;
6746 case ITEM_MOD_FERAL_ATTACK_POWER:
6747 ApplyFeralAPBonus(int32(val), apply);
6748 break;
6749 case ITEM_MOD_MANA_REGENERATION:
6750 ApplyManaRegenBonus(int32(val), apply);
6751 break;
6752 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6753 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6754 break;
6755 case ITEM_MOD_SPELL_POWER:
6756 ApplySpellPowerBonus(int32(val), apply);
6757 break;
6758 // depricated item mods
6759 case ITEM_MOD_SPELL_HEALING_DONE:
6760 case ITEM_MOD_SPELL_DAMAGE_DONE:
6761 break;
6765 // Apply Spell Power from ScalingStatValue if set
6766 if(ssv)
6768 if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
6769 ApplySpellPowerBonus(spellbonus, apply);
6772 // If set ScalingStatValue armor get it or use item armor
6773 uint32 armor = proto->Armor;
6774 if (ssv)
6776 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6777 armor = ssvarmor;
6779 // Add armor bonus from ArmorDamageModifier if > 0
6780 if (proto->ArmorDamageModifier > 0)
6781 armor += uint32(proto->ArmorDamageModifier);
6783 if (armor)
6784 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6786 if (proto->Block)
6787 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6789 if (proto->HolyRes)
6790 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6792 if (proto->FireRes)
6793 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6795 if (proto->NatureRes)
6796 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6798 if (proto->FrostRes)
6799 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6801 if (proto->ShadowRes)
6802 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6804 if (proto->ArcaneRes)
6805 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6807 WeaponAttackType attType = BASE_ATTACK;
6808 float damage = 0.0f;
6810 if( slot == EQUIPMENT_SLOT_RANGED && (
6811 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6812 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6814 attType = RANGED_ATTACK;
6816 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6818 attType = OFF_ATTACK;
6821 float minDamage = proto->Damage[0].DamageMin;
6822 float maxDamage = proto->Damage[0].DamageMax;
6823 int32 extraDPS = 0;
6824 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6825 if (ssv)
6827 if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue)))
6829 float average = extraDPS * proto->Delay / 1000.0f;
6830 minDamage = 0.7f * average;
6831 maxDamage = 1.3f * average;
6834 if (minDamage > 0 )
6836 damage = apply ? minDamage : BASE_MINDAMAGE;
6837 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6838 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6841 if (maxDamage > 0 )
6843 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6844 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6847 // Apply feral bonus from ScalingStatValue if set
6848 if (ssv)
6850 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6851 ApplyFeralAPBonus(feral_bonus, apply);
6853 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6854 if(getClass() == CLASS_DRUID)
6856 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6857 if (feral_bonus > 0)
6858 ApplyFeralAPBonus(feral_bonus, apply);
6861 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6862 return;
6864 if (proto->Delay)
6866 if(slot == EQUIPMENT_SLOT_RANGED)
6867 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6868 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6869 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6870 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6871 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6874 if(CanModifyStats() && (damage || proto->Delay))
6875 UpdateDamagePhysical(attType);
6878 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6880 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6881 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6882 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6884 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6885 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6886 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6888 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6889 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6890 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6893 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6895 // generic not weapon specific case processes in aura code
6896 if(aura->GetSpellProto()->EquippedItemClass == -1)
6897 return;
6899 BaseModGroup mod = BASEMOD_END;
6900 switch(attackType)
6902 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6903 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6904 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6905 default: return;
6908 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6910 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6914 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6916 // ignore spell mods for not wands
6917 Modifier const* modifier = aura->GetModifier();
6918 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6919 return;
6921 // generic not weapon specific case processes in aura code
6922 if(aura->GetSpellProto()->EquippedItemClass == -1)
6923 return;
6925 UnitMods unitMod = UNIT_MOD_END;
6926 switch(attackType)
6928 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6929 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6930 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6931 default: return;
6934 UnitModifierType unitModType = TOTAL_VALUE;
6935 switch(modifier->m_auraname)
6937 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6938 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6939 default: return;
6942 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6944 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6948 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6950 if(!item)
6951 return;
6953 ItemPrototype const *proto = item->GetProto();
6954 if(!proto)
6955 return;
6957 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6959 _Spell const& spellData = proto->Spells[i];
6961 // no spell
6962 if(!spellData.SpellId )
6963 continue;
6965 // wrong triggering type
6966 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6967 continue;
6969 // check if it is valid spell
6970 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6971 if(!spellproto)
6972 continue;
6974 ApplyEquipSpell(spellproto,item,apply,form_change);
6978 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6980 if(apply)
6982 // Cannot be used in this stance/form
6983 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6984 return;
6986 if(form_change) // check aura active state from other form
6988 bool found = false;
6989 for (int k=0; k < 3; ++k)
6991 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6992 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6994 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6996 found = true;
6997 break;
7000 if(found)
7001 break;
7004 if(found) // and skip re-cast already active aura at form change
7005 return;
7008 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
7010 CastSpell(this,spellInfo,true,item);
7012 else
7014 if(form_change) // check aura compatibility
7016 // Cannot be used in this stance/form
7017 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
7018 return; // and remove only not compatible at form change
7021 if(item)
7022 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
7023 else
7024 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
7028 void Player::UpdateEquipSpellsAtFormChange()
7030 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7032 if(m_items[i] && !m_items[i]->IsBroken())
7034 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
7035 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
7039 // item set bonuses not dependent from item broken state
7040 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
7042 ItemSetEffect* eff = ItemSetEff[setindex];
7043 if(!eff)
7044 continue;
7046 for(uint32 y=0;y<8; ++y)
7048 SpellEntry const* spellInfo = eff->spells[y];
7049 if(!spellInfo)
7050 continue;
7052 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
7053 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
7058 void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
7060 Item *item = GetWeaponForAttack(attType, true, false);
7061 if(!item)
7062 return;
7064 ItemPrototype const *proto = item->GetProto();
7065 if(!proto)
7066 return;
7068 if (!Target || Target == this )
7069 return;
7071 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7073 _Spell const& spellData = proto->Spells[i];
7075 // no spell
7076 if(!spellData.SpellId )
7077 continue;
7079 // wrong triggering type
7080 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7081 continue;
7083 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7084 if(!spellInfo)
7086 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7087 continue;
7090 // not allow proc extra attack spell at extra attack
7091 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7092 return;
7094 float chance = spellInfo->procChance;
7096 if(spellData.SpellPPMRate)
7098 uint32 WeaponSpeed = proto->Delay;
7099 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7101 else if(chance > 100.0f)
7103 chance = GetWeaponProcChance();
7106 if (roll_chance_f(chance))
7107 CastSpell(Target, spellInfo->Id, true, item);
7110 // item combat enchantments
7111 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7113 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7114 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7115 if(!pEnchant) continue;
7116 for (int s=0;s<3;s++)
7118 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7119 continue;
7121 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7122 if (!spellInfo)
7124 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7125 continue;
7128 // Use first rank to access spell item enchant procs
7129 float ppmRate = sSpellMgr.GetItemEnchantProcChance(spellInfo->Id);
7131 float chance = ppmRate
7132 ? GetPPMProcChance(proto->Delay, ppmRate)
7133 : pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7136 ApplySpellMod(spellInfo->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
7137 ApplySpellMod(spellInfo->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
7139 if (roll_chance_f(chance))
7141 if(IsPositiveSpell(pEnchant->spellid[s]))
7142 CastSpell(this, pEnchant->spellid[s], true, item);
7143 else
7144 CastSpell(Target, pEnchant->spellid[s], true, item);
7150 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7152 ItemPrototype const* proto = item->GetProto();
7153 // special learning case
7154 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7156 uint32 learn_spell_id = proto->Spells[0].SpellId;
7157 uint32 learning_spell_id = proto->Spells[1].SpellId;
7159 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7160 if(!spellInfo)
7162 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7163 SendEquipError(EQUIP_ERR_NONE,item,NULL);
7164 return;
7167 Spell *spell = new Spell(this, spellInfo, false);
7168 spell->m_CastItem = item;
7169 spell->m_cast_count = cast_count; //set count of casts
7170 spell->m_currentBasePoints[0] = learning_spell_id;
7171 spell->prepare(&targets);
7172 return;
7175 // use triggered flag only for items with many spell casts and for not first cast
7176 int count = 0;
7178 // item spells casted at use
7179 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7181 _Spell const& spellData = proto->Spells[i];
7183 // no spell
7184 if(!spellData.SpellId)
7185 continue;
7187 // wrong triggering type
7188 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7189 continue;
7191 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7192 if(!spellInfo)
7194 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7195 continue;
7198 Spell *spell = new Spell(this, spellInfo, (count > 0));
7199 spell->m_CastItem = item;
7200 spell->m_cast_count = cast_count; // set count of casts
7201 spell->m_glyphIndex = glyphIndex; // glyph index
7202 spell->prepare(&targets);
7204 ++count;
7207 // Item enchantments spells casted at use
7208 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7210 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7211 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7212 if(!pEnchant) continue;
7213 for (int s=0;s<3;s++)
7215 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7216 continue;
7218 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7219 if (!spellInfo)
7221 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7222 continue;
7225 Spell *spell = new Spell(this, spellInfo, (count > 0));
7226 spell->m_CastItem = item;
7227 spell->m_cast_count = cast_count; // set count of casts
7228 spell->m_glyphIndex = glyphIndex; // glyph index
7229 spell->prepare(&targets);
7231 ++count;
7236 void Player::_RemoveAllItemMods()
7238 sLog.outDebug("_RemoveAllItemMods start.");
7240 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7242 if(m_items[i])
7244 ItemPrototype const *proto = m_items[i]->GetProto();
7245 if(!proto)
7246 continue;
7248 // item set bonuses not dependent from item broken state
7249 if(proto->ItemSet)
7250 RemoveItemsSetItem(this,proto);
7252 if(m_items[i]->IsBroken())
7253 continue;
7255 ApplyItemEquipSpell(m_items[i],false);
7256 ApplyEnchantment(m_items[i], false);
7260 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7262 if(m_items[i])
7264 if(m_items[i]->IsBroken())
7265 continue;
7266 ItemPrototype const *proto = m_items[i]->GetProto();
7267 if(!proto)
7268 continue;
7270 uint32 attacktype = Player::GetAttackBySlot(i);
7271 if(attacktype < MAX_ATTACK)
7272 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7274 _ApplyItemBonuses(proto,i, false);
7276 if( i == EQUIPMENT_SLOT_RANGED )
7277 _ApplyAmmoBonuses();
7281 sLog.outDebug("_RemoveAllItemMods complete.");
7284 void Player::_ApplyAllItemMods()
7286 sLog.outDebug("_ApplyAllItemMods start.");
7288 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7290 if(m_items[i])
7292 if(m_items[i]->IsBroken())
7293 continue;
7295 ItemPrototype const *proto = m_items[i]->GetProto();
7296 if(!proto)
7297 continue;
7299 uint32 attacktype = Player::GetAttackBySlot(i);
7300 if(attacktype < MAX_ATTACK)
7301 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7303 _ApplyItemBonuses(proto,i, true);
7305 if( i == EQUIPMENT_SLOT_RANGED )
7306 _ApplyAmmoBonuses();
7310 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7312 if(m_items[i])
7314 ItemPrototype const *proto = m_items[i]->GetProto();
7315 if(!proto)
7316 continue;
7318 // item set bonuses not dependent from item broken state
7319 if(proto->ItemSet)
7320 AddItemsSetItem(this,m_items[i]);
7322 if(m_items[i]->IsBroken())
7323 continue;
7325 ApplyItemEquipSpell(m_items[i],true);
7326 ApplyEnchantment(m_items[i], true);
7330 sLog.outDebug("_ApplyAllItemMods complete.");
7333 void Player::_ApplyAllLevelScaleItemMods(bool apply)
7335 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7337 if(m_items[i])
7339 if(m_items[i]->IsBroken())
7340 continue;
7342 ItemPrototype const *proto = m_items[i]->GetProto();
7343 if(!proto)
7344 continue;
7346 _ApplyItemBonuses(proto,i, apply, true);
7351 void Player::_ApplyAmmoBonuses()
7353 // check ammo
7354 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7355 if(!ammo_id)
7356 return;
7358 float currentAmmoDPS;
7360 ItemPrototype const *ammo_proto = ObjectMgr::GetItemPrototype( ammo_id );
7361 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7362 currentAmmoDPS = 0.0f;
7363 else
7364 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7366 if(currentAmmoDPS == GetAmmoDPS())
7367 return;
7369 m_ammoDPS = currentAmmoDPS;
7371 if(CanModifyStats())
7372 UpdateDamagePhysical(RANGED_ATTACK);
7375 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7377 if(!ammo_proto)
7378 return false;
7380 // check ranged weapon
7381 Item *weapon = GetWeaponForAttack( RANGED_ATTACK, true, false );
7382 if (!weapon)
7383 return false;
7385 ItemPrototype const* weapon_proto = weapon->GetProto();
7386 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7387 return false;
7389 // check ammo ws. weapon compatibility
7390 switch(weapon_proto->SubClass)
7392 case ITEM_SUBCLASS_WEAPON_BOW:
7393 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7394 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7395 return false;
7396 break;
7397 case ITEM_SUBCLASS_WEAPON_GUN:
7398 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7399 return false;
7400 break;
7401 default:
7402 return false;
7405 return true;
7408 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7409 Called by remove insignia spell effect */
7410 void Player::RemovedInsignia(Player* looterPlr)
7412 if (!GetBattleGroundId())
7413 return;
7415 // If not released spirit, do it !
7416 if(m_deathTimer > 0)
7418 m_deathTimer = 0;
7419 BuildPlayerRepop();
7420 RepopAtGraveyard();
7423 Corpse *corpse = GetCorpse();
7424 if (!corpse)
7425 return;
7427 // We have to convert player corpse to bones, not to be able to resurrect there
7428 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7429 Corpse *bones = sObjectAccessor.ConvertCorpseForPlayer(GetGUID(),true);
7430 if (!bones)
7431 return;
7433 // Now we must make bones lootable, and send player loot
7434 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7436 // We store the level of our player in the gold field
7437 // We retrieve this information at Player::SendLoot()
7438 bones->loot.gold = getLevel();
7439 bones->lootRecipient = looterPlr;
7440 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7443 void Player::SendLootRelease( uint64 guid )
7445 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7446 data << uint64(guid) << uint8(1);
7447 SendDirectMessage( &data );
7450 void Player::SendLoot(uint64 guid, LootType loot_type)
7452 if (uint64 lguid = GetLootGUID())
7453 m_session->DoLootRelease(lguid);
7455 Loot *loot = 0;
7456 PermissionTypes permission = ALL_PERMISSION;
7458 sLog.outDebug("Player::SendLoot");
7459 if (IS_GAMEOBJECT_GUID(guid))
7461 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7462 GameObject *go = GetMap()->GetGameObject(guid);
7464 // not check distance for GO in case owned GO (fishing bobber case, for example)
7465 // And permit out of range GO with no owner in case fishing hole
7466 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7468 SendLootRelease(guid);
7469 return;
7472 loot = &go->loot;
7474 if (go->getLootState() == GO_READY)
7476 uint32 lootid = go->GetGOInfo()->GetLootId();
7477 if ((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S))
7478 if (BattleGround *bg = GetBattleGround())
7479 if (bg->GetTypeID() == BATTLEGROUND_AV)
7480 if (!(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(go->GetEntry(), GetTeam())))
7482 SendLootRelease(guid);
7483 return;
7486 if (lootid)
7488 sLog.outDebug(" if(lootid)");
7489 loot->clear();
7490 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7493 if (loot_type == LOOT_FISHING)
7494 go->getFishLoot(loot,this);
7496 go->SetLootState(GO_ACTIVATED);
7499 else if (IS_ITEM_GUID(guid))
7501 Item *item = GetItemByGuid( guid );
7503 if (!item)
7505 SendLootRelease(guid);
7506 return;
7509 loot = &item->loot;
7511 if (!item->m_lootGenerated)
7513 item->m_lootGenerated = true;
7514 loot->clear();
7516 switch(loot_type)
7518 case LOOT_DISENCHANTING:
7519 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7520 break;
7521 case LOOT_PROSPECTING:
7522 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7523 break;
7524 case LOOT_MILLING:
7525 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7526 break;
7527 default:
7528 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7529 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7530 break;
7534 else if (IS_CORPSE_GUID(guid)) // remove insignia
7536 Corpse *bones = GetMap()->GetCorpse(guid);
7538 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7540 SendLootRelease(guid);
7541 return;
7544 loot = &bones->loot;
7546 if (!bones->lootForBody)
7548 bones->lootForBody = true;
7549 uint32 pLevel = bones->loot.gold;
7550 bones->loot.clear();
7551 if (GetBattleGround()->GetTypeID() == BATTLEGROUND_AV)
7552 loot->FillLoot(0, LootTemplates_Creature, this, false);
7553 // It may need a better formula
7554 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7555 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7558 if (bones->lootRecipient != this)
7559 permission = NONE_PERMISSION;
7561 else
7563 Creature *creature = GetMap()->GetCreature(guid);
7565 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7566 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7568 SendLootRelease(guid);
7569 return;
7572 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7574 SendLootRelease(guid);
7575 return;
7578 loot = &creature->loot;
7580 if (loot_type == LOOT_PICKPOCKETING)
7582 if (!creature->lootForPickPocketed)
7584 creature->lootForPickPocketed = true;
7585 loot->clear();
7587 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7588 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7590 // Generate extra money for pick pocket loot
7591 const uint32 a = urand(0, creature->getLevel()/2);
7592 const uint32 b = urand(0, getLevel()/2);
7593 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7596 else
7598 // the player whose group may loot the corpse
7599 Player *recipient = creature->GetLootRecipient();
7600 if (!recipient)
7602 creature->SetLootRecipient(this);
7603 recipient = this;
7606 if (creature->lootForPickPocketed)
7608 creature->lootForPickPocketed = false;
7609 loot->clear();
7612 if (!creature->lootForBody)
7614 creature->lootForBody = true;
7615 loot->clear();
7617 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7618 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7620 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7622 if (Group* group = recipient->GetGroup())
7624 group->UpdateLooterGuid(creature,true);
7626 switch (group->GetLootMethod())
7628 case GROUP_LOOT:
7629 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7630 group->GroupLoot(recipient->GetGUID(), loot, creature);
7631 break;
7632 case NEED_BEFORE_GREED:
7633 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7634 break;
7635 case MASTER_LOOT:
7636 group->MasterLoot(recipient->GetGUID(), loot, creature);
7637 break;
7638 default:
7639 break;
7644 // possible only if creature->lootForBody && loot->empty() at spell cast check
7645 if (loot_type == LOOT_SKINNING)
7647 loot->clear();
7648 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7650 // set group rights only for loot_type != LOOT_SKINNING
7651 else
7653 if(Group* group = GetGroup())
7655 if (group == recipient->GetGroup())
7657 if (group->GetLootMethod() == FREE_FOR_ALL)
7658 permission = ALL_PERMISSION;
7659 else if (group->GetLooterGuid() == GetGUID())
7661 if (group->GetLootMethod() == MASTER_LOOT)
7662 permission = MASTER_PERMISSION;
7663 else
7664 permission = ALL_PERMISSION;
7666 else
7667 permission = GROUP_PERMISSION;
7669 else
7670 permission = NONE_PERMISSION;
7672 else if (recipient == this)
7673 permission = ALL_PERMISSION;
7674 else
7675 permission = NONE_PERMISSION;
7680 SetLootGUID(guid);
7682 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7683 switch(loot_type)
7685 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7686 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7687 default: break;
7690 // need know merged fishing/corpse loot type for achievements
7691 loot->loot_type = loot_type;
7693 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7695 data << uint64(guid);
7696 data << uint8(loot_type);
7697 data << LootView(*loot, this, permission);
7699 SendDirectMessage(&data);
7701 // add 'this' player as one of the players that are looting 'loot'
7702 if (permission != NONE_PERMISSION)
7703 loot->AddLooter(GetGUID());
7705 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7706 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7709 void Player::SendNotifyLootMoneyRemoved()
7711 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7712 GetSession()->SendPacket( &data );
7715 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7717 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7718 data << uint8(lootSlot);
7719 GetSession()->SendPacket( &data );
7722 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7724 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7725 data << Field;
7726 data << Value;
7727 GetSession()->SendPacket(&data);
7730 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7732 // data depends on zoneid/mapid...
7733 BattleGround* bg = GetBattleGround();
7734 uint16 NumberOfFields = 0;
7735 uint32 mapid = GetMapId();
7737 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7739 // may be exist better way to do this...
7740 switch(zoneid)
7742 case 0:
7743 case 1:
7744 case 4:
7745 case 8:
7746 case 10:
7747 case 11:
7748 case 12:
7749 case 36:
7750 case 38:
7751 case 40:
7752 case 41:
7753 case 51:
7754 case 267:
7755 case 1519:
7756 case 1537:
7757 case 2257:
7758 case 2918:
7759 NumberOfFields = 8;
7760 break;
7761 case 139:
7762 NumberOfFields = 41;
7763 break;
7764 case 1377:
7765 NumberOfFields = 15;
7766 break;
7767 case 2597:
7768 NumberOfFields = 83;
7769 break;
7770 case 3277:
7771 NumberOfFields = 16;
7772 break;
7773 case 3358:
7774 case 3820:
7775 NumberOfFields = 40;
7776 break;
7777 case 3483:
7778 NumberOfFields = 27;
7779 break;
7780 case 3518:
7781 NumberOfFields = 39;
7782 break;
7783 case 3519:
7784 NumberOfFields = 38;
7785 break;
7786 case 3521:
7787 NumberOfFields = 37;
7788 break;
7789 case 3698:
7790 case 3702:
7791 case 3968:
7792 NumberOfFields = 11;
7793 break;
7794 case 3703:
7795 NumberOfFields = 11;
7796 break;
7797 default:
7798 NumberOfFields = 12;
7799 break;
7802 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7803 data << uint32(mapid); // mapid
7804 data << uint32(zoneid); // zone id
7805 data << uint32(areaid); // area id, new 2.1.0
7806 data << uint16(NumberOfFields); // count of uint64 blocks
7807 data << uint32(0x8d8) << uint32(0x0); // 1
7808 data << uint32(0x8d7) << uint32(0x0); // 2
7809 data << uint32(0x8d6) << uint32(0x0); // 3
7810 data << uint32(0x8d5) << uint32(0x0); // 4
7811 data << uint32(0x8d4) << uint32(0x0); // 5
7812 data << uint32(0x8d3) << uint32(0x0); // 6
7813 // 7 1 - Arena season in progress, 0 - end of season
7814 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7815 // 8 Arena season id
7816 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7817 if(mapid == 530) // Outland
7819 data << uint32(0x9bf) << uint32(0x0); // 7
7820 data << uint32(0x9bd) << uint32(0xF); // 8
7821 data << uint32(0x9bb) << uint32(0xF); // 9
7823 switch(zoneid)
7825 case 1:
7826 case 11:
7827 case 12:
7828 case 38:
7829 case 40:
7830 case 51:
7831 case 1519:
7832 case 1537:
7833 case 2257:
7834 break;
7835 case 2597: // AV
7836 if (bg && bg->GetTypeID() == BATTLEGROUND_AV)
7837 bg->FillInitialWorldStates(data);
7838 else
7840 data << uint32(0x7ae) << uint32(0x1); // 7 snowfall n
7841 data << uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
7842 data << uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
7843 data << uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
7844 data << uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
7845 data << uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
7846 data << uint32(0x567) << uint32(0x1); // 13 frostwolfe c
7847 data << uint32(0x566) << uint32(0x1); // 14 frostwolfw c
7848 data << uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
7849 data << uint32(0x544) << uint32(0x0); // 16 ice grave a_a
7850 data << uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
7851 data << uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
7852 data << uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
7853 data << uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
7854 data << uint32(0x574) << uint32(0x0); // 21 1396 unk
7855 data << uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
7856 data << uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
7857 data << uint32(0x56f) << uint32(0x0); // 24 1391 unk
7858 data << uint32(0x56e) << uint32(0x0); // 25 iceblood a
7859 data << uint32(0x56d) << uint32(0x0); // 26 towerp a
7860 data << uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
7861 data << uint32(0x56b) << uint32(0x0); // 28 froswolfw a
7862 data << uint32(0x56a) << uint32(0x1); // 29 1386 unk
7863 data << uint32(0x569) << uint32(0x1); // 30 iceblood c
7864 data << uint32(0x568) << uint32(0x1); // 31 towerp c
7865 data << uint32(0x565) << uint32(0x0); // 32 stoneh tower a
7866 data << uint32(0x564) << uint32(0x0); // 33 icewing tower a
7867 data << uint32(0x563) << uint32(0x0); // 34 dunn a
7868 data << uint32(0x562) << uint32(0x0); // 35 duns a
7869 data << uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
7870 data << uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
7871 data << uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
7872 data << uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
7873 data << uint32(0x55d) << uint32(0x0); // 40 stone tower d
7874 data << uint32(0x3c6) << uint32(0x0); // 41 966 unk
7875 data << uint32(0x3c4) << uint32(0x0); // 42 964 unk
7876 data << uint32(0x3c2) << uint32(0x0); // 43 962 unk
7877 data << uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
7878 data << uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
7879 data << uint32(0x3b6) << uint32(0x0); // 46 950 unk
7880 data << uint32(0x55c) << uint32(0x0); // 47 icewing tower d
7881 data << uint32(0x55b) << uint32(0x0); // 48 dunn d
7882 data << uint32(0x55a) << uint32(0x0); // 49 duns d
7883 data << uint32(0x559) << uint32(0x0); // 50 1369 unk
7884 data << uint32(0x558) << uint32(0x0); // 51 iceblood d
7885 data << uint32(0x557) << uint32(0x0); // 52 towerp d
7886 data << uint32(0x556) << uint32(0x0); // 53 frostwolfe d
7887 data << uint32(0x555) << uint32(0x0); // 54 frostwolfw d
7888 data << uint32(0x554) << uint32(0x1); // 55 stoneh tower c
7889 data << uint32(0x553) << uint32(0x1); // 56 icewing tower c
7890 data << uint32(0x552) << uint32(0x1); // 57 dunn c
7891 data << uint32(0x551) << uint32(0x1); // 58 duns c
7892 data << uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
7893 data << uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
7894 data << uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
7895 data << uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
7896 data << uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
7897 data << uint32(0x545) << uint32(0x0); // 64 iceblood h_a
7898 data << uint32(0x543) << uint32(0x1); // 65 iceblod h_c
7899 data << uint32(0x542) << uint32(0x0); // 66 iceblood a_c
7900 data << uint32(0x540) << uint32(0x0); // 67 snowfall h_a
7901 data << uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
7902 data << uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
7903 data << uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
7904 data << uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
7905 data << uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
7906 data << uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
7907 data << uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
7908 data << uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
7909 data << uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
7910 data << uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
7911 data << uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
7912 data << uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
7913 data << uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
7914 data << uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
7916 break;
7917 case 3277: // WS
7918 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7919 bg->FillInitialWorldStates(data);
7920 else
7922 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7923 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7924 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7925 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7926 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7927 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7928 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7929 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7931 break;
7932 case 3358: // AB
7933 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7934 bg->FillInitialWorldStates(data);
7935 else
7937 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7938 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7939 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7940 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7941 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7942 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7943 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7944 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7945 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7946 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7947 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7948 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7949 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7950 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7951 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7952 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7953 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7954 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7955 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7956 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7957 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7958 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7959 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7960 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7961 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7962 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7963 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7964 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7965 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7966 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7967 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7968 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7970 break;
7971 case 3820: // EY
7972 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7973 bg->FillInitialWorldStates(data);
7974 else
7976 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7977 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7978 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7979 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7980 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7981 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7982 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7983 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7984 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7985 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7986 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7987 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7988 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7989 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7990 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7991 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7992 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7993 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7994 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7995 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7996 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7997 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7998 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7999 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
8000 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
8001 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
8002 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
8003 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
8004 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
8005 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
8006 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
8007 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
8008 // and some more ... unknown
8010 break;
8011 case 3483: // Hellfire Peninsula
8012 data << uint32(0x9ba) << uint32(0x1); // 10
8013 data << uint32(0x9b9) << uint32(0x1); // 11
8014 data << uint32(0x9b5) << uint32(0x0); // 12
8015 data << uint32(0x9b4) << uint32(0x1); // 13
8016 data << uint32(0x9b3) << uint32(0x0); // 14
8017 data << uint32(0x9b2) << uint32(0x0); // 15
8018 data << uint32(0x9b1) << uint32(0x1); // 16
8019 data << uint32(0x9b0) << uint32(0x0); // 17
8020 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
8021 data << uint32(0x9ac) << uint32(0x0); // 19
8022 data << uint32(0x9a8) << uint32(0x0); // 20
8023 data << uint32(0x9a7) << uint32(0x0); // 21
8024 data << uint32(0x9a6) << uint32(0x1); // 22
8025 break;
8026 case 3519: // Terokkar Forest
8027 data << uint32(0xa41) << uint32(0x0); // 10
8028 data << uint32(0xa40) << uint32(0x14); // 11
8029 data << uint32(0xa3f) << uint32(0x0); // 12
8030 data << uint32(0xa3e) << uint32(0x0); // 13
8031 data << uint32(0xa3d) << uint32(0x5); // 14
8032 data << uint32(0xa3c) << uint32(0x0); // 15
8033 data << uint32(0xa87) << uint32(0x0); // 16
8034 data << uint32(0xa86) << uint32(0x0); // 17
8035 data << uint32(0xa85) << uint32(0x0); // 18
8036 data << uint32(0xa84) << uint32(0x0); // 19
8037 data << uint32(0xa83) << uint32(0x0); // 20
8038 data << uint32(0xa82) << uint32(0x0); // 21
8039 data << uint32(0xa81) << uint32(0x0); // 22
8040 data << uint32(0xa80) << uint32(0x0); // 23
8041 data << uint32(0xa7e) << uint32(0x0); // 24
8042 data << uint32(0xa7d) << uint32(0x0); // 25
8043 data << uint32(0xa7c) << uint32(0x0); // 26
8044 data << uint32(0xa7b) << uint32(0x0); // 27
8045 data << uint32(0xa7a) << uint32(0x0); // 28
8046 data << uint32(0xa79) << uint32(0x0); // 29
8047 data << uint32(0x9d0) << uint32(0x5); // 30
8048 data << uint32(0x9ce) << uint32(0x0); // 31
8049 data << uint32(0x9cd) << uint32(0x0); // 32
8050 data << uint32(0x9cc) << uint32(0x0); // 33
8051 data << uint32(0xa88) << uint32(0x0); // 34
8052 data << uint32(0xad0) << uint32(0x0); // 35
8053 data << uint32(0xacf) << uint32(0x1); // 36
8054 break;
8055 case 3521: // Zangarmarsh
8056 data << uint32(0x9e1) << uint32(0x0); // 10
8057 data << uint32(0x9e0) << uint32(0x0); // 11
8058 data << uint32(0x9df) << uint32(0x0); // 12
8059 data << uint32(0xa5d) << uint32(0x1); // 13
8060 data << uint32(0xa5c) << uint32(0x0); // 14
8061 data << uint32(0xa5b) << uint32(0x1); // 15
8062 data << uint32(0xa5a) << uint32(0x0); // 16
8063 data << uint32(0xa59) << uint32(0x1); // 17
8064 data << uint32(0xa58) << uint32(0x0); // 18
8065 data << uint32(0xa57) << uint32(0x0); // 19
8066 data << uint32(0xa56) << uint32(0x0); // 20
8067 data << uint32(0xa55) << uint32(0x1); // 21
8068 data << uint32(0xa54) << uint32(0x0); // 22
8069 data << uint32(0x9e7) << uint32(0x0); // 23
8070 data << uint32(0x9e6) << uint32(0x0); // 24
8071 data << uint32(0x9e5) << uint32(0x0); // 25
8072 data << uint32(0xa00) << uint32(0x0); // 26
8073 data << uint32(0x9ff) << uint32(0x1); // 27
8074 data << uint32(0x9fe) << uint32(0x0); // 28
8075 data << uint32(0x9fd) << uint32(0x0); // 29
8076 data << uint32(0x9fc) << uint32(0x1); // 30
8077 data << uint32(0x9fb) << uint32(0x0); // 31
8078 data << uint32(0xa62) << uint32(0x0); // 32
8079 data << uint32(0xa61) << uint32(0x1); // 33
8080 data << uint32(0xa60) << uint32(0x1); // 34
8081 data << uint32(0xa5f) << uint32(0x0); // 35
8082 break;
8083 case 3698: // Nagrand Arena
8084 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
8085 bg->FillInitialWorldStates(data);
8086 else
8088 data << uint32(0xa0f) << uint32(0x0); // 7
8089 data << uint32(0xa10) << uint32(0x0); // 8
8090 data << uint32(0xa11) << uint32(0x0); // 9 show
8092 break;
8093 case 3702: // Blade's Edge Arena
8094 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8095 bg->FillInitialWorldStates(data);
8096 else
8098 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8099 data << uint32(0x9f1) << uint32(0x0); // 8 green
8100 data << uint32(0x9f3) << uint32(0x0); // 9 show
8102 break;
8103 case 3968: // Ruins of Lordaeron
8104 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8105 bg->FillInitialWorldStates(data);
8106 else
8108 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8109 data << uint32(0xbb9) << uint32(0x0); // 8 green
8110 data << uint32(0xbba) << uint32(0x0); // 9 show
8112 break;
8113 case 3703: // Shattrath City
8114 break;
8115 default:
8116 data << uint32(0x914) << uint32(0x0); // 7
8117 data << uint32(0x913) << uint32(0x0); // 8
8118 data << uint32(0x912) << uint32(0x0); // 9
8119 data << uint32(0x915) << uint32(0x0); // 10
8120 break;
8122 GetSession()->SendPacket(&data);
8125 uint32 Player::GetXPRestBonus(uint32 xp)
8127 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8129 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8130 rested_bonus = xp;
8132 SetRestBonus( GetRestBonus() - rested_bonus);
8134 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8135 return rested_bonus;
8138 void Player::SetBindPoint(uint64 guid)
8140 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8141 data << uint64(guid);
8142 GetSession()->SendPacket( &data );
8145 void Player::SendTalentWipeConfirm(uint64 guid)
8147 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8148 data << uint64(guid);
8149 data << uint32(resetTalentsCost());
8150 GetSession()->SendPacket( &data );
8153 void Player::SendPetSkillWipeConfirm()
8155 Pet* pet = GetPet();
8156 if(!pet)
8157 return;
8158 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8159 data << pet->GetGUID();
8160 data << uint32(pet->resetTalentsCost());
8161 GetSession()->SendPacket( &data );
8164 /*********************************************************/
8165 /*** STORAGE SYSTEM ***/
8166 /*********************************************************/
8168 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8170 assert(i < 3);
8171 if(i < 2 && item)
8173 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8174 return;
8175 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8176 if(charges == 0)
8177 return;
8178 if(charges > 1)
8179 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8180 else if(charges <= 1)
8182 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8183 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8188 void Player::SetSheath( SheathState sheathed )
8190 switch (sheathed)
8192 case SHEATH_STATE_UNARMED: // no prepared weapon
8193 SetVirtualItemSlot(0,NULL);
8194 SetVirtualItemSlot(1,NULL);
8195 SetVirtualItemSlot(2,NULL);
8196 break;
8197 case SHEATH_STATE_MELEE: // prepared melee weapon
8199 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true,true));
8200 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true,true));
8201 SetVirtualItemSlot(2,NULL);
8202 }; break;
8203 case SHEATH_STATE_RANGED: // prepared ranged weapon
8204 SetVirtualItemSlot(0,NULL);
8205 SetVirtualItemSlot(1,NULL);
8206 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true,true));
8207 break;
8208 default:
8209 SetVirtualItemSlot(0,NULL);
8210 SetVirtualItemSlot(1,NULL);
8211 SetVirtualItemSlot(2,NULL);
8212 break;
8214 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
8217 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8219 uint8 pClass = getClass();
8221 uint8 slots[4];
8222 slots[0] = NULL_SLOT;
8223 slots[1] = NULL_SLOT;
8224 slots[2] = NULL_SLOT;
8225 slots[3] = NULL_SLOT;
8226 switch( proto->InventoryType )
8228 case INVTYPE_HEAD:
8229 slots[0] = EQUIPMENT_SLOT_HEAD;
8230 break;
8231 case INVTYPE_NECK:
8232 slots[0] = EQUIPMENT_SLOT_NECK;
8233 break;
8234 case INVTYPE_SHOULDERS:
8235 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8236 break;
8237 case INVTYPE_BODY:
8238 slots[0] = EQUIPMENT_SLOT_BODY;
8239 break;
8240 case INVTYPE_CHEST:
8241 slots[0] = EQUIPMENT_SLOT_CHEST;
8242 break;
8243 case INVTYPE_ROBE:
8244 slots[0] = EQUIPMENT_SLOT_CHEST;
8245 break;
8246 case INVTYPE_WAIST:
8247 slots[0] = EQUIPMENT_SLOT_WAIST;
8248 break;
8249 case INVTYPE_LEGS:
8250 slots[0] = EQUIPMENT_SLOT_LEGS;
8251 break;
8252 case INVTYPE_FEET:
8253 slots[0] = EQUIPMENT_SLOT_FEET;
8254 break;
8255 case INVTYPE_WRISTS:
8256 slots[0] = EQUIPMENT_SLOT_WRISTS;
8257 break;
8258 case INVTYPE_HANDS:
8259 slots[0] = EQUIPMENT_SLOT_HANDS;
8260 break;
8261 case INVTYPE_FINGER:
8262 slots[0] = EQUIPMENT_SLOT_FINGER1;
8263 slots[1] = EQUIPMENT_SLOT_FINGER2;
8264 break;
8265 case INVTYPE_TRINKET:
8266 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8267 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8268 break;
8269 case INVTYPE_CLOAK:
8270 slots[0] = EQUIPMENT_SLOT_BACK;
8271 break;
8272 case INVTYPE_WEAPON:
8274 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8276 // suggest offhand slot only if know dual wielding
8277 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8278 if(CanDualWield())
8279 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8280 break;
8282 case INVTYPE_SHIELD:
8283 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8284 break;
8285 case INVTYPE_RANGED:
8286 slots[0] = EQUIPMENT_SLOT_RANGED;
8287 break;
8288 case INVTYPE_2HWEAPON:
8289 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8290 if (CanDualWield() && CanTitanGrip())
8291 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8292 break;
8293 case INVTYPE_TABARD:
8294 slots[0] = EQUIPMENT_SLOT_TABARD;
8295 break;
8296 case INVTYPE_WEAPONMAINHAND:
8297 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8298 break;
8299 case INVTYPE_WEAPONOFFHAND:
8300 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8301 break;
8302 case INVTYPE_HOLDABLE:
8303 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8304 break;
8305 case INVTYPE_THROWN:
8306 slots[0] = EQUIPMENT_SLOT_RANGED;
8307 break;
8308 case INVTYPE_RANGEDRIGHT:
8309 slots[0] = EQUIPMENT_SLOT_RANGED;
8310 break;
8311 case INVTYPE_BAG:
8312 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8313 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8314 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8315 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8316 break;
8317 case INVTYPE_RELIC:
8319 switch(proto->SubClass)
8321 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8322 if (pClass == CLASS_PALADIN)
8323 slots[0] = EQUIPMENT_SLOT_RANGED;
8324 break;
8325 case ITEM_SUBCLASS_ARMOR_IDOL:
8326 if (pClass == CLASS_DRUID)
8327 slots[0] = EQUIPMENT_SLOT_RANGED;
8328 break;
8329 case ITEM_SUBCLASS_ARMOR_TOTEM:
8330 if (pClass == CLASS_SHAMAN)
8331 slots[0] = EQUIPMENT_SLOT_RANGED;
8332 break;
8333 case ITEM_SUBCLASS_ARMOR_MISC:
8334 if (pClass == CLASS_WARLOCK)
8335 slots[0] = EQUIPMENT_SLOT_RANGED;
8336 break;
8337 case ITEM_SUBCLASS_ARMOR_SIGIL:
8338 if (pClass == CLASS_DEATH_KNIGHT)
8339 slots[0] = EQUIPMENT_SLOT_RANGED;
8340 break;
8342 break;
8344 default :
8345 return NULL_SLOT;
8348 if( slot != NULL_SLOT )
8350 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8352 for (int i = 0; i < 4; ++i)
8354 if ( slots[i] == slot )
8355 return slot;
8359 else
8361 // search free slot at first
8362 for (int i = 0; i < 4; ++i)
8364 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8366 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8367 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8368 return slots[i];
8372 // if not found free and can swap return first appropriate from used
8373 for (int i = 0; i < 4; ++i)
8375 if ( slots[i] != NULL_SLOT && swap )
8376 return slots[i];
8380 // no free position
8381 return NULL_SLOT;
8384 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8386 Item *pItem;
8387 uint32 tempcount = 0;
8389 uint8 res = EQUIP_ERR_OK;
8391 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8393 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8394 if( pItem && pItem->GetEntry() == item )
8396 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8397 if(ires==EQUIP_ERR_OK)
8399 tempcount += pItem->GetCount();
8400 if( tempcount >= count )
8401 return EQUIP_ERR_OK;
8403 else
8404 res = ires;
8407 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8409 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8410 if( pItem && pItem->GetEntry() == item )
8412 tempcount += pItem->GetCount();
8413 if( tempcount >= count )
8414 return EQUIP_ERR_OK;
8417 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8419 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8420 if( pItem && pItem->GetEntry() == item )
8422 tempcount += pItem->GetCount();
8423 if( tempcount >= count )
8424 return EQUIP_ERR_OK;
8427 Bag *pBag;
8428 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8430 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8431 if( pBag )
8433 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8435 pItem = GetItemByPos( i, j );
8436 if( pItem && pItem->GetEntry() == item )
8438 tempcount += pItem->GetCount();
8439 if( tempcount >= count )
8440 return EQUIP_ERR_OK;
8446 // not found req. item count and have unequippable items
8447 return res;
8450 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8452 uint32 count = 0;
8453 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8455 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8456 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8457 count += pItem->GetCount();
8459 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8461 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8462 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8463 count += pItem->GetCount();
8465 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8467 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8468 if( pBag )
8469 count += pBag->GetItemCount(item,skipItem);
8472 if(skipItem && skipItem->GetProto()->GemProperties)
8474 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8476 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8477 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8478 count += pItem->GetGemCountWithID(item);
8482 if(inBankAlso)
8484 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8486 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8487 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8488 count += pItem->GetCount();
8490 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8492 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8493 if( pBag )
8494 count += pBag->GetItemCount(item,skipItem);
8497 if(skipItem && skipItem->GetProto()->GemProperties)
8499 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8501 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8502 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8503 count += pItem->GetGemCountWithID(item);
8508 return count;
8511 Item* Player::GetItemByGuid( uint64 guid ) const
8513 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8515 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8516 if( pItem && pItem->GetGUID() == guid )
8517 return pItem;
8519 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8521 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8522 if( pItem && pItem->GetGUID() == guid )
8523 return pItem;
8526 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8528 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8529 if( pBag )
8531 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8533 Item* pItem = pBag->GetItemByPos( j );
8534 if( pItem && pItem->GetGUID() == guid )
8535 return pItem;
8539 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8541 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8542 if( pBag )
8544 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8546 Item* pItem = pBag->GetItemByPos( j );
8547 if( pItem && pItem->GetGUID() == guid )
8548 return pItem;
8553 return NULL;
8556 Item* Player::GetItemByPos( uint16 pos ) const
8558 uint8 bag = pos >> 8;
8559 uint8 slot = pos & 255;
8560 return GetItemByPos( bag, slot );
8563 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8565 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END )) )
8566 return m_items[slot];
8567 else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8568 || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END) )
8570 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8571 if ( pBag )
8572 return pBag->GetItemByPos(slot);
8574 return NULL;
8577 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool nonbroken, bool useable) const
8579 uint16 slot;
8580 switch (attackType)
8582 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8583 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8584 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8585 default: return NULL;
8588 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8589 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8590 return NULL;
8592 if (useable && !IsUseEquipedWeapon(attackType==BASE_ATTACK))
8593 return NULL;
8595 if (nonbroken && item->IsBroken())
8596 return NULL;
8598 return item;
8601 Item* Player::GetShield(bool useable) const
8603 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8604 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8605 return NULL;
8607 if(!useable)
8608 return item;
8610 if( item->IsBroken())
8611 return NULL;
8613 return item;
8616 uint32 Player::GetAttackBySlot( uint8 slot )
8618 switch(slot)
8620 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8621 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8622 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8623 default: return MAX_ATTACK;
8627 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8629 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8630 return true;
8631 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8632 return true;
8633 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8634 return true;
8635 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8636 return true;
8637 return false;
8640 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8642 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8643 return true;
8644 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8645 return true;
8646 return false;
8649 bool Player::IsBankPos( uint8 bag, uint8 slot )
8651 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8652 return true;
8653 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8654 return true;
8655 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8656 return true;
8657 return false;
8660 bool Player::IsBagPos( uint16 pos )
8662 uint8 bag = pos >> 8;
8663 uint8 slot = pos & 255;
8664 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8665 return true;
8666 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8667 return true;
8668 return false;
8671 bool Player::IsValidPos( uint8 bag, uint8 slot, bool explicit_pos )
8673 // post selected
8674 if(bag == NULL_BAG && !explicit_pos)
8675 return true;
8677 if (bag == INVENTORY_SLOT_BAG_0)
8679 // any post selected
8680 if (slot == NULL_SLOT && !explicit_pos)
8681 return true;
8683 // equipment
8684 if (slot < EQUIPMENT_SLOT_END)
8685 return true;
8687 // bag equip slots
8688 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8689 return true;
8691 // backpack slots
8692 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8693 return true;
8695 // keyring slots
8696 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8697 return true;
8699 // bank main slots
8700 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8701 return true;
8703 // bank bag slots
8704 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8705 return true;
8707 return false;
8710 // bag content slots
8711 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8713 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8714 if(!pBag)
8715 return false;
8717 // any post selected
8718 if (slot == NULL_SLOT && !explicit_pos)
8719 return true;
8721 return slot < pBag->GetBagSize();
8724 // bank bag content slots
8725 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8727 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8728 if(!pBag)
8729 return false;
8731 // any post selected
8732 if (slot == NULL_SLOT && !explicit_pos)
8733 return true;
8735 return slot < pBag->GetBagSize();
8738 // where this?
8739 return false;
8743 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8745 uint32 tempcount = 0;
8746 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8748 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8749 if( pItem && pItem->GetEntry() == item )
8751 tempcount += pItem->GetCount();
8752 if( tempcount >= count )
8753 return true;
8756 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8758 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8759 if( pItem && pItem->GetEntry() == item )
8761 tempcount += pItem->GetCount();
8762 if( tempcount >= count )
8763 return true;
8766 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8768 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8770 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8772 Item* pItem = GetItemByPos( i, j );
8773 if( pItem && pItem->GetEntry() == item )
8775 tempcount += pItem->GetCount();
8776 if( tempcount >= count )
8777 return true;
8783 if(inBankAlso)
8785 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8787 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8788 if( pItem && pItem->GetEntry() == item )
8790 tempcount += pItem->GetCount();
8791 if( tempcount >= count )
8792 return true;
8795 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8797 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8799 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8801 Item* pItem = GetItemByPos( i, j );
8802 if( pItem && pItem->GetEntry() == item )
8804 tempcount += pItem->GetCount();
8805 if( tempcount >= count )
8806 return true;
8813 return false;
8816 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8818 uint32 tempcount = 0;
8819 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8821 if(i==int(except_slot))
8822 continue;
8824 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8825 if( pItem && pItem->GetEntry() == item)
8827 tempcount += pItem->GetCount();
8828 if( tempcount >= count )
8829 return true;
8833 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item);
8834 if (pProto && pProto->GemProperties)
8836 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8838 if(i==int(except_slot))
8839 continue;
8841 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8842 if( pItem && pItem->GetProto()->Socket[0].Color)
8844 tempcount += pItem->GetGemCountWithID(item);
8845 if( tempcount >= count )
8846 return true;
8851 return false;
8854 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8856 uint32 tempcount = 0;
8857 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8859 if(i==int(except_slot))
8860 continue;
8862 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8863 if (!pItem)
8864 continue;
8866 ItemPrototype const *pProto = pItem->GetProto();
8867 if (!pProto)
8868 continue;
8870 if (pProto->ItemLimitCategory == limitCategory)
8872 tempcount += pItem->GetCount();
8873 if( tempcount >= count )
8874 return true;
8877 if( pProto->Socket[0].Color)
8879 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8880 if( tempcount >= count )
8881 return true;
8885 return false;
8888 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8890 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
8891 if( !pProto )
8893 if(no_space_count)
8894 *no_space_count = count;
8895 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8898 // no maximum
8899 if(pProto->MaxCount <= 0)
8900 return EQUIP_ERR_OK;
8902 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8904 if (curcount + count > uint32(pProto->MaxCount))
8906 if(no_space_count)
8907 *no_space_count = count +curcount - pProto->MaxCount;
8908 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8911 return EQUIP_ERR_OK;
8914 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8916 Item *pItem;
8917 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8919 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8920 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8921 return true;
8923 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8925 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8926 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8927 return true;
8929 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8931 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8933 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8935 pItem = GetItemByPos( i, j );
8936 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8937 return true;
8941 return false;
8944 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8946 Item* pItem2 = GetItemByPos( bag, slot );
8948 // ignore move item (this slot will be empty at move)
8949 if (pItem2==pSrcItem)
8950 pItem2 = NULL;
8952 uint32 need_space;
8954 // empty specific slot - check item fit to slot
8955 if (!pItem2 || swap)
8957 if (bag == INVENTORY_SLOT_BAG_0)
8959 // keyring case
8960 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8961 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8963 // currencytoken case
8964 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8965 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8967 // prevent cheating
8968 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8969 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8971 else
8973 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8974 if (!pBag)
8975 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8977 ItemPrototype const* pBagProto = pBag->GetProto();
8978 if (!pBagProto)
8979 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8981 if (slot >= pBagProto->ContainerSlots)
8982 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8984 if (!ItemCanGoIntoBag(pProto,pBagProto))
8985 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8988 // non empty stack with space
8989 need_space = pProto->GetMaxStackSize();
8991 // non empty slot, check item type
8992 else
8994 // check item type
8995 if (pItem2->GetEntry() != pProto->ItemId)
8996 return EQUIP_ERR_ITEM_CANT_STACK;
8998 // check free space
8999 if (pItem2->GetCount() >= pProto->GetMaxStackSize())
9000 return EQUIP_ERR_ITEM_CANT_STACK;
9002 // free stack space or infinity
9003 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9006 if (need_space > count)
9007 need_space = count;
9009 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
9010 if (!newPosition.isContainedIn(dest))
9012 dest.push_back(newPosition);
9013 count -= need_space;
9015 return EQUIP_ERR_OK;
9018 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
9020 // skip specific bag already processed in first called _CanStoreItem_InBag
9021 if (bag==skip_bag)
9022 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9024 // skip not existed bag or self targeted bag
9025 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9026 if (!pBag || pBag==pSrcItem)
9027 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9029 ItemPrototype const* pBagProto = pBag->GetProto();
9030 if (!pBagProto)
9031 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9033 // specialized bag mode or non-specilized
9034 if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
9035 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9037 if (!ItemCanGoIntoBag(pProto,pBagProto))
9038 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9040 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9042 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9043 if (j==skip_slot)
9044 continue;
9046 Item* pItem2 = GetItemByPos( bag, j );
9048 // ignore move item (this slot will be empty at move)
9049 if (pItem2 == pSrcItem)
9050 pItem2 = NULL;
9052 // if merge skip empty, if !merge skip non-empty
9053 if ((pItem2 != NULL) != merge)
9054 continue;
9056 if (pItem2)
9058 if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9060 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9061 if(need_space > count)
9062 need_space = count;
9064 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9065 if (!newPosition.isContainedIn(dest))
9067 dest.push_back(newPosition);
9068 count -= need_space;
9070 if (count==0)
9071 return EQUIP_ERR_OK;
9075 else
9077 uint32 need_space = pProto->GetMaxStackSize();
9078 if (need_space > count)
9079 need_space = count;
9081 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9082 if (!newPosition.isContainedIn(dest))
9084 dest.push_back(newPosition);
9085 count -= need_space;
9087 if (count==0)
9088 return EQUIP_ERR_OK;
9092 return EQUIP_ERR_OK;
9095 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
9097 for(uint32 j = slot_begin; j < slot_end; ++j)
9099 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9100 if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
9101 continue;
9103 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
9105 // ignore move item (this slot will be empty at move)
9106 if (pItem2==pSrcItem)
9107 pItem2 = NULL;
9109 // if merge skip empty, if !merge skip non-empty
9110 if ((pItem2 != NULL) != merge)
9111 continue;
9113 if (pItem2)
9115 if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9117 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9118 if (need_space > count)
9119 need_space = count;
9120 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9121 if (!newPosition.isContainedIn(dest))
9123 dest.push_back(newPosition);
9124 count -= need_space;
9126 if (count==0)
9127 return EQUIP_ERR_OK;
9131 else
9133 uint32 need_space = pProto->GetMaxStackSize();
9134 if (need_space > count)
9135 need_space = count;
9137 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9138 if (!newPosition.isContainedIn(dest))
9140 dest.push_back(newPosition);
9141 count -= need_space;
9143 if (count==0)
9144 return EQUIP_ERR_OK;
9148 return EQUIP_ERR_OK;
9151 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9153 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9155 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
9156 if (!pProto)
9158 if (no_space_count)
9159 *no_space_count = count;
9160 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9163 if (pItem && pItem->IsBindedNotWith(this))
9165 if (no_space_count)
9166 *no_space_count = count;
9167 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9170 // check count of items (skip for auto move for same player from bank)
9171 uint32 no_similar_count = 0; // can't store this amount similar items
9172 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9173 if (res!=EQUIP_ERR_OK)
9175 if (count==no_similar_count)
9177 if (no_space_count)
9178 *no_space_count = no_similar_count;
9179 return res;
9181 count -= no_similar_count;
9184 // in specific slot
9185 if (bag != NULL_BAG && slot != NULL_SLOT)
9187 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9188 if (res!=EQUIP_ERR_OK)
9190 if (no_space_count)
9191 *no_space_count = count + no_similar_count;
9192 return res;
9195 if (count==0)
9197 if (no_similar_count==0)
9198 return EQUIP_ERR_OK;
9200 if (no_space_count)
9201 *no_space_count = count + no_similar_count;
9202 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9206 // not specific slot or have space for partly store only in specific slot
9208 // in specific bag
9209 if (bag != NULL_BAG)
9211 // search stack in bag for merge to
9212 if (pProto->Stackable != 1)
9214 if (bag == INVENTORY_SLOT_BAG_0) // inventory
9216 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9217 if (res!=EQUIP_ERR_OK)
9219 if (no_space_count)
9220 *no_space_count = count + no_similar_count;
9221 return res;
9224 if (count==0)
9226 if (no_similar_count==0)
9227 return EQUIP_ERR_OK;
9229 if (no_space_count)
9230 *no_space_count = count + no_similar_count;
9231 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9234 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9235 if (res!=EQUIP_ERR_OK)
9237 if (no_space_count)
9238 *no_space_count = count + no_similar_count;
9239 return res;
9242 if (count==0)
9244 if (no_similar_count==0)
9245 return EQUIP_ERR_OK;
9247 if (no_space_count)
9248 *no_space_count = count + no_similar_count;
9249 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9252 else // equipped bag
9254 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9255 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9256 if (res!=EQUIP_ERR_OK)
9257 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9259 if (res!=EQUIP_ERR_OK)
9261 if (no_space_count)
9262 *no_space_count = count + no_similar_count;
9263 return res;
9266 if (count==0)
9268 if (no_similar_count==0)
9269 return EQUIP_ERR_OK;
9271 if (no_space_count)
9272 *no_space_count = count + no_similar_count;
9273 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9278 // search free slot in bag for place to
9279 if(bag == INVENTORY_SLOT_BAG_0) // inventory
9281 // search free slot - keyring case
9282 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9284 uint32 keyringSize = GetMaxKeyringSize();
9285 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9286 if (res!=EQUIP_ERR_OK)
9288 if (no_space_count)
9289 *no_space_count = count + no_similar_count;
9290 return res;
9293 if (count==0)
9295 if (no_similar_count==0)
9296 return EQUIP_ERR_OK;
9298 if (no_space_count)
9299 *no_space_count = count + no_similar_count;
9300 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9303 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9304 if (res!=EQUIP_ERR_OK)
9306 if (no_space_count)
9307 *no_space_count = count + no_similar_count;
9308 return res;
9311 if (count==0)
9313 if (no_similar_count==0)
9314 return EQUIP_ERR_OK;
9316 if (no_space_count)
9317 *no_space_count = count + no_similar_count;
9318 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9321 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9323 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9324 if (res!=EQUIP_ERR_OK)
9326 if (no_space_count)
9327 *no_space_count = count + no_similar_count;
9328 return res;
9331 if (count==0)
9333 if (no_similar_count==0)
9334 return EQUIP_ERR_OK;
9336 if (no_space_count)
9337 *no_space_count = count + no_similar_count;
9338 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9342 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9343 if (res!=EQUIP_ERR_OK)
9345 if (no_space_count)
9346 *no_space_count = count + no_similar_count;
9347 return res;
9350 if (count==0)
9352 if (no_similar_count==0)
9353 return EQUIP_ERR_OK;
9355 if (no_space_count)
9356 *no_space_count = count + no_similar_count;
9357 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9360 else // equipped bag
9362 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9363 if (res!=EQUIP_ERR_OK)
9364 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9366 if (res!=EQUIP_ERR_OK)
9368 if (no_space_count)
9369 *no_space_count = count + no_similar_count;
9370 return res;
9373 if (count==0)
9375 if (no_similar_count==0)
9376 return EQUIP_ERR_OK;
9378 if (no_space_count)
9379 *no_space_count = count + no_similar_count;
9380 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9385 // not specific bag or have space for partly store only in specific bag
9387 // search stack for merge to
9388 if (pProto->Stackable != 1)
9390 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9391 if (res!=EQUIP_ERR_OK)
9393 if (no_space_count)
9394 *no_space_count = count + no_similar_count;
9395 return res;
9398 if (count==0)
9400 if (no_similar_count==0)
9401 return EQUIP_ERR_OK;
9403 if (no_space_count)
9404 *no_space_count = count + no_similar_count;
9405 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9408 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9409 if (res!=EQUIP_ERR_OK)
9411 if (no_space_count)
9412 *no_space_count = count + no_similar_count;
9413 return res;
9416 if (count==0)
9418 if (no_similar_count==0)
9419 return EQUIP_ERR_OK;
9421 if (no_space_count)
9422 *no_space_count = count + no_similar_count;
9423 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9426 if (pProto->BagFamily)
9428 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9430 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9431 if (res!=EQUIP_ERR_OK)
9432 continue;
9434 if (count==0)
9436 if (no_similar_count==0)
9437 return EQUIP_ERR_OK;
9439 if (no_space_count)
9440 *no_space_count = count + no_similar_count;
9441 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9446 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9448 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9449 if (res!=EQUIP_ERR_OK)
9450 continue;
9452 if (count==0)
9454 if (no_similar_count==0)
9455 return EQUIP_ERR_OK;
9457 if (no_space_count)
9458 *no_space_count = count + no_similar_count;
9459 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9464 // search free slot - special bag case
9465 if (pProto->BagFamily)
9467 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9469 uint32 keyringSize = GetMaxKeyringSize();
9470 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9471 if (res!=EQUIP_ERR_OK)
9473 if (no_space_count)
9474 *no_space_count = count + no_similar_count;
9475 return res;
9478 if (count==0)
9480 if (no_similar_count==0)
9481 return EQUIP_ERR_OK;
9483 if (no_space_count)
9484 *no_space_count = count + no_similar_count;
9485 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9488 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9490 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9491 if (res!=EQUIP_ERR_OK)
9493 if (no_space_count)
9494 *no_space_count = count + no_similar_count;
9495 return res;
9498 if (count==0)
9500 if (no_similar_count==0)
9501 return EQUIP_ERR_OK;
9503 if (no_space_count)
9504 *no_space_count = count + no_similar_count;
9505 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9509 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9511 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9512 if (res!=EQUIP_ERR_OK)
9513 continue;
9515 if (count==0)
9517 if (no_similar_count==0)
9518 return EQUIP_ERR_OK;
9520 if (no_space_count)
9521 *no_space_count = count + no_similar_count;
9522 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9527 // search free slot
9528 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9529 if (res!=EQUIP_ERR_OK)
9531 if (no_space_count)
9532 *no_space_count = count + no_similar_count;
9533 return res;
9536 if (count==0)
9538 if (no_similar_count==0)
9539 return EQUIP_ERR_OK;
9541 if (no_space_count)
9542 *no_space_count = count + no_similar_count;
9543 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9546 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9548 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9549 if (res!=EQUIP_ERR_OK)
9550 continue;
9552 if (count==0)
9554 if (no_similar_count==0)
9555 return EQUIP_ERR_OK;
9557 if (no_space_count)
9558 *no_space_count = count + no_similar_count;
9559 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9563 if (no_space_count)
9564 *no_space_count = count + no_similar_count;
9566 return EQUIP_ERR_INVENTORY_FULL;
9569 //////////////////////////////////////////////////////////////////////////
9570 uint8 Player::CanStoreItems( Item **pItems,int count) const
9572 Item *pItem2;
9574 // fill space table
9575 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9576 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9577 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9578 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9580 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9581 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9582 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9583 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9585 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9587 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9589 if (pItem2 && !pItem2->IsInTrade())
9591 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9595 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9597 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9599 if (pItem2 && !pItem2->IsInTrade())
9601 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9605 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9607 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9609 if (pItem2 && !pItem2->IsInTrade())
9611 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9615 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9617 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9619 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9621 pItem2 = GetItemByPos( i, j );
9622 if (pItem2 && !pItem2->IsInTrade())
9624 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9630 // check free space for all items
9631 for (int k = 0; k < count; ++k)
9633 Item *pItem = pItems[k];
9635 // no item
9636 if (!pItem) continue;
9638 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9639 ItemPrototype const *pProto = pItem->GetProto();
9641 // strange item
9642 if( !pProto )
9643 return EQUIP_ERR_ITEM_NOT_FOUND;
9645 // item it 'bind'
9646 if(pItem->IsBindedNotWith(this))
9647 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9649 Bag *pBag;
9650 ItemPrototype const *pBagProto;
9652 // item is 'one item only'
9653 uint8 res = CanTakeMoreSimilarItems(pItem);
9654 if(res != EQUIP_ERR_OK)
9655 return res;
9657 // search stack for merge to
9658 if( pProto->Stackable != 1 )
9660 bool b_found = false;
9662 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9664 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9665 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9667 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9668 b_found = true;
9669 break;
9672 if (b_found) continue;
9674 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9676 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9677 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9679 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9680 b_found = true;
9681 break;
9684 if (b_found) continue;
9686 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9688 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9689 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9691 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9692 b_found = true;
9693 break;
9696 if (b_found) continue;
9698 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9700 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9701 if( pBag )
9703 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9705 pItem2 = GetItemByPos( t, j );
9706 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9708 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9709 b_found = true;
9710 break;
9715 if (b_found) continue;
9718 // special bag case
9719 if( pProto->BagFamily )
9721 bool b_found = false;
9722 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9724 uint32 keyringSize = GetMaxKeyringSize();
9725 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9727 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9729 inv_keys[t-KEYRING_SLOT_START] = 1;
9730 b_found = true;
9731 break;
9736 if (b_found) continue;
9738 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9740 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9742 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9744 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9745 b_found = true;
9746 break;
9751 if (b_found) continue;
9753 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9755 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9756 if( pBag )
9758 pBagProto = pBag->GetProto();
9760 // not plain container check
9761 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9762 ItemCanGoIntoBag(pProto,pBagProto) )
9764 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9766 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9768 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9769 b_found = true;
9770 break;
9776 if (b_found) continue;
9779 // search free slot
9780 bool b_found = false;
9781 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9783 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9785 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9786 b_found = true;
9787 break;
9790 if (b_found) continue;
9792 // search free slot in bags
9793 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9795 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9796 if( pBag )
9798 pBagProto = pBag->GetProto();
9800 // special bag already checked
9801 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9802 continue;
9804 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9806 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9808 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9809 b_found = true;
9810 break;
9816 // no free slot found?
9817 if (!b_found)
9818 return EQUIP_ERR_INVENTORY_FULL;
9821 return EQUIP_ERR_OK;
9824 //////////////////////////////////////////////////////////////////////////
9825 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9827 dest = 0;
9828 Item *pItem = Item::CreateItem( item, 1, this );
9829 if( pItem )
9831 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9832 delete pItem;
9833 return result;
9836 return EQUIP_ERR_ITEM_NOT_FOUND;
9839 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9841 dest = 0;
9842 if( pItem )
9844 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9845 ItemPrototype const *pProto = pItem->GetProto();
9846 if( pProto )
9848 if(pItem->IsBindedNotWith(this))
9849 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9851 // check count of items (skip for auto move for same player from bank)
9852 uint8 res = CanTakeMoreSimilarItems(pItem);
9853 if(res != EQUIP_ERR_OK)
9854 return res;
9856 // check this only in game
9857 if(not_loading)
9859 // May be here should be more stronger checks; STUNNED checked
9860 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9861 if (hasUnitState(UNIT_STAT_STUNNED))
9862 return EQUIP_ERR_YOU_ARE_STUNNED;
9864 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9865 // - combat
9866 // - in-progress arenas
9867 if( !pProto->CanChangeEquipStateInCombat() )
9869 if( isInCombat() )
9870 return EQUIP_ERR_NOT_IN_COMBAT;
9872 if(BattleGround* bg = GetBattleGround())
9873 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9874 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9877 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9878 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9880 if(IsNonMeleeSpellCasted(false))
9881 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9884 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
9885 // 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)
9886 if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
9887 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9889 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9890 if (eslot == NULL_SLOT)
9891 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9893 uint8 msg = CanUseItem(pItem , not_loading);
9894 if (msg != EQUIP_ERR_OK)
9895 return msg;
9896 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
9897 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9899 // if swap ignore item (equipped also)
9900 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9901 return res2;
9903 // check unique-equipped special item classes
9904 if (pProto->Class == ITEM_CLASS_QUIVER)
9906 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9908 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
9910 if (pBag != pItem)
9912 if (ItemPrototype const* pBagProto = pBag->GetProto())
9914 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
9915 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9916 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
9917 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9924 uint32 type = pProto->InventoryType;
9926 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9928 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9930 if (!CanDualWield())
9931 return EQUIP_ERR_CANT_DUAL_WIELD;
9933 else if (type == INVTYPE_2HWEAPON)
9935 if (!CanDualWield() || !CanTitanGrip())
9936 return EQUIP_ERR_CANT_DUAL_WIELD;
9939 if (IsTwoHandUsed())
9940 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9943 // equip two-hand weapon case (with possible unequip 2 items)
9944 if (type == INVTYPE_2HWEAPON)
9946 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9948 if (!CanTitanGrip())
9949 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9951 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9952 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9954 if (!CanTitanGrip())
9956 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9957 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9958 ItemPosCountVec off_dest;
9959 if (offItem && (!not_loading ||
9960 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9961 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
9962 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9965 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9966 return EQUIP_ERR_OK;
9970 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9973 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9975 // Applied only to equipped items and bank bags
9976 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9977 return EQUIP_ERR_OK;
9979 Item* pItem = GetItemByPos(pos);
9981 // Applied only to existed equipped item
9982 if( !pItem )
9983 return EQUIP_ERR_OK;
9985 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9987 ItemPrototype const *pProto = pItem->GetProto();
9988 if( !pProto )
9989 return EQUIP_ERR_ITEM_NOT_FOUND;
9991 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9992 // - combat
9993 // - in-progress arenas
9994 if( !pProto->CanChangeEquipStateInCombat() )
9996 if( isInCombat() )
9997 return EQUIP_ERR_NOT_IN_COMBAT;
9999 if(BattleGround* bg = GetBattleGround())
10000 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
10001 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
10004 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
10005 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
10007 return EQUIP_ERR_OK;
10010 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
10012 if (!pItem)
10013 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10015 if (pItem->m_lootGenerated)
10016 return EQUIP_ERR_ITEM_LOCKED;
10018 uint32 count = pItem->GetCount();
10020 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
10021 ItemPrototype const *pProto = pItem->GetProto();
10022 if (!pProto)
10023 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10025 if (pItem->IsBindedNotWith(this))
10026 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10028 // check count of items (skip for auto move for same player from bank)
10029 uint8 res = CanTakeMoreSimilarItems(pItem);
10030 if (res != EQUIP_ERR_OK)
10031 return res;
10033 // in specific slot
10034 if (bag != NULL_BAG && slot != NULL_SLOT)
10036 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
10038 if (!pItem->IsBag())
10039 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
10041 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
10042 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
10044 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
10045 return cantuse;
10048 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
10049 if (res!=EQUIP_ERR_OK)
10050 return res;
10052 if (count==0)
10053 return EQUIP_ERR_OK;
10056 // not specific slot or have space for partly store only in specific slot
10058 // in specific bag
10059 if( bag != NULL_BAG )
10061 if( pProto->InventoryType == INVTYPE_BAG )
10063 Bag *pBag = (Bag*)pItem;
10064 if( pBag && !pBag->IsEmpty() )
10065 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
10068 // search stack in bag for merge to
10069 if( pProto->Stackable != 1 )
10071 if( bag == INVENTORY_SLOT_BAG_0 )
10073 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10074 if(res!=EQUIP_ERR_OK)
10075 return res;
10077 if(count==0)
10078 return EQUIP_ERR_OK;
10080 else
10082 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
10083 if(res!=EQUIP_ERR_OK)
10084 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
10086 if(res!=EQUIP_ERR_OK)
10087 return res;
10089 if(count==0)
10090 return EQUIP_ERR_OK;
10094 // search free slot in bag
10095 if( bag == INVENTORY_SLOT_BAG_0 )
10097 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10098 if(res!=EQUIP_ERR_OK)
10099 return res;
10101 if(count==0)
10102 return EQUIP_ERR_OK;
10104 else
10106 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
10107 if(res != EQUIP_ERR_OK)
10108 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
10110 if(res != EQUIP_ERR_OK)
10111 return res;
10113 if(count == 0)
10114 return EQUIP_ERR_OK;
10118 // not specific bag or have space for partly store only in specific bag
10120 // search stack for merge to
10121 if( pProto->Stackable != 1 )
10123 // in slots
10124 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10125 if(res != EQUIP_ERR_OK)
10126 return res;
10128 if(count == 0)
10129 return EQUIP_ERR_OK;
10131 // in special bags
10132 if( pProto->BagFamily )
10134 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10136 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10137 if(res!=EQUIP_ERR_OK)
10138 continue;
10140 if(count==0)
10141 return EQUIP_ERR_OK;
10145 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10147 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10148 if(res!=EQUIP_ERR_OK)
10149 continue;
10151 if(count==0)
10152 return EQUIP_ERR_OK;
10156 // search free place in special bag
10157 if( pProto->BagFamily )
10159 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10161 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10162 if(res!=EQUIP_ERR_OK)
10163 continue;
10165 if(count==0)
10166 return EQUIP_ERR_OK;
10170 // search free space
10171 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10172 if(res!=EQUIP_ERR_OK)
10173 return res;
10175 if(count==0)
10176 return EQUIP_ERR_OK;
10178 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10180 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10181 if(res!=EQUIP_ERR_OK)
10182 continue;
10184 if(count==0)
10185 return EQUIP_ERR_OK;
10187 return EQUIP_ERR_BANK_FULL;
10190 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10192 if (pItem)
10194 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10196 if (!isAlive() && not_loading)
10197 return EQUIP_ERR_YOU_ARE_DEAD;
10199 //if (isStunned())
10200 // return EQUIP_ERR_YOU_ARE_STUNNED;
10202 ItemPrototype const *pProto = pItem->GetProto();
10203 if (pProto)
10205 if (pItem->IsBindedNotWith(this))
10206 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10208 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
10209 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10211 if (uint32 item_use_skill = pItem->GetSkill())
10213 if (GetSkillValue(item_use_skill) == 0)
10215 // armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
10216 if (pProto->Class != ITEM_CLASS_ARMOR)
10217 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10219 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : NULL;
10220 if (!ssd)
10221 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10223 bool allowScaleSkill = false;
10224 for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i)
10226 SkillLineAbilityEntry const *skillInfo = sSkillLineAbilityStore.LookupEntry(i);
10227 if (!skillInfo)
10228 continue;
10230 if (skillInfo->skillId != item_use_skill)
10231 continue;
10233 // can't learn
10234 if (skillInfo->classmask && (skillInfo->classmask & getClassMask()) == 0)
10235 continue;
10237 if (skillInfo->racemask && (skillInfo->racemask & getRaceMask()) == 0)
10238 continue;
10240 allowScaleSkill = true;
10241 break;
10244 if (!allowScaleSkill)
10245 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10249 if (pProto->RequiredSkill != 0)
10251 if (GetSkillValue( pProto->RequiredSkill ) == 0)
10252 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10254 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
10255 return EQUIP_ERR_CANT_EQUIP_SKILL;
10258 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
10259 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10261 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
10262 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10264 if (getLevel() < pProto->RequiredLevel)
10265 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10267 return EQUIP_ERR_OK;
10270 return EQUIP_ERR_ITEM_NOT_FOUND;
10273 bool Player::CanUseItem( ItemPrototype const *pProto )
10275 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10277 if( pProto )
10279 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10280 return false;
10281 if( pProto->RequiredSkill != 0 )
10283 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10284 return false;
10285 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10286 return false;
10288 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10289 return false;
10290 if( getLevel() < pProto->RequiredLevel )
10291 return false;
10292 return true;
10294 return false;
10297 uint8 Player::CanUseAmmo( uint32 item ) const
10299 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10300 if( !isAlive() )
10301 return EQUIP_ERR_YOU_ARE_DEAD;
10302 //if( isStunned() )
10303 // return EQUIP_ERR_YOU_ARE_STUNNED;
10304 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
10305 if( pProto )
10307 if( pProto->InventoryType!= INVTYPE_AMMO )
10308 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10309 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10310 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10311 if( pProto->RequiredSkill != 0 )
10313 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10314 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10315 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10316 return EQUIP_ERR_CANT_EQUIP_SKILL;
10318 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10319 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10320 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10321 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10323 if( getLevel() < pProto->RequiredLevel )
10324 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10326 // Requires No Ammo
10327 if(GetDummyAura(46699))
10328 return EQUIP_ERR_BAG_FULL6;
10330 return EQUIP_ERR_OK;
10332 return EQUIP_ERR_ITEM_NOT_FOUND;
10335 void Player::SetAmmo( uint32 item )
10337 if(!item)
10338 return;
10340 // already set
10341 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10342 return;
10344 // check ammo
10345 if(item)
10347 uint8 msg = CanUseAmmo( item );
10348 if( msg != EQUIP_ERR_OK )
10350 SendEquipError( msg, NULL, NULL );
10351 return;
10355 SetUInt32Value(PLAYER_AMMO_ID, item);
10357 _ApplyAmmoBonuses();
10360 void Player::RemoveAmmo()
10362 SetUInt32Value(PLAYER_AMMO_ID, 0);
10364 m_ammoDPS = 0.0f;
10366 if(CanModifyStats())
10367 UpdateDamagePhysical(RANGED_ATTACK);
10370 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10371 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10373 uint32 count = 0;
10374 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10375 count += itr->count;
10377 Item *pItem = Item::CreateItem( item, count, this );
10378 if( pItem )
10380 ItemAddedQuestCheck( item, count );
10381 if(randomPropertyId)
10382 pItem->SetItemRandomProperties(randomPropertyId);
10383 pItem = StoreItem( dest, pItem, update );
10385 return pItem;
10388 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10390 if( !pItem )
10391 return NULL;
10393 Item* lastItem = pItem;
10394 uint32 entry = pItem->GetEntry();
10395 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10397 uint16 pos = itr->pos;
10398 uint32 count = itr->count;
10400 ++itr;
10402 if(itr == dest.end())
10404 lastItem = _StoreItem(pos,pItem,count,false,update);
10405 break;
10408 lastItem = _StoreItem(pos,pItem,count,true,update);
10410 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10411 return lastItem;
10414 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10415 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10417 if( !pItem )
10418 return NULL;
10420 uint8 bag = pos >> 8;
10421 uint8 slot = pos & 255;
10423 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10425 Item *pItem2 = GetItemByPos( bag, slot );
10427 if (!pItem2)
10429 if (clone)
10430 pItem = pItem->CloneItem(count, this);
10431 else
10432 pItem->SetCount(count);
10434 if (!pItem)
10435 return NULL;
10437 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10438 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10439 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10440 pItem->SetBinding( true );
10442 if (bag == INVENTORY_SLOT_BAG_0)
10444 m_items[slot] = pItem;
10445 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10446 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10447 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10449 pItem->SetSlot( slot );
10450 pItem->SetContainer( NULL );
10452 // need update known currency
10453 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10454 UpdateKnownCurrencies(pItem->GetEntry(), true);
10456 if (IsInWorld() && update)
10458 pItem->AddToWorld();
10459 pItem->SendCreateUpdateToPlayer( this );
10462 pItem->SetState(ITEM_CHANGED, this);
10464 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10466 pBag->StoreItem( slot, pItem, update );
10467 if( IsInWorld() && update )
10469 pItem->AddToWorld();
10470 pItem->SendCreateUpdateToPlayer( this );
10472 pItem->SetState(ITEM_CHANGED, this);
10473 pBag->SetState(ITEM_CHANGED, this);
10476 AddEnchantmentDurations(pItem);
10477 AddItemDurations(pItem);
10479 return pItem;
10481 else
10483 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10484 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10485 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10486 pItem2->SetBinding( true );
10488 pItem2->SetCount( pItem2->GetCount() + count );
10489 if (IsInWorld() && update)
10490 pItem2->SendCreateUpdateToPlayer( this );
10492 if (!clone)
10494 // delete item (it not in any slot currently)
10495 if (IsInWorld() && update)
10497 pItem->RemoveFromWorld();
10498 pItem->DestroyForPlayer( this );
10501 RemoveEnchantmentDurations(pItem);
10502 RemoveItemDurations(pItem);
10504 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10505 pItem->SetState(ITEM_REMOVED, this);
10508 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10509 AddEnchantmentDurations(pItem2);
10511 pItem2->SetState(ITEM_CHANGED, this);
10513 return pItem2;
10517 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10519 if (Item *pItem = Item::CreateItem( item, 1, this ))
10521 ItemAddedQuestCheck( item, 1 );
10522 return EquipItem( pos, pItem, update );
10525 return NULL;
10528 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10530 AddEnchantmentDurations(pItem);
10531 AddItemDurations(pItem);
10533 uint8 bag = pos >> 8;
10534 uint8 slot = pos & 255;
10536 Item *pItem2 = GetItemByPos( bag, slot );
10538 if( !pItem2 )
10540 VisualizeItem( slot, pItem);
10542 if(isAlive())
10544 ItemPrototype const *pProto = pItem->GetProto();
10546 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10547 if(pProto && pProto->ItemSet)
10548 AddItemsSetItem(this, pItem);
10550 _ApplyItemMods(pItem, slot, true);
10552 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10554 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10556 if (getClass() == CLASS_ROGUE)
10557 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10559 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10561 if (!spellProto)
10562 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10563 else
10565 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10567 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10568 data << uint64(GetGUID());
10569 data << uint8(1);
10570 data << uint32(cooldownSpell);
10571 data << uint32(0);
10572 GetSession()->SendPacket(&data);
10577 if( IsInWorld() && update )
10579 pItem->AddToWorld();
10580 pItem->SendCreateUpdateToPlayer( this );
10583 ApplyEquipCooldown(pItem);
10585 if( slot == EQUIPMENT_SLOT_MAINHAND )
10587 UpdateExpertise(BASE_ATTACK);
10588 UpdateArmorPenetration();
10590 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10592 UpdateExpertise(OFF_ATTACK);
10593 UpdateArmorPenetration();
10596 else
10598 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10599 if( IsInWorld() && update )
10600 pItem2->SendCreateUpdateToPlayer( this );
10602 // delete item (it not in any slot currently)
10603 //pItem->DeleteFromDB();
10604 if( IsInWorld() && update )
10606 pItem->RemoveFromWorld();
10607 pItem->DestroyForPlayer( this );
10610 RemoveEnchantmentDurations(pItem);
10611 RemoveItemDurations(pItem);
10613 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10614 pItem->SetState(ITEM_REMOVED, this);
10615 pItem2->SetState(ITEM_CHANGED, this);
10617 ApplyEquipCooldown(pItem2);
10619 return pItem2;
10622 // only for full equip instead adding to stack
10623 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10625 return pItem;
10628 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10630 if( pItem )
10632 AddEnchantmentDurations(pItem);
10633 AddItemDurations(pItem);
10635 uint8 slot = pos & 255;
10636 VisualizeItem( slot, pItem);
10638 if( IsInWorld() )
10640 pItem->AddToWorld();
10641 pItem->SendCreateUpdateToPlayer( this );
10644 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10648 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10650 if(pItem)
10652 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10653 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10654 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10656 else
10658 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10659 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10663 void Player::VisualizeItem( uint8 slot, Item *pItem)
10665 if(!pItem)
10666 return;
10668 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10669 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10670 pItem->SetBinding( true );
10672 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10674 m_items[slot] = pItem;
10675 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10676 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10677 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10678 pItem->SetSlot( slot );
10679 pItem->SetContainer( NULL );
10681 if( slot < EQUIPMENT_SLOT_END )
10682 SetVisibleItemSlot(slot, pItem);
10684 pItem->SetState(ITEM_CHANGED, this);
10687 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10689 // note: removeitem does not actually change the item
10690 // it only takes the item out of storage temporarily
10691 // note2: if removeitem is to be used for delinking
10692 // the item must be removed from the player's updatequeue
10694 Item *pItem = GetItemByPos( bag, slot );
10695 if( pItem )
10697 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10699 RemoveEnchantmentDurations(pItem);
10700 RemoveItemDurations(pItem);
10702 if( bag == INVENTORY_SLOT_BAG_0 )
10704 if ( slot < INVENTORY_SLOT_BAG_END )
10706 ItemPrototype const *pProto = pItem->GetProto();
10707 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10709 if(pProto && pProto->ItemSet)
10710 RemoveItemsSetItem(this, pProto);
10712 _ApplyItemMods(pItem, slot, false);
10714 // remove item dependent auras and casts (only weapon and armor slots)
10715 if(slot < EQUIPMENT_SLOT_END)
10717 RemoveItemDependentAurasAndCasts(pItem);
10719 // remove held enchantments, update expertise
10720 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10722 if (pItem->GetItemSuffixFactor())
10724 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10725 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10727 else
10729 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10730 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10733 UpdateExpertise(BASE_ATTACK);
10734 UpdateArmorPenetration();
10736 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10738 UpdateExpertise(OFF_ATTACK);
10739 UpdateArmorPenetration();
10743 // need update known currency
10744 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10745 UpdateKnownCurrencies(pItem->GetEntry(), false);
10747 m_items[slot] = NULL;
10748 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10750 if ( slot < EQUIPMENT_SLOT_END )
10751 SetVisibleItemSlot(slot, NULL);
10753 else
10755 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10756 if( pBag )
10757 pBag->RemoveItem(slot, update);
10759 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10760 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10761 pItem->SetSlot( NULL_SLOT );
10762 if( IsInWorld() && update )
10763 pItem->SendCreateUpdateToPlayer( this );
10767 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10768 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10770 if(Item* it = GetItemByPos(bag,slot))
10772 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10773 RemoveItem(bag, slot, update);
10774 it->RemoveFromUpdateQueueOf(this);
10775 if(it->IsInWorld())
10777 it->RemoveFromWorld();
10778 it->DestroyForPlayer( this );
10783 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10784 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10786 // update quest counters
10787 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10789 // store item
10790 Item* pLastItem = StoreItem(dest, pItem, update);
10792 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10793 if(pLastItem == pItem)
10795 // update owner for last item (this can be original item with wrong owner
10796 if(pLastItem->GetOwnerGUID() != GetGUID())
10797 pLastItem->SetOwnerGUID(GetGUID());
10799 // if this original item then it need create record in inventory
10800 // in case trade we already have item in other player inventory
10801 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10805 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10807 Item *pItem = GetItemByPos( bag, slot );
10808 if( pItem )
10810 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10812 // start from destroy contained items (only equipped bag can have its)
10813 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10815 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10816 DestroyItem(slot, i, update);
10819 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10820 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10822 RemoveEnchantmentDurations(pItem);
10823 RemoveItemDurations(pItem);
10825 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10827 if( bag == INVENTORY_SLOT_BAG_0 )
10829 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10831 // equipment and equipped bags can have applied bonuses
10832 if ( slot < INVENTORY_SLOT_BAG_END )
10834 ItemPrototype const *pProto = pItem->GetProto();
10836 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10837 if(pProto && pProto->ItemSet)
10838 RemoveItemsSetItem(this, pProto);
10840 _ApplyItemMods(pItem, slot, false);
10843 if ( slot < EQUIPMENT_SLOT_END )
10845 // remove item dependent auras and casts (only weapon and armor slots)
10846 RemoveItemDependentAurasAndCasts(pItem);
10848 // update expertise
10849 if( slot == EQUIPMENT_SLOT_MAINHAND )
10851 UpdateExpertise(BASE_ATTACK);
10852 UpdateArmorPenetration();
10854 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10856 UpdateExpertise(OFF_ATTACK);
10857 UpdateArmorPenetration();
10860 // equipment visual show
10861 SetVisibleItemSlot(slot, NULL);
10863 // need update known currency
10864 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10865 UpdateKnownCurrencies(pItem->GetEntry(), false);
10867 m_items[slot] = NULL;
10869 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10870 pBag->RemoveItem(slot, update);
10872 if( IsInWorld() && update )
10874 pItem->RemoveFromWorld();
10875 pItem->DestroyForPlayer(this);
10878 //pItem->SetOwnerGUID(0);
10879 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10880 pItem->SetSlot( NULL_SLOT );
10881 pItem->SetState(ITEM_REMOVED, this);
10885 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10887 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10888 uint32 remcount = 0;
10890 // in inventory
10891 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10893 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10895 if (pItem->GetEntry() == item)
10897 if (pItem->GetCount() + remcount <= count)
10899 // all items in inventory can unequipped
10900 remcount += pItem->GetCount();
10901 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10903 if (remcount >= count)
10904 return;
10906 else
10908 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10909 pItem->SetCount( pItem->GetCount() - count + remcount );
10910 if (IsInWorld() & update)
10911 pItem->SendCreateUpdateToPlayer( this );
10912 pItem->SetState(ITEM_CHANGED, this);
10913 return;
10919 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10921 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10923 if (pItem->GetEntry() == item)
10925 if (pItem->GetCount() + remcount <= count)
10927 // all keys can be unequipped
10928 remcount += pItem->GetCount();
10929 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10931 if (remcount >= count)
10932 return;
10934 else
10936 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10937 pItem->SetCount( pItem->GetCount() - count + remcount );
10938 if (IsInWorld() & update)
10939 pItem->SendCreateUpdateToPlayer( this );
10940 pItem->SetState(ITEM_CHANGED, this);
10941 return;
10947 // in inventory bags
10948 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10950 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10952 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10954 if(Item* pItem = pBag->GetItemByPos(j))
10956 if (pItem->GetEntry() == item)
10958 // all items in bags can be unequipped
10959 if (pItem->GetCount() + remcount <= count)
10961 remcount += pItem->GetCount();
10962 DestroyItem( i, j, update );
10964 if (remcount >= count)
10965 return;
10967 else
10969 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10970 pItem->SetCount( pItem->GetCount() - count + remcount );
10971 if (IsInWorld() && update)
10972 pItem->SendCreateUpdateToPlayer( this );
10973 pItem->SetState(ITEM_CHANGED, this);
10974 return;
10982 // in equipment and bag list
10983 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10985 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10987 if (pItem && pItem->GetEntry() == item)
10989 if (pItem->GetCount() + remcount <= count)
10991 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
10993 remcount += pItem->GetCount();
10994 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10996 if (remcount >= count)
10997 return;
11000 else
11002 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11003 pItem->SetCount( pItem->GetCount() - count + remcount );
11004 if (IsInWorld() & update)
11005 pItem->SendCreateUpdateToPlayer( this );
11006 pItem->SetState(ITEM_CHANGED, this);
11007 return;
11014 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
11016 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
11018 // in inventory
11019 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11020 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11021 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11022 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11024 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
11025 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11026 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11027 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11029 // in inventory bags
11030 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11031 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11032 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11033 if (Item* pItem = pBag->GetItemByPos(j))
11034 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11035 DestroyItem(i, j, update);
11037 // in equipment and bag list
11038 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11039 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11040 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11041 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11044 void Player::DestroyConjuredItems( bool update )
11046 // used when entering arena
11047 // destroys all conjured items
11048 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
11050 // in inventory
11051 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11052 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11053 if (pItem->IsConjuredConsumable())
11054 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11056 // in inventory bags
11057 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11058 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11059 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11060 if (Item* pItem = pBag->GetItemByPos(j))
11061 if (pItem->IsConjuredConsumable())
11062 DestroyItem( i, j, update);
11064 // in equipment and bag list
11065 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11066 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11067 if (pItem->IsConjuredConsumable())
11068 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11071 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
11073 if(!pItem)
11074 return;
11076 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
11078 if( pItem->GetCount() <= count )
11080 count -= pItem->GetCount();
11082 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
11084 else
11086 ItemRemovedQuestCheck( pItem->GetEntry(), count);
11087 pItem->SetCount( pItem->GetCount() - count );
11088 count = 0;
11089 if( IsInWorld() & update )
11090 pItem->SendCreateUpdateToPlayer( this );
11091 pItem->SetState(ITEM_CHANGED, this);
11095 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
11097 uint8 srcbag = src >> 8;
11098 uint8 srcslot = src & 255;
11100 uint8 dstbag = dst >> 8;
11101 uint8 dstslot = dst & 255;
11103 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11104 if( !pSrcItem )
11106 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11107 return;
11110 // not let split all items (can be only at cheating)
11111 if(pSrcItem->GetCount() == count)
11113 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11114 return;
11117 // not let split more existed items (can be only at cheating)
11118 if(pSrcItem->GetCount() < count)
11120 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
11121 return;
11124 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11126 //best error message found for attempting to split while looting
11127 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11128 return;
11131 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11132 Item *pNewItem = pSrcItem->CloneItem( count, this );
11133 if( !pNewItem )
11135 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11136 return;
11139 if( IsInventoryPos( dst ) )
11141 // change item amount before check (for unique max count check)
11142 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11144 ItemPosCountVec dest;
11145 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11146 if( msg != EQUIP_ERR_OK )
11148 delete pNewItem;
11149 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11150 SendEquipError( msg, pSrcItem, NULL );
11151 return;
11154 if( IsInWorld() )
11155 pSrcItem->SendCreateUpdateToPlayer( this );
11156 pSrcItem->SetState(ITEM_CHANGED, this);
11157 StoreItem( dest, pNewItem, true);
11159 else if( IsBankPos ( dst ) )
11161 // change item amount before check (for unique max count check)
11162 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11164 ItemPosCountVec dest;
11165 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11166 if( msg != EQUIP_ERR_OK )
11168 delete pNewItem;
11169 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11170 SendEquipError( msg, pSrcItem, NULL );
11171 return;
11174 if( IsInWorld() )
11175 pSrcItem->SendCreateUpdateToPlayer( this );
11176 pSrcItem->SetState(ITEM_CHANGED, this);
11177 BankItem( dest, pNewItem, true);
11179 else if( IsEquipmentPos ( dst ) )
11181 // change item amount before check (for unique max count check), provide space for splitted items
11182 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11184 uint16 dest;
11185 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11186 if( msg != EQUIP_ERR_OK )
11188 delete pNewItem;
11189 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11190 SendEquipError( msg, pSrcItem, NULL );
11191 return;
11194 if( IsInWorld() )
11195 pSrcItem->SendCreateUpdateToPlayer( this );
11196 pSrcItem->SetState(ITEM_CHANGED, this);
11197 EquipItem( dest, pNewItem, true);
11198 AutoUnequipOffhandIfNeed();
11202 void Player::SwapItem( uint16 src, uint16 dst )
11204 uint8 srcbag = src >> 8;
11205 uint8 srcslot = src & 255;
11207 uint8 dstbag = dst >> 8;
11208 uint8 dstslot = dst & 255;
11210 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11211 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11213 if (!pSrcItem)
11214 return;
11216 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11218 if (!isAlive())
11220 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11221 return;
11224 // SRC checks
11226 if (pSrcItem->m_lootGenerated) // prevent swap looting item
11228 //best error message found for attempting to swap while looting
11229 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11230 return;
11233 // check unequip potability for equipped items and bank bags
11234 if (IsEquipmentPos(src) || IsBagPos(src))
11236 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11237 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty()));
11238 if (msg != EQUIP_ERR_OK)
11240 SendEquipError( msg, pSrcItem, pDstItem );
11241 return;
11245 // prevent put equipped/bank bag in self
11246 if (IsBagPos(src) && srcslot == dstbag)
11248 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11249 return;
11252 // prevent put equipped/bank bag in self
11253 if (IsBagPos(dst) && dstslot == srcbag)
11255 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pDstItem, pSrcItem );
11256 return;
11259 // DST checks
11261 if (pDstItem)
11263 if(pDstItem->m_lootGenerated) // prevent swap looting item
11265 //best error message found for attempting to swap while looting
11266 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11267 return;
11270 // check unequip potability for equipped items and bank bags
11271 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11273 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11274 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty()));
11275 if(msg != EQUIP_ERR_OK)
11277 SendEquipError( msg, pSrcItem, pDstItem );
11278 return;
11283 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11284 // or swap empty bag with another empty or not empty bag (with items exchange)
11286 // Move case
11287 if( !pDstItem )
11289 if( IsInventoryPos( dst ) )
11291 ItemPosCountVec dest;
11292 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11293 if( msg != EQUIP_ERR_OK )
11295 SendEquipError( msg, pSrcItem, NULL );
11296 return;
11299 RemoveItem(srcbag, srcslot, true);
11300 StoreItem( dest, pSrcItem, true);
11302 else if( IsBankPos ( dst ) )
11304 ItemPosCountVec dest;
11305 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11306 if( msg != EQUIP_ERR_OK )
11308 SendEquipError( msg, pSrcItem, NULL );
11309 return;
11312 RemoveItem(srcbag, srcslot, true);
11313 BankItem( dest, pSrcItem, true);
11315 else if( IsEquipmentPos ( dst ) )
11317 uint16 dest;
11318 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11319 if( msg != EQUIP_ERR_OK )
11321 SendEquipError( msg, pSrcItem, NULL );
11322 return;
11325 RemoveItem(srcbag, srcslot, true);
11326 EquipItem(dest, pSrcItem, true);
11327 AutoUnequipOffhandIfNeed();
11330 return;
11333 // attempt merge to / fill target item
11334 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11336 uint8 msg;
11337 ItemPosCountVec sDest;
11338 uint16 eDest;
11339 if( IsInventoryPos( dst ) )
11340 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11341 else if( IsBankPos ( dst ) )
11342 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11343 else if( IsEquipmentPos ( dst ) )
11344 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11345 else
11346 return;
11348 // can be merge/fill
11349 if(msg == EQUIP_ERR_OK)
11351 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11353 RemoveItem(srcbag, srcslot, true);
11355 if( IsInventoryPos( dst ) )
11356 StoreItem( sDest, pSrcItem, true);
11357 else if( IsBankPos ( dst ) )
11358 BankItem( sDest, pSrcItem, true);
11359 else if( IsEquipmentPos ( dst ) )
11361 EquipItem( eDest, pSrcItem, true);
11362 AutoUnequipOffhandIfNeed();
11365 else
11367 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11368 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11369 pSrcItem->SetState(ITEM_CHANGED, this);
11370 pDstItem->SetState(ITEM_CHANGED, this);
11371 if( IsInWorld() )
11373 pSrcItem->SendCreateUpdateToPlayer( this );
11374 pDstItem->SendCreateUpdateToPlayer( this );
11377 return;
11381 // impossible merge/fill, do real swap
11382 uint8 msg;
11384 // check src->dest move possibility
11385 ItemPosCountVec sDest;
11386 uint16 eDest = 0;
11387 if( IsInventoryPos( dst ) )
11388 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11389 else if( IsBankPos( dst ) )
11390 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11391 else if( IsEquipmentPos( dst ) )
11393 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11394 if( msg == EQUIP_ERR_OK )
11395 msg = CanUnequipItem( eDest, true );
11398 if( msg != EQUIP_ERR_OK )
11400 SendEquipError( msg, pSrcItem, pDstItem );
11401 return;
11404 // check dest->src move possibility
11405 ItemPosCountVec sDest2;
11406 uint16 eDest2 = 0;
11407 if( IsInventoryPos( src ) )
11408 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11409 else if( IsBankPos( src ) )
11410 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11411 else if( IsEquipmentPos( src ) )
11413 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11414 if( msg == EQUIP_ERR_OK )
11415 msg = CanUnequipItem( eDest2, true);
11418 if( msg != EQUIP_ERR_OK )
11420 SendEquipError( msg, pDstItem, pSrcItem );
11421 return;
11424 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11425 if(pSrcItem->IsBag() && pDstItem->IsBag())
11427 Bag* emptyBag = NULL;
11428 Bag* fullBag = NULL;
11429 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11431 emptyBag = (Bag*)pSrcItem;
11432 fullBag = (Bag*)pDstItem;
11434 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11436 emptyBag = (Bag*)pDstItem;
11437 fullBag = (Bag*)pSrcItem;
11440 // bag swap (with items exchange) case
11441 if(emptyBag && fullBag)
11443 ItemPrototype const* emotyProto = emptyBag->GetProto();
11445 uint32 count = 0;
11447 for(int i=0; i < fullBag->GetBagSize(); ++i)
11449 Item *bagItem = fullBag->GetItemByPos(i);
11450 if (!bagItem)
11451 continue;
11453 ItemPrototype const* bagItemProto = bagItem->GetProto();
11454 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11456 // one from items not go to empty target bag
11457 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11458 return;
11461 ++count;
11465 if (count > emptyBag->GetBagSize())
11467 // too small targeted bag
11468 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11469 return;
11472 // Items swap
11473 count = 0; // will pos in new bag
11474 for(int i = 0; i< fullBag->GetBagSize(); ++i)
11476 Item *bagItem = fullBag->GetItemByPos(i);
11477 if (!bagItem)
11478 continue;
11480 fullBag->RemoveItem(i, true);
11481 emptyBag->StoreItem(count, bagItem, true);
11482 bagItem->SetState(ITEM_CHANGED, this);
11484 ++count;
11489 // now do moves, remove...
11490 RemoveItem(dstbag, dstslot, false);
11491 RemoveItem(srcbag, srcslot, false);
11493 // add to dest
11494 if (IsInventoryPos(dst))
11495 StoreItem(sDest, pSrcItem, true);
11496 else if (IsBankPos(dst))
11497 BankItem(sDest, pSrcItem, true);
11498 else if (IsEquipmentPos(dst))
11499 EquipItem(eDest, pSrcItem, true);
11501 // add to src
11502 if (IsInventoryPos(src))
11503 StoreItem(sDest2, pDstItem, true);
11504 else if (IsBankPos(src))
11505 BankItem(sDest2, pDstItem, true);
11506 else if (IsEquipmentPos(src))
11507 EquipItem(eDest2, pDstItem, true);
11509 AutoUnequipOffhandIfNeed();
11512 void Player::AddItemToBuyBackSlot( Item *pItem )
11514 if (pItem)
11516 uint32 slot = m_currentBuybackSlot;
11517 // if current back slot non-empty search oldest or free
11518 if (m_items[slot])
11520 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11521 uint32 oldest_slot = BUYBACK_SLOT_START;
11523 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11525 // found empty
11526 if (!m_items[i])
11528 slot = i;
11529 break;
11532 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11534 if (oldest_time > i_time)
11536 oldest_time = i_time;
11537 oldest_slot = i;
11541 // find oldest
11542 slot = oldest_slot;
11545 RemoveItemFromBuyBackSlot( slot, true );
11546 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11548 m_items[slot] = pItem;
11549 time_t base = time(NULL);
11550 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11551 uint32 eslot = slot - BUYBACK_SLOT_START;
11553 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11554 if (ItemPrototype const *pProto = pItem->GetProto())
11555 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11556 else
11557 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11558 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11560 // move to next (for non filled list is move most optimized choice)
11561 if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11562 ++m_currentBuybackSlot;
11566 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11568 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11569 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11570 return m_items[slot];
11571 return NULL;
11574 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11576 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11577 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11579 Item *pItem = m_items[slot];
11580 if (pItem)
11582 pItem->RemoveFromWorld();
11583 if(del) pItem->SetState(ITEM_REMOVED, this);
11586 m_items[slot] = NULL;
11588 uint32 eslot = slot - BUYBACK_SLOT_START;
11589 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11590 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11591 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11593 // if current backslot is filled set to now free slot
11594 if (m_items[m_currentBuybackSlot])
11595 m_currentBuybackSlot = slot;
11599 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11601 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11602 WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, 1+8+8+1);
11603 data << uint8(msg);
11605 if (msg != EQUIP_ERR_OK)
11607 data << uint64(pItem ? pItem->GetGUID() : 0);
11608 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11609 data << uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2
11611 switch(msg)
11613 case EQUIP_ERR_CANT_EQUIP_LEVEL_I:
11614 case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW:
11616 ItemPrototype const* proto = pItem ? pItem->GetProto() : NULL;
11617 data << uint32(proto ? proto->RequiredLevel : 0);
11618 } break;
11619 case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM: // no idea about this one...
11621 data << uint64(0);
11622 data << uint32(0);
11623 data << uint64(0);
11624 } break;
11625 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS:
11626 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS:
11627 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS:
11629 ItemPrototype const* proto = pItem ? pItem->GetProto() : NULL;
11630 data << uint32(proto ? proto->ItemLimitCategory : 0);
11631 } break;
11632 default:
11633 break;
11636 GetSession()->SendPacket(&data);
11639 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11641 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11642 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11643 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11644 data << uint32(item);
11645 if (param > 0)
11646 data << uint32(param);
11647 data << uint8(msg);
11648 GetSession()->SendPacket(&data);
11651 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11653 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11654 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11655 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11656 data << uint64(guid);
11657 if (param > 0)
11658 data << uint32(param);
11659 data << uint8(msg);
11660 GetSession()->SendPacket(&data);
11663 void Player::ClearTrade()
11665 tradeGold = 0;
11666 acceptTrade = false;
11667 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11668 tradeItems[i] = NULL_SLOT;
11671 void Player::TradeCancel(bool sendback)
11673 if (pTrader)
11675 // send yellow "Trade canceled" message to both traders
11676 WorldSession* ws;
11677 ws = GetSession();
11678 if (sendback)
11679 ws->SendCancelTrade();
11680 ws = pTrader->GetSession();
11681 if (!ws->PlayerLogout())
11682 ws->SendCancelTrade();
11684 // cleanup
11685 ClearTrade();
11686 pTrader->ClearTrade();
11687 // prevent loss of reference
11688 pTrader->pTrader = NULL;
11689 pTrader = NULL;
11693 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11695 if (m_itemDuration.empty())
11696 return;
11698 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11700 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11702 Item* item = *itr;
11703 ++itr; // current element can be erased in UpdateDuration
11705 if ((realtimeonly && item->GetProto()->Duration < 0) || !realtimeonly)
11706 item->UpdateDuration(this,time);
11710 void Player::UpdateEnchantTime(uint32 time)
11712 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11714 assert(itr->item);
11715 next = itr;
11716 if (!itr->item->GetEnchantmentId(itr->slot))
11718 next = m_enchantDuration.erase(itr);
11720 else if (itr->leftduration <= time)
11722 ApplyEnchantment(itr->item, itr->slot, false, false);
11723 itr->item->ClearEnchantment(itr->slot);
11724 next = m_enchantDuration.erase(itr);
11726 else if (itr->leftduration > time)
11728 itr->leftduration -= time;
11729 ++next;
11734 void Player::AddEnchantmentDurations(Item *item)
11736 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11738 if (!item->GetEnchantmentId(EnchantmentSlot(x)))
11739 continue;
11741 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11742 if (duration > 0)
11743 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11747 void Player::RemoveEnchantmentDurations(Item *item)
11749 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11751 if (itr->item == item)
11753 // save duration in item
11754 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11755 itr = m_enchantDuration.erase(itr);
11757 else
11758 ++itr;
11762 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11764 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11765 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11767 next = itr;
11768 if (itr->slot == slot)
11770 if (itr->item && itr->item->GetEnchantmentId(slot))
11772 // remove from stats
11773 ApplyEnchantment(itr->item, slot, false, false);
11774 // remove visual
11775 itr->item->ClearEnchantment(slot);
11777 // remove from update list
11778 next = m_enchantDuration.erase(itr);
11780 else
11781 ++next;
11784 // remove enchants from inventory items
11785 // NOTE: no need to remove these from stats, since these aren't equipped
11786 // in inventory
11787 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11788 if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
11789 if (pItem->GetEnchantmentId(slot))
11790 pItem->ClearEnchantment(slot);
11792 // in inventory bags
11793 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11794 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11795 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11796 if (Item* pItem = pBag->GetItemByPos(j))
11797 if (pItem->GetEnchantmentId(slot))
11798 pItem->ClearEnchantment(slot);
11801 // duration == 0 will remove item enchant
11802 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11804 if (!item)
11805 return;
11807 if (slot >= MAX_ENCHANTMENT_SLOT)
11808 return;
11810 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11812 if (itr->item == item && itr->slot == slot)
11814 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11815 m_enchantDuration.erase(itr);
11816 break;
11819 if (item && duration > 0 )
11821 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11822 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11826 void Player::ApplyEnchantment(Item *item,bool apply)
11828 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11829 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11832 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11834 if (!item)
11835 return;
11837 if (!item->IsEquipped())
11838 return;
11840 if (slot >= MAX_ENCHANTMENT_SLOT)
11841 return;
11843 uint32 enchant_id = item->GetEnchantmentId(slot);
11844 if (!enchant_id)
11845 return;
11847 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11848 if (!pEnchant)
11849 return;
11851 if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11852 return;
11854 if (!item->IsBroken())
11856 for (int s = 0; s < 3; ++s)
11858 uint32 enchant_display_type = pEnchant->type[s];
11859 uint32 enchant_amount = pEnchant->amount[s];
11860 uint32 enchant_spell_id = pEnchant->spellid[s];
11862 switch(enchant_display_type)
11864 case ITEM_ENCHANTMENT_TYPE_NONE:
11865 break;
11866 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11867 // processed in Player::CastItemCombatSpell
11868 break;
11869 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11870 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11871 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11872 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11873 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11874 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11875 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11876 break;
11877 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11878 if (enchant_spell_id)
11880 if (apply)
11882 int32 basepoints = 0;
11883 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11884 if (item->GetItemRandomPropertyId())
11886 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11887 if (item_rand)
11889 // Search enchant_amount
11890 for (int k = 0; k < 3; ++k)
11892 if(item_rand->enchant_id[k] == enchant_id)
11894 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11895 break;
11900 // Cast custom spell vs all equal basepoints getted from enchant_amount
11901 if (basepoints)
11902 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11903 else
11904 CastSpell(this, enchant_spell_id, true, item);
11906 else
11907 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11909 break;
11910 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11911 if (!enchant_amount)
11913 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11914 if(item_rand)
11916 for (int k = 0; k < 3; ++k)
11918 if(item_rand->enchant_id[k] == enchant_id)
11920 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11921 break;
11927 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11928 break;
11929 case ITEM_ENCHANTMENT_TYPE_STAT:
11931 if (!enchant_amount)
11933 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11934 if(item_rand_suffix)
11936 for (int k = 0; k < 3; ++k)
11938 if(item_rand_suffix->enchant_id[k] == enchant_id)
11940 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11941 break;
11947 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11948 switch (enchant_spell_id)
11950 case ITEM_MOD_MANA:
11951 sLog.outDebug("+ %u MANA",enchant_amount);
11952 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
11953 break;
11954 case ITEM_MOD_HEALTH:
11955 sLog.outDebug("+ %u HEALTH",enchant_amount);
11956 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
11957 break;
11958 case ITEM_MOD_AGILITY:
11959 sLog.outDebug("+ %u AGILITY",enchant_amount);
11960 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11961 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11962 break;
11963 case ITEM_MOD_STRENGTH:
11964 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11965 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11966 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11967 break;
11968 case ITEM_MOD_INTELLECT:
11969 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11970 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11971 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11972 break;
11973 case ITEM_MOD_SPIRIT:
11974 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11975 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11976 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11977 break;
11978 case ITEM_MOD_STAMINA:
11979 sLog.outDebug("+ %u STAMINA",enchant_amount);
11980 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11981 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11982 break;
11983 case ITEM_MOD_DEFENSE_SKILL_RATING:
11984 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11985 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11986 break;
11987 case ITEM_MOD_DODGE_RATING:
11988 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11989 sLog.outDebug("+ %u DODGE", enchant_amount);
11990 break;
11991 case ITEM_MOD_PARRY_RATING:
11992 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11993 sLog.outDebug("+ %u PARRY", enchant_amount);
11994 break;
11995 case ITEM_MOD_BLOCK_RATING:
11996 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11997 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11998 break;
11999 case ITEM_MOD_HIT_MELEE_RATING:
12000 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12001 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
12002 break;
12003 case ITEM_MOD_HIT_RANGED_RATING:
12004 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12005 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
12006 break;
12007 case ITEM_MOD_HIT_SPELL_RATING:
12008 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12009 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
12010 break;
12011 case ITEM_MOD_CRIT_MELEE_RATING:
12012 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12013 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
12014 break;
12015 case ITEM_MOD_CRIT_RANGED_RATING:
12016 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12017 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
12018 break;
12019 case ITEM_MOD_CRIT_SPELL_RATING:
12020 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12021 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
12022 break;
12023 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12024 // in Enchantments
12025 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12026 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12027 // break;
12028 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12029 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12030 // break;
12031 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12032 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12033 // break;
12034 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12035 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12036 // break;
12037 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12038 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12039 // break;
12040 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12041 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12042 // break;
12043 // case ITEM_MOD_HASTE_MELEE_RATING:
12044 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12045 // break;
12046 // case ITEM_MOD_HASTE_RANGED_RATING:
12047 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12048 // break;
12049 case ITEM_MOD_HASTE_SPELL_RATING:
12050 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12051 break;
12052 case ITEM_MOD_HIT_RATING:
12053 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12054 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12055 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12056 sLog.outDebug("+ %u HIT", enchant_amount);
12057 break;
12058 case ITEM_MOD_CRIT_RATING:
12059 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12060 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12061 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12062 sLog.outDebug("+ %u CRITICAL", enchant_amount);
12063 break;
12064 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12065 // case ITEM_MOD_HIT_TAKEN_RATING:
12066 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12067 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12068 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12069 // break;
12070 // case ITEM_MOD_CRIT_TAKEN_RATING:
12071 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12072 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12073 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12074 // break;
12075 case ITEM_MOD_RESILIENCE_RATING:
12076 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12077 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12078 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12079 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
12080 break;
12081 case ITEM_MOD_HASTE_RATING:
12082 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12083 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12084 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12085 sLog.outDebug("+ %u HASTE", enchant_amount);
12086 break;
12087 case ITEM_MOD_EXPERTISE_RATING:
12088 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
12089 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
12090 break;
12091 case ITEM_MOD_ATTACK_POWER:
12092 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
12093 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12094 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
12095 break;
12096 case ITEM_MOD_RANGED_ATTACK_POWER:
12097 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12098 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
12099 break;
12100 case ITEM_MOD_FERAL_ATTACK_POWER:
12101 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
12102 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
12103 break;
12104 case ITEM_MOD_MANA_REGENERATION:
12105 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
12106 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
12107 break;
12108 case ITEM_MOD_ARMOR_PENETRATION_RATING:
12109 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
12110 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
12111 break;
12112 case ITEM_MOD_SPELL_POWER:
12113 ((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
12114 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
12115 break;
12116 case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
12117 case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
12118 default:
12119 break;
12121 break;
12123 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
12125 if(getClass() == CLASS_SHAMAN)
12127 float addValue = 0.0f;
12128 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12130 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12131 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
12133 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
12135 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12136 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
12139 break;
12141 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
12142 // processed in Player::CastItemUseSpell
12143 break;
12144 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
12145 // nothing do..
12146 break;
12147 default:
12148 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
12149 break;
12150 } /*switch(enchant_display_type)*/
12151 } /*for*/
12154 // visualize enchantment at player and equipped items
12155 if(slot == PERM_ENCHANTMENT_SLOT)
12156 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
12158 if(slot == TEMP_ENCHANTMENT_SLOT)
12159 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
12162 if(apply_dur)
12164 if(apply)
12166 // set duration
12167 uint32 duration = item->GetEnchantmentDuration(slot);
12168 if(duration > 0)
12169 AddEnchantmentDuration(item, slot, duration);
12171 else
12173 // duration == 0 will remove EnchantDuration
12174 AddEnchantmentDuration(item, slot, 0);
12179 void Player::SendEnchantmentDurations()
12181 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
12183 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
12187 void Player::SendItemDurations()
12189 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
12191 (*itr)->SendTimeUpdate(this);
12195 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12197 if(!item) // prevent crash
12198 return;
12200 // last check 2.0.10
12201 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12202 data << uint64(GetGUID()); // player GUID
12203 data << uint32(received); // 0=looted, 1=from npc
12204 data << uint32(created); // 0=received, 1=created
12205 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12206 data << uint8(item->GetBagSlot()); // bagslot
12207 // item slot, but when added to stack: 0xFFFFFFFF
12208 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
12209 data << uint32(item->GetEntry()); // item id
12210 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12211 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12212 data << uint32(count); // count of items
12213 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
12215 if (broadcast && GetGroup())
12216 GetGroup()->BroadcastPacket(&data, true);
12217 else
12218 GetSession()->SendPacket(&data);
12221 /*********************************************************/
12222 /*** GOSSIP SYSTEM ***/
12223 /*********************************************************/
12225 void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId)
12227 PlayerMenu* pMenu = PlayerTalkClass;
12228 pMenu->ClearMenus();
12230 pMenu->GetGossipMenu().SetMenuId(menuId);
12232 GossipMenuItemsMapBounds pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(menuId);
12234 // if default menuId and no menu options exist for this, use options from default options
12235 if (pMenuItemBounds.first == pMenuItemBounds.second && menuId == GetDefaultGossipMenuForSource(pSource))
12236 pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(0);
12238 for(GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr)
12240 bool bCanTalk = true;
12242 if (itr->second.cond_1 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1))
12243 continue;
12245 if (itr->second.cond_2 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12246 continue;
12248 if (itr->second.cond_3 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_3))
12249 continue;
12251 if (pSource->GetTypeId() == TYPEID_UNIT)
12253 Creature *pCreature = (Creature*)pSource;
12255 uint32 npcflags = pCreature->GetUInt32Value(UNIT_NPC_FLAGS);
12257 if (!(itr->second.npc_option_npcflag & npcflags))
12258 continue;
12260 switch(itr->second.option_id)
12262 case GOSSIP_OPTION_QUESTGIVER:
12263 PrepareQuestMenu(pSource->GetGUID());
12264 bCanTalk = false;
12265 break;
12266 case GOSSIP_OPTION_ARMORER:
12267 bCanTalk = false; // added in special mode
12268 break;
12269 case GOSSIP_OPTION_SPIRITHEALER:
12270 if (!isDead())
12271 bCanTalk = false;
12272 break;
12273 case GOSSIP_OPTION_VENDOR:
12275 VendorItemData const* vItems = pCreature->GetVendorItems();
12276 if (!vItems || vItems->Empty())
12278 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature->GetGUIDLow(), pCreature->GetEntry());
12279 bCanTalk = false;
12281 break;
12283 case GOSSIP_OPTION_TRAINER:
12284 if (!pCreature->isCanTrainingOf(this, false))
12285 bCanTalk = false;
12286 break;
12287 case GOSSIP_OPTION_UNLEARNTALENTS:
12288 if (!pCreature->isCanTrainingAndResetTalentsOf(this))
12289 bCanTalk = false;
12290 break;
12291 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12292 if (!GetPet() || GetPet()->getPetType() != HUNTER_PET || GetPet()->m_spells.size() <= 1 || pCreature->GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || pCreature->GetCreatureInfo()->trainer_class != CLASS_HUNTER)
12293 bCanTalk = false;
12294 break;
12295 case GOSSIP_OPTION_TAXIVENDOR:
12296 if (GetSession()->SendLearnNewTaxiNode(pCreature))
12297 return;
12298 break;
12299 case GOSSIP_OPTION_BATTLEFIELD:
12300 if (!pCreature->isCanInteractWithBattleMaster(this, false))
12301 bCanTalk = false;
12302 break;
12303 case GOSSIP_OPTION_STABLEPET:
12304 if (getClass() != CLASS_HUNTER)
12305 bCanTalk = false;
12306 break;
12307 case GOSSIP_OPTION_GOSSIP:
12308 case GOSSIP_OPTION_SPIRITGUIDE:
12309 case GOSSIP_OPTION_INNKEEPER:
12310 case GOSSIP_OPTION_BANKER:
12311 case GOSSIP_OPTION_PETITIONER:
12312 case GOSSIP_OPTION_TABARDDESIGNER:
12313 case GOSSIP_OPTION_AUCTIONEER:
12314 break; // no checks
12315 default:
12316 sLog.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature->GetEntry(), itr->second.option_id, itr->second.menu_id);
12317 bCanTalk = false;
12318 break;
12321 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12323 GameObject *pGo = (GameObject*)pSource;
12325 switch(itr->second.option_id)
12327 case GOSSIP_OPTION_QUESTGIVER:
12328 if (pGo->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
12329 PrepareQuestMenu(pSource->GetGUID());
12330 bCanTalk = false;
12331 break;
12332 case GOSSIP_OPTION_GOSSIP:
12333 if (pGo->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && pGo->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
12334 bCanTalk = false;
12335 break;
12336 default:
12337 bCanTalk = false;
12338 break;
12342 if (bCanTalk)
12344 std::string strOptionText = itr->second.option_text;
12345 std::string strBoxText = itr->second.box_text;
12347 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12349 if (loc_idx >= 0)
12351 uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.id);
12353 if (GossipMenuItemsLocale const *no = sObjectMgr.GetGossipMenuItemsLocale(idxEntry))
12355 if (no->OptionText.size() > (size_t)loc_idx && !no->OptionText[loc_idx].empty())
12356 strOptionText = no->OptionText[loc_idx];
12358 if (no->BoxText.size() > (size_t)loc_idx && !no->BoxText[loc_idx].empty())
12359 strBoxText = no->BoxText[loc_idx];
12363 pMenu->GetGossipMenu().AddMenuItem(itr->second.option_icon, strOptionText, 0, itr->second.option_id, strBoxText, itr->second.box_money, itr->second.box_coded);
12364 pMenu->GetGossipMenu().AddGossipMenuItemData(itr->second.action_menu_id, itr->second.action_poi_id, itr->second.action_script_id);
12368 // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
12369 /*if (pMenu->Empty())
12371 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
12373 // output error message if need
12374 pCreature->isCanTrainingOf(this, true);
12377 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
12379 // output error message if need
12380 pCreature->isCanInteractWithBattleMaster(this, true);
12385 void Player::SendPreparedGossip(WorldObject *pSource)
12387 if (!pSource)
12388 return;
12390 if (pSource->GetTypeId() == TYPEID_UNIT)
12392 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
12393 if (!((Creature*)pSource)->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
12395 SendPreparedQuest(pSource->GetGUID());
12396 return;
12399 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12401 // probably need to find a better way here
12402 if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
12404 SendPreparedQuest(pSource->GetGUID());
12405 return;
12409 // in case non empty gossip menu (that not included quests list size) show it
12410 // (quest entries from quest menu will be included in list)
12412 uint32 textId = GetGossipTextId(pSource);
12414 if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
12415 textId = GetGossipTextId(menuId);
12417 PlayerTalkClass->SendGossipMenu(textId, pSource->GetGUID());
12420 void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 menuId)
12422 GossipMenu& gossipmenu = PlayerTalkClass->GetGossipMenu();
12424 if (gossipListId >= gossipmenu.MenuItemCount())
12425 return;
12427 // if not same, then something funky is going on
12428 if (menuId != gossipmenu.GetMenuId())
12429 return;
12431 uint32 gossipOptionId = gossipmenu.GetItem(gossipListId).m_gOptionId;
12432 uint64 guid = pSource->GetGUID();
12434 if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12436 if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
12438 sLog.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource->GetEntry());
12439 return;
12443 GossipMenuItemData pMenuData = gossipmenu.GetItemData(gossipListId);
12445 switch(gossipOptionId)
12447 case GOSSIP_OPTION_GOSSIP:
12449 if (pMenuData.m_gAction_menu)
12451 PrepareGossipMenu(pSource, pMenuData.m_gAction_menu);
12452 SendPreparedGossip(pSource);
12455 if (pMenuData.m_gAction_poi)
12456 PlayerTalkClass->SendPointOfInterest(pMenuData.m_gAction_poi);
12458 if (pMenuData.m_gAction_script)
12460 if (pSource->GetTypeId() == TYPEID_UNIT)
12461 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, this, pSource);
12462 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12463 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, pSource, this);
12466 break;
12468 case GOSSIP_OPTION_SPIRITHEALER:
12469 if (isDead())
12470 ((Creature*)pSource)->CastSpell(((Creature*)pSource),17251,true,NULL,NULL,GetGUID());
12471 break;
12472 case GOSSIP_OPTION_QUESTGIVER:
12473 PrepareQuestMenu(guid);
12474 SendPreparedQuest(guid);
12475 break;
12476 case GOSSIP_OPTION_VENDOR:
12477 case GOSSIP_OPTION_ARMORER:
12478 GetSession()->SendListInventory(guid);
12479 break;
12480 case GOSSIP_OPTION_STABLEPET:
12481 GetSession()->SendStablePet(guid);
12482 break;
12483 case GOSSIP_OPTION_TRAINER:
12484 GetSession()->SendTrainerList(guid);
12485 break;
12486 case GOSSIP_OPTION_UNLEARNTALENTS:
12487 PlayerTalkClass->CloseGossip();
12488 SendTalentWipeConfirm(guid);
12489 break;
12490 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12491 PlayerTalkClass->CloseGossip();
12492 SendPetSkillWipeConfirm();
12493 break;
12494 case GOSSIP_OPTION_TAXIVENDOR:
12495 GetSession()->SendTaxiMenu(((Creature*)pSource));
12496 break;
12497 case GOSSIP_OPTION_INNKEEPER:
12498 PlayerTalkClass->CloseGossip();
12499 SetBindPoint(guid);
12500 break;
12501 case GOSSIP_OPTION_BANKER:
12502 GetSession()->SendShowBank(guid);
12503 break;
12504 case GOSSIP_OPTION_PETITIONER:
12505 PlayerTalkClass->CloseGossip();
12506 GetSession()->SendPetitionShowList(guid);
12507 break;
12508 case GOSSIP_OPTION_TABARDDESIGNER:
12509 PlayerTalkClass->CloseGossip();
12510 GetSession()->SendTabardVendorActivate(guid);
12511 break;
12512 case GOSSIP_OPTION_AUCTIONEER:
12513 GetSession()->SendAuctionHello(guid, ((Creature*)pSource));
12514 break;
12515 case GOSSIP_OPTION_SPIRITGUIDE:
12516 PrepareGossipMenu(pSource);
12517 SendPreparedGossip(pSource);
12518 break;
12519 case GOSSIP_OPTION_BATTLEFIELD:
12521 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(pSource->GetEntry());
12523 if (bgTypeId == BATTLEGROUND_TYPE_NONE)
12525 sLog.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
12526 return;
12529 GetSession()->SendBattlegGroundList(guid, bgTypeId);
12530 break;
12535 uint32 Player::GetGossipTextId(WorldObject *pSource)
12537 if (!pSource || pSource->GetTypeId() != TYPEID_UNIT || !((Creature*)pSource)->GetDBTableGUIDLow())
12538 return DEFAULT_GOSSIP_MESSAGE;
12540 if (uint32 pos = sObjectMgr.GetNpcGossip(((Creature*)pSource)->GetDBTableGUIDLow()))
12541 return pos;
12543 return DEFAULT_GOSSIP_MESSAGE;
12546 uint32 Player::GetGossipTextId(uint32 menuId)
12548 uint32 textId = DEFAULT_GOSSIP_MESSAGE;
12550 if (!menuId)
12551 return textId;
12553 GossipMenusMapBounds pMenuBounds = sObjectMgr.GetGossipMenusMapBounds(menuId);
12555 for(GossipMenusMap::const_iterator itr = pMenuBounds.first; itr != pMenuBounds.second; ++itr)
12557 if (sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1) && sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12558 textId = itr->second.text_id;
12561 return textId;
12564 uint32 Player::GetDefaultGossipMenuForSource(WorldObject *pSource)
12566 if (pSource->GetTypeId() == TYPEID_UNIT)
12567 return ((Creature*)pSource)->GetCreatureInfo()->GossipMenuId;
12568 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12569 return((GameObject*)pSource)->GetGOInfo()->GetGossipMenuId();
12571 return 0;
12574 /*********************************************************/
12575 /*** QUEST SYSTEM ***/
12576 /*********************************************************/
12578 void Player::PrepareQuestMenu( uint64 guid )
12580 Object *pObject;
12581 QuestRelations* pObjectQR;
12582 QuestRelations* pObjectQIR;
12584 // pets also can have quests
12585 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12587 pObject = (Object*)pCreature;
12588 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
12589 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
12591 else
12593 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12594 //only for quests which cast teleport spells on player
12595 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
12596 ASSERT(_map);
12597 GameObject *pGameObject = _map->GetGameObject(guid);
12598 if( pGameObject )
12600 pObject = (Object*)pGameObject;
12601 pObjectQR = &sObjectMgr.mGOQuestRelations;
12602 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
12604 else
12605 return;
12608 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12609 qm.ClearMenu();
12611 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12613 uint32 quest_id = i->second;
12614 QuestStatus status = GetQuestStatus( quest_id );
12615 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12616 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12617 else if ( status == QUEST_STATUS_INCOMPLETE )
12618 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12619 else if (status == QUEST_STATUS_AVAILABLE )
12620 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12623 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12625 uint32 quest_id = i->second;
12626 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12627 if(!pQuest) continue;
12629 QuestStatus status = GetQuestStatus( quest_id );
12631 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12632 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12633 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12634 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12638 void Player::SendPreparedQuest(uint64 guid)
12640 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12642 if (questMenu.Empty())
12643 return;
12645 QuestMenuItem const& qmi0 = questMenu.GetItem(0);
12647 uint32 status = qmi0.m_qIcon;
12649 // single element case
12650 if (questMenu.MenuItemCount() == 1)
12652 // Auto open -- maybe also should verify there is no greeting
12653 uint32 quest_id = qmi0.m_qId;
12654 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12656 if (pQuest)
12658 if (status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus(quest_id))
12659 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12660 else if (status == DIALOG_STATUS_UNK2)
12661 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12662 // Send completable on repeatable and autoCompletable quest if player don't have quest
12663 // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
12664 else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDaily())
12665 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true);
12666 else
12667 PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true);
12670 // multiply entries
12671 else
12673 QEmote qe;
12674 qe._Delay = 0;
12675 qe._Emote = 0;
12676 std::string title = "";
12678 // need pet case for some quests
12679 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12681 uint32 textid = GetGossipTextId(pCreature);
12683 GossipText const* gossiptext = sObjectMgr.GetGossipText(textid);
12684 if (!gossiptext)
12686 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12687 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12688 title = "";
12690 else
12692 qe = gossiptext->Options[0].Emotes[0];
12694 if(!gossiptext->Options[0].Text_0.empty())
12696 title = gossiptext->Options[0].Text_0;
12698 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12699 if (loc_idx >= 0)
12701 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12702 if (nl)
12704 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12705 title = nl->Text_0[0][loc_idx];
12709 else
12711 title = gossiptext->Options[0].Text_1;
12713 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12714 if (loc_idx >= 0)
12716 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12717 if (nl)
12719 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12720 title = nl->Text_1[0][loc_idx];
12726 PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
12730 bool Player::IsActiveQuest( uint32 quest_id ) const
12732 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12734 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12737 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12739 Object *pObject;
12740 QuestRelations* pObjectQR;
12741 QuestRelations* pObjectQIR;
12743 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12745 pObject = (Object*)pCreature;
12746 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
12747 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
12749 else
12751 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12752 //only for quests which cast teleport spells on player
12753 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
12754 ASSERT(_map);
12755 GameObject *pGameObject = _map->GetGameObject(guid);
12756 if( pGameObject )
12758 pObject = (Object*)pGameObject;
12759 pObjectQR = &sObjectMgr.mGOQuestRelations;
12760 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
12762 else
12763 return NULL;
12766 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12767 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12769 if (itr->second == nextQuestID)
12770 return sObjectMgr.GetQuestTemplate(nextQuestID);
12773 return NULL;
12776 bool Player::CanSeeStartQuest( Quest const *pQuest )
12778 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12779 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12780 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12781 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12783 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12786 return false;
12789 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12791 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12792 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12793 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12794 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12795 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12796 && SatisfyQuestDay( pQuest, msg );
12799 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12801 if( !SatisfyQuestLog( msg ) )
12802 return false;
12804 uint32 srcitem = pQuest->GetSrcItemId();
12805 if( srcitem > 0 )
12807 uint32 count = pQuest->GetSrcItemCount();
12808 ItemPosCountVec dest;
12809 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12811 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12812 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12813 return true;
12814 else if( msg2 != EQUIP_ERR_OK )
12816 SendEquipError( msg2, NULL, NULL );
12817 return false;
12820 return true;
12823 bool Player::CanCompleteQuest( uint32 quest_id )
12825 if( quest_id )
12827 QuestStatusData& q_status = mQuestStatus[quest_id];
12828 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12829 return false; // not allow re-complete quest
12831 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
12833 if(!qInfo)
12834 return false;
12836 // auto complete quest
12837 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12838 return true;
12840 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12843 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12845 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12847 if( qInfo->ReqItemCount[i] != 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12848 return false;
12852 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12854 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12856 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12857 continue;
12859 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12860 return false;
12864 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12865 return false;
12867 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12868 return false;
12870 if ( qInfo->GetRewOrReqMoney() < 0 )
12872 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12873 return false;
12876 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12877 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12878 return false;
12880 return true;
12883 return false;
12886 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12888 // Solve problem that player don't have the quest and try complete it.
12889 // if repeatable she must be able to complete event if player don't have it.
12890 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12891 if( !CanTakeQuest(pQuest, false) )
12892 return false;
12894 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12895 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12896 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i], pQuest->ReqItemCount[i]) )
12897 return false;
12899 if( !CanRewardQuest(pQuest, false) )
12900 return false;
12902 return true;
12905 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12907 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12908 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12909 return false;
12911 // daily quest can't be rewarded (25 daily quest already completed)
12912 if(!SatisfyQuestDay(pQuest,true))
12913 return false;
12915 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12916 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12917 return false;
12919 // prevent receive reward with quest items in bank
12920 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12922 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12924 if( pQuest->ReqItemCount[i] != 0 &&
12925 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12927 if(msg)
12928 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12929 return false;
12934 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12935 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12936 return false;
12938 return true;
12941 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12943 // prevent receive reward with quest items in bank or for not completed quest
12944 if(!CanRewardQuest(pQuest,msg))
12945 return false;
12947 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12949 if( pQuest->RewChoiceItemId[reward] )
12951 ItemPosCountVec dest;
12952 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12953 if( res != EQUIP_ERR_OK )
12955 SendEquipError( res, NULL, NULL );
12956 return false;
12961 if ( pQuest->GetRewItemsCount() > 0 )
12963 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12965 if( pQuest->RewItemId[i] )
12967 ItemPosCountVec dest;
12968 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12969 if( res != EQUIP_ERR_OK )
12971 SendEquipError( res, NULL, NULL );
12972 return false;
12978 return true;
12981 void Player::SendPetTameFailure(PetTameFailureReason reason)
12983 WorldPacket data(SMSG_PET_TAME_FAILURE, 1);
12984 data << uint8(reason);
12985 GetSession()->SendPacket(&data);
12988 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12990 uint16 log_slot = FindQuestSlot( 0 );
12991 assert(log_slot < MAX_QUEST_LOG_SIZE);
12993 uint32 quest_id = pQuest->GetQuestId();
12995 // if not exist then created with set uState==NEW and rewarded=false
12996 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12998 // check for repeatable quests status reset
12999 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
13000 questStatusData.m_explored = false;
13002 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13004 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13005 questStatusData.m_itemcount[i] = 0;
13008 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
13010 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13011 questStatusData.m_creatureOrGOcount[i] = 0;
13014 GiveQuestSourceItem( pQuest );
13015 AdjustQuestReqItemCount( pQuest, questStatusData );
13017 if( pQuest->GetRepObjectiveFaction() )
13018 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
13019 GetReputationMgr().SetVisible(factionEntry);
13021 uint32 qtime = 0;
13022 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13024 uint32 limittime = pQuest->GetLimitTime();
13026 // shared timed quest
13027 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
13028 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
13030 AddTimedQuest( quest_id );
13031 questStatusData.m_timer = limittime * IN_MILISECONDS;
13032 qtime = static_cast<uint32>(time(NULL)) + limittime;
13034 else
13035 questStatusData.m_timer = 0;
13037 SetQuestSlot(log_slot, quest_id, qtime);
13039 if (questStatusData.uState != QUEST_NEW)
13040 questStatusData.uState = QUEST_CHANGED;
13042 //starting initial quest script
13043 if(questGiver && pQuest->GetQuestStartScript()!=0)
13044 GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
13046 // Some spells applied at quest activation
13047 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,true);
13048 if(saBounds.first != saBounds.second)
13050 uint32 zone, area;
13051 GetZoneAndAreaId(zone,area);
13053 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13054 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13055 if( !HasAura(itr->second->spellId,0) )
13056 CastSpell(this,itr->second->spellId,true);
13059 UpdateForQuestWorldObjects();
13062 void Player::CompleteQuest( uint32 quest_id )
13064 if( quest_id )
13066 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
13068 uint16 log_slot = FindQuestSlot( quest_id );
13069 if( log_slot < MAX_QUEST_LOG_SIZE)
13070 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13072 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
13074 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
13075 RewardQuest(qInfo,0,this,false);
13076 else
13077 SendQuestComplete( quest_id );
13082 void Player::IncompleteQuest( uint32 quest_id )
13084 if( quest_id )
13086 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
13088 uint16 log_slot = FindQuestSlot( quest_id );
13089 if( log_slot < MAX_QUEST_LOG_SIZE)
13090 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13094 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
13096 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
13097 //should work fine, cause far teleport will be executed in Player::Update()
13098 SetCanDelayTeleport(true);
13100 uint32 quest_id = pQuest->GetQuestId();
13102 for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i )
13104 if (pQuest->ReqItemId[i])
13105 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
13108 RemoveTimedQuest(quest_id);
13110 if (BattleGround* bg = GetBattleGround())
13111 if (bg->GetTypeID() == BATTLEGROUND_AV)
13112 ((BattleGroundAV*)bg)->HandleQuestComplete(pQuest->GetQuestId(), this);
13114 if (pQuest->GetRewChoiceItemsCount() > 0)
13116 if (uint32 itemId = pQuest->RewChoiceItemId[reward])
13118 ItemPosCountVec dest;
13119 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK)
13121 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13122 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
13127 if (pQuest->GetRewItemsCount() > 0)
13129 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
13131 if (uint32 itemId = pQuest->RewItemId[i])
13133 ItemPosCountVec dest;
13134 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i] ) == EQUIP_ERR_OK)
13136 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13137 SendNewItem(item, pQuest->RewItemCount[i], true, false);
13143 RewardReputation( pQuest );
13145 uint16 log_slot = FindQuestSlot( quest_id );
13146 if (log_slot < MAX_QUEST_LOG_SIZE)
13147 SetQuestSlot(log_slot,0);
13149 QuestStatusData& q_status = mQuestStatus[quest_id];
13151 // Not give XP in case already completed once repeatable quest
13152 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
13154 if (getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
13155 GiveXP( XP , NULL );
13156 else
13158 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
13159 ModifyMoney( money );
13160 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
13163 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
13164 if (pQuest->GetRewOrReqMoney())
13166 ModifyMoney( pQuest->GetRewOrReqMoney() );
13168 if (pQuest->GetRewOrReqMoney() > 0)
13169 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
13172 // honor reward
13173 if (pQuest->GetRewHonorableKills())
13174 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13176 // title reward
13177 if (pQuest->GetCharTitleId())
13179 if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
13180 SetTitle(titleEntry);
13183 if (pQuest->GetBonusTalents())
13185 m_questRewardTalentCount+=pQuest->GetBonusTalents();
13186 InitTalentForLevel();
13189 // Send reward mail
13190 if (uint32 mail_template_id = pQuest->GetRewMailTemplateId())
13191 MailDraft(mail_template_id).SendMailTo(this, questGiver, MAIL_CHECK_MASK_NONE, pQuest->GetRewMailDelaySecs());
13193 if (pQuest->IsDaily())
13195 SetDailyQuestStatus(quest_id);
13196 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
13199 if (!pQuest->IsRepeatable())
13200 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
13201 else
13202 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
13204 q_status.m_rewarded = true;
13205 if (q_status.uState != QUEST_NEW)
13206 q_status.uState = QUEST_CHANGED;
13208 if (announce)
13209 SendQuestReward( pQuest, XP, questGiver );
13211 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
13212 if (pQuest->GetRewSpellCast() > 0)
13213 CastSpell( this, pQuest->GetRewSpellCast(), true);
13214 else if ( pQuest->GetRewSpell() > 0)
13215 CastSpell( this, pQuest->GetRewSpell(), true);
13217 if (pQuest->GetZoneOrSort() > 0)
13218 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
13219 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
13220 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
13222 uint32 zone = 0;
13223 uint32 area = 0;
13225 // remove auras from spells with quest reward state limitations
13226 SpellAreaForQuestMapBounds saEndBounds = sSpellMgr.GetSpellAreaForQuestEndMapBounds(quest_id);
13227 if(saEndBounds.first != saEndBounds.second)
13229 GetZoneAndAreaId(zone,area);
13231 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
13232 if(!itr->second->IsFitToRequirements(this,zone,area))
13233 RemoveAurasDueToSpell(itr->second->spellId);
13236 // Some spells applied at quest reward
13237 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,false);
13238 if(saBounds.first != saBounds.second)
13240 if(!zone || !area)
13241 GetZoneAndAreaId(zone,area);
13243 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13244 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13245 if( !HasAura(itr->second->spellId,0) )
13246 CastSpell(this,itr->second->spellId,true);
13249 //lets remove flag for delayed teleports
13250 SetCanDelayTeleport(false);
13253 void Player::FailQuest(uint32 questId)
13255 if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(questId))
13257 SetQuestStatus(questId, QUEST_STATUS_FAILED);
13259 uint16 log_slot = FindQuestSlot(questId);
13261 if (log_slot < MAX_QUEST_LOG_SIZE)
13263 SetQuestSlotTimer(log_slot, 1);
13264 SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
13267 if (pQuest->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13269 QuestStatusData& q_status = mQuestStatus[questId];
13271 RemoveTimedQuest(questId);
13272 q_status.m_timer = 0;
13274 SendQuestTimerFailed(questId);
13276 else
13277 SendQuestFailed(questId);
13281 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
13283 int32 zoneOrSort = qInfo->GetZoneOrSort();
13284 int32 skillOrClass = qInfo->GetSkillOrClass();
13286 // skip zone zoneOrSort and 0 case skillOrClass
13287 if( zoneOrSort >= 0 && skillOrClass == 0 )
13288 return true;
13290 int32 questSort = -zoneOrSort;
13291 uint8 reqSortClass = ClassByQuestSort(questSort);
13293 // check class sort cases in zoneOrSort
13294 if( reqSortClass != 0 && getClass() != reqSortClass)
13296 if( msg )
13297 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13298 return false;
13301 // check class
13302 if( skillOrClass < 0 )
13304 uint8 reqClass = -int32(skillOrClass);
13305 if(getClass() != reqClass)
13307 if( msg )
13308 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13309 return false;
13312 // check skill
13313 else if( skillOrClass > 0 )
13315 uint32 reqSkill = skillOrClass;
13316 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
13318 if( msg )
13319 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13320 return false;
13324 return true;
13327 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
13329 if( getLevel() < qInfo->GetMinLevel() )
13331 if( msg )
13332 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13333 return false;
13335 return true;
13338 bool Player::SatisfyQuestLog( bool msg )
13340 // exist free slot
13341 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
13342 return true;
13344 if( msg )
13346 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
13347 GetSession()->SendPacket( &data );
13348 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
13350 return false;
13353 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
13355 // No previous quest (might be first quest in a series)
13356 if( qInfo->prevQuests.empty())
13357 return true;
13359 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
13361 uint32 prevId = abs(*iter);
13363 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13364 Quest const* qPrevInfo = sObjectMgr.GetQuestTemplate(prevId);
13366 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
13368 // If any of the positive previous quests completed, return true
13369 if( *iter > 0 && i_prevstatus->second.m_rewarded )
13371 // skip one-from-all exclusive group
13372 if(qPrevInfo->GetExclusiveGroup() >= 0)
13373 return true;
13375 // each-from-all exclusive group ( < 0)
13376 // can be start if only all quests in prev quest exclusive group completed and rewarded
13377 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13378 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13380 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13382 for(; iter2 != end; ++iter2)
13384 uint32 exclude_Id = iter2->second;
13386 // skip checked quest id, only state of other quests in group is interesting
13387 if(exclude_Id == prevId)
13388 continue;
13390 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13392 // alternative quest from group also must be completed and rewarded(reported)
13393 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
13395 if( msg )
13396 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13397 return false;
13400 return true;
13402 // If any of the negative previous quests active, return true
13403 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13404 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
13406 // skip one-from-all exclusive group
13407 if(qPrevInfo->GetExclusiveGroup() >= 0)
13408 return true;
13410 // each-from-all exclusive group ( < 0)
13411 // can be start if only all quests in prev quest exclusive group active
13412 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13413 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13415 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13417 for(; iter2 != end; ++iter2)
13419 uint32 exclude_Id = iter2->second;
13421 // skip checked quest id, only state of other quests in group is interesting
13422 if(exclude_Id == prevId)
13423 continue;
13425 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13427 // alternative quest from group also must be active
13428 if( i_exstatus == mQuestStatus.end() ||
13429 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
13430 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
13432 if( msg )
13433 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13434 return false;
13437 return true;
13442 // Has only positive prev. quests in non-rewarded state
13443 // and negative prev. quests in non-active state
13444 if( msg )
13445 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13447 return false;
13450 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
13452 uint32 reqraces = qInfo->GetRequiredRaces();
13453 if ( reqraces == 0 )
13454 return true;
13455 if( (reqraces & getRaceMask()) == 0 )
13457 if( msg )
13458 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13459 return false;
13461 return true;
13464 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13466 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13467 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13469 if( msg )
13470 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13471 return false;
13474 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13475 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13477 if( msg )
13478 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13479 return false;
13482 return true;
13485 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13487 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13488 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13490 if( msg )
13491 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13492 return false;
13494 return true;
13497 bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
13499 if (!m_timedquests.empty() && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13501 if (msg)
13502 SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
13504 return false;
13506 return true;
13509 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13511 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13512 if(qInfo->GetExclusiveGroup() <= 0)
13513 return true;
13515 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = sObjectMgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13516 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13518 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13520 for(; iter != end; ++iter)
13522 uint32 exclude_Id = iter->second;
13524 // skip checked quest id, only state of other quests in group is interesting
13525 if(exclude_Id == qInfo->GetQuestId())
13526 continue;
13528 // not allow have daily quest if daily quest from exclusive group already recently completed
13529 Quest const* Nquest = sObjectMgr.GetQuestTemplate(exclude_Id);
13530 if( !SatisfyQuestDay(Nquest, false) )
13532 if( msg )
13533 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13534 return false;
13537 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13539 // alternative quest already started or completed
13540 if( i_exstatus != mQuestStatus.end()
13541 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13543 if( msg )
13544 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13545 return false;
13548 return true;
13551 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13553 if(!qInfo->GetNextQuestInChain())
13554 return true;
13556 // next quest in chain already started or completed
13557 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13558 if( itr != mQuestStatus.end()
13559 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13561 if( msg )
13562 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13563 return false;
13566 // check for all quests further up the chain
13567 // only necessary if there are quest chains with more than one quest that can be skipped
13568 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13569 return true;
13572 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13574 // No previous quest in chain
13575 if( qInfo->prevChainQuests.empty())
13576 return true;
13578 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13580 uint32 prevId = *iter;
13582 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13584 if( i_prevstatus != mQuestStatus.end() )
13586 // If any of the previous quests in chain active, return false
13587 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13588 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13590 if( msg )
13591 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13592 return false;
13596 // check for all quests further down the chain
13597 // only necessary if there are quest chains with more than one quest that can be skipped
13598 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13599 // return false;
13602 // No previous quest in chain active
13603 return true;
13606 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13608 if(!qInfo->IsDaily())
13609 return true;
13611 bool have_slot = false;
13612 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13614 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13615 if(qInfo->GetQuestId()==id)
13616 return false;
13618 if(!id)
13619 have_slot = true;
13622 if(!have_slot)
13624 if( msg )
13625 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13626 return false;
13629 return true;
13632 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13634 uint32 srcitem = pQuest->GetSrcItemId();
13635 if( srcitem > 0 )
13637 uint32 count = pQuest->GetSrcItemCount();
13638 if( count <= 0 )
13639 count = 1;
13641 ItemPosCountVec dest;
13642 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13643 if( msg == EQUIP_ERR_OK )
13645 Item * item = StoreNewItem(dest, srcitem, true);
13646 SendNewItem(item, count, true, false);
13647 return true;
13649 // player already have max amount required item, just report success
13650 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13651 return true;
13652 else
13653 SendEquipError( msg, NULL, NULL );
13654 return false;
13657 return true;
13660 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13662 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13663 if( qInfo )
13665 uint32 srcitem = qInfo->GetSrcItemId();
13666 if( srcitem > 0 )
13668 uint32 count = qInfo->GetSrcItemCount();
13669 if( count <= 0 )
13670 count = 1;
13672 // exist one case when destroy source quest item not possible:
13673 // non un-equippable item (equipped non-empty bag, for example)
13674 uint8 res = CanUnequipItems(srcitem,count);
13675 if(res != EQUIP_ERR_OK)
13677 if(msg)
13678 SendEquipError( res, NULL, NULL );
13679 return false;
13682 DestroyItemCount(srcitem, count, true, true);
13685 return true;
13688 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13690 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13691 if( qInfo )
13693 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13694 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13695 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13696 && !qInfo->IsRepeatable() )
13697 return itr->second.m_rewarded;
13699 return false;
13701 return false;
13704 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13706 if( quest_id )
13708 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13709 if( itr != mQuestStatus.end() )
13710 return itr->second.m_status;
13712 return QUEST_STATUS_NONE;
13715 bool Player::CanShareQuest(uint32 quest_id) const
13717 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13718 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13720 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13721 if( itr != mQuestStatus.end() )
13722 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13724 return false;
13727 void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
13729 if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
13731 QuestStatusData& q_status = mQuestStatus[quest_id];
13733 q_status.m_status = status;
13735 if (q_status.uState != QUEST_NEW)
13736 q_status.uState = QUEST_CHANGED;
13739 UpdateForQuestWorldObjects();
13742 // not used in MaNGOS, but used in scripting code
13743 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13745 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13746 if( !qInfo )
13747 return 0;
13749 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13750 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13751 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13753 return 0;
13756 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13758 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13760 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13762 uint32 reqitemcount = pQuest->ReqItemCount[i];
13763 if( reqitemcount != 0 )
13765 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i], true);
13767 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13768 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13774 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13776 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13777 if ( GetQuestSlotQuestId(i) == quest_id )
13778 return i;
13780 return MAX_QUEST_LOG_SIZE;
13783 void Player::AreaExploredOrEventHappens( uint32 questId )
13785 if( questId )
13787 uint16 log_slot = FindQuestSlot( questId );
13788 if( log_slot < MAX_QUEST_LOG_SIZE)
13790 QuestStatusData& q_status = mQuestStatus[questId];
13792 if(!q_status.m_explored)
13794 q_status.m_explored = true;
13795 if (q_status.uState != QUEST_NEW)
13796 q_status.uState = QUEST_CHANGED;
13799 if( CanCompleteQuest( questId ) )
13800 CompleteQuest( questId );
13804 //not used in mangosd, function for external script library
13805 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13807 if( Group *pGroup = GetGroup() )
13809 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13811 Player *pGroupGuy = itr->getSource();
13813 // for any leave or dead (with not released body) group member at appropriate distance
13814 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13815 pGroupGuy->AreaExploredOrEventHappens(questId);
13818 else
13819 AreaExploredOrEventHappens(questId);
13822 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13824 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13826 uint32 questid = GetQuestSlotQuestId(i);
13827 if ( questid == 0 )
13828 continue;
13830 QuestStatusData& q_status = mQuestStatus[questid];
13832 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13833 continue;
13835 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13836 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13837 continue;
13839 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
13841 uint32 reqitem = qInfo->ReqItemId[j];
13842 if ( reqitem == entry )
13844 uint32 reqitemcount = qInfo->ReqItemCount[j];
13845 uint32 curitemcount = q_status.m_itemcount[j];
13846 if ( curitemcount < reqitemcount )
13848 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13849 q_status.m_itemcount[j] += additemcount;
13850 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13852 SendQuestUpdateAddItem( qInfo, j, additemcount );
13854 if ( CanCompleteQuest( questid ) )
13855 CompleteQuest( questid );
13856 return;
13860 UpdateForQuestWorldObjects();
13863 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13865 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13867 uint32 questid = GetQuestSlotQuestId(i);
13868 if(!questid)
13869 continue;
13870 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13871 if ( !qInfo )
13872 continue;
13873 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13874 continue;
13876 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
13878 uint32 reqitem = qInfo->ReqItemId[j];
13879 if ( reqitem == entry )
13881 QuestStatusData& q_status = mQuestStatus[questid];
13883 uint32 reqitemcount = qInfo->ReqItemCount[j];
13884 uint32 curitemcount;
13885 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13886 curitemcount = q_status.m_itemcount[j];
13887 else
13888 curitemcount = GetItemCount(entry, true);
13889 if ( curitemcount < reqitemcount + count )
13891 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13892 q_status.m_itemcount[j] = curitemcount - remitemcount;
13893 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13895 IncompleteQuest( questid );
13897 return;
13901 UpdateForQuestWorldObjects();
13904 void Player::KilledMonster( CreatureInfo const* cInfo, uint64 guid )
13906 if(cInfo->Entry)
13907 KilledMonsterCredit(cInfo->Entry,guid);
13909 for(int i = 0; i < MAX_KILL_CREDIT; ++i)
13910 if(cInfo->KillCredit[i])
13911 KilledMonsterCredit(cInfo->KillCredit[i],guid);
13914 void Player::KilledMonsterCredit( uint32 entry, uint64 guid )
13916 uint32 addkillcount = 1;
13917 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13918 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13920 uint32 questid = GetQuestSlotQuestId(i);
13921 if(!questid)
13922 continue;
13924 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13925 if( !qInfo )
13926 continue;
13927 // just if !ingroup || !noraidgroup || raidgroup
13928 QuestStatusData& q_status = mQuestStatus[questid];
13929 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13931 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13933 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13935 // skip GO activate objective or none
13936 if(qInfo->ReqCreatureOrGOId[j] <=0)
13937 continue;
13939 // skip Cast at creature objective
13940 if(qInfo->ReqSpell[j] !=0 )
13941 continue;
13943 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13945 if ( reqkill == entry )
13947 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13948 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13949 if ( curkillcount < reqkillcount )
13951 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13952 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13954 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13956 if ( CanCompleteQuest( questid ) )
13957 CompleteQuest( questid );
13959 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13960 continue;
13968 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13970 bool isCreature = IS_CREATURE_GUID(guid);
13972 uint32 addCastCount = 1;
13973 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13975 uint32 questid = GetQuestSlotQuestId(i);
13976 if(!questid)
13977 continue;
13979 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13980 if ( !qInfo )
13981 continue;
13983 QuestStatusData& q_status = mQuestStatus[questid];
13985 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13987 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13989 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13991 // skip kill creature objective (0) or wrong spell casts
13992 if(qInfo->ReqSpell[j] != spell_id )
13993 continue;
13995 uint32 reqTarget = 0;
13997 if(isCreature)
13999 // creature activate objectives
14000 if(qInfo->ReqCreatureOrGOId[j] > 0)
14001 // checked at quest_template loading
14002 reqTarget = qInfo->ReqCreatureOrGOId[j];
14004 else
14006 // GO activate objective
14007 if(qInfo->ReqCreatureOrGOId[j] < 0)
14008 // checked at quest_template loading
14009 reqTarget = - qInfo->ReqCreatureOrGOId[j];
14012 // other not this creature/GO related objectives
14013 if( reqTarget != entry )
14014 continue;
14016 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
14017 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
14018 if ( curCastCount < reqCastCount )
14020 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
14021 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14023 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
14026 if ( CanCompleteQuest( questid ) )
14027 CompleteQuest( questid );
14029 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14030 break;
14037 void Player::TalkedToCreature( uint32 entry, uint64 guid )
14039 uint32 addTalkCount = 1;
14040 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14042 uint32 questid = GetQuestSlotQuestId(i);
14043 if(!questid)
14044 continue;
14046 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14047 if ( !qInfo )
14048 continue;
14050 QuestStatusData& q_status = mQuestStatus[questid];
14052 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14054 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
14056 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14058 // skip spell casts and Gameobject objectives
14059 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
14060 continue;
14062 uint32 reqTarget = 0;
14064 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
14065 // checked at quest_template loading
14066 reqTarget = qInfo->ReqCreatureOrGOId[j];
14067 else
14068 continue;
14070 if ( reqTarget == entry )
14072 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
14073 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
14074 if ( curTalkCount < reqTalkCount )
14076 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
14077 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14079 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
14081 if ( CanCompleteQuest( questid ) )
14082 CompleteQuest( questid );
14084 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14085 continue;
14093 void Player::MoneyChanged( uint32 count )
14095 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14097 uint32 questid = GetQuestSlotQuestId(i);
14098 if (!questid)
14099 continue;
14101 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14102 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
14104 QuestStatusData& q_status = mQuestStatus[questid];
14106 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14108 if(int32(count) >= -qInfo->GetRewOrReqMoney())
14110 if ( CanCompleteQuest( questid ) )
14111 CompleteQuest( questid );
14114 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14116 if(int32(count) < -qInfo->GetRewOrReqMoney())
14117 IncompleteQuest( questid );
14123 void Player::ReputationChanged(FactionEntry const* factionEntry )
14125 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14127 if(uint32 questid = GetQuestSlotQuestId(i))
14129 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid))
14131 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
14133 QuestStatusData& q_status = mQuestStatus[questid];
14134 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14136 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
14137 if ( CanCompleteQuest( questid ) )
14138 CompleteQuest( questid );
14140 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14142 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
14143 IncompleteQuest( questid );
14151 bool Player::HasQuestForItem( uint32 itemid ) const
14153 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14155 uint32 questid = GetQuestSlotQuestId(i);
14156 if ( questid == 0 )
14157 continue;
14159 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
14160 if(qs_itr == mQuestStatus.end())
14161 continue;
14163 QuestStatusData const& q_status = qs_itr->second;
14165 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
14167 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
14168 if(!qinfo)
14169 continue;
14171 // hide quest if player is in raid-group and quest is no raid quest
14172 if (GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID
14173 && !InBattleGround())
14174 continue;
14176 // There should be no mixed ReqItem/ReqSource drop
14177 // This part for ReqItem drop
14178 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
14180 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
14181 return true;
14183 // This part - for ReqSource
14184 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
14186 // examined item is a source item
14187 if (qinfo->ReqSourceId[j] == itemid)
14189 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(itemid);
14191 // 'unique' item
14192 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
14193 return true;
14195 // allows custom amount drop when not 0
14196 if (qinfo->ReqSourceCount[j])
14198 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
14199 return true;
14200 } else if (GetItemCount(itemid,true) < pProto->Stackable)
14201 return true;
14206 return false;
14209 void Player::SendQuestComplete( uint32 quest_id )
14211 if( quest_id )
14213 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
14214 data << uint32(quest_id);
14215 GetSession()->SendPacket( &data );
14216 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
14220 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
14222 uint32 questid = pQuest->GetQuestId();
14223 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
14224 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
14225 data << uint32(questid);
14227 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
14229 data << uint32(XP);
14230 data << uint32(pQuest->GetRewOrReqMoney());
14232 else
14234 data << uint32(0);
14235 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
14238 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
14239 data << uint32(pQuest->GetBonusTalents()); // bonus talents
14240 data << uint32(0);
14241 GetSession()->SendPacket( &data );
14243 if (pQuest->GetQuestCompleteScript() != 0)
14244 GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
14247 void Player::SendQuestFailed( uint32 quest_id )
14249 if( quest_id )
14251 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
14252 data << uint32(quest_id);
14253 data << uint32(0); // failed reason (4 for inventory is full)
14254 GetSession()->SendPacket( &data );
14255 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
14259 void Player::SendQuestTimerFailed( uint32 quest_id )
14261 if( quest_id )
14263 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
14264 data << uint32(quest_id);
14265 GetSession()->SendPacket( &data );
14266 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
14270 void Player::SendCanTakeQuestResponse( uint32 msg )
14272 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
14273 data << uint32(msg);
14274 GetSession()->SendPacket( &data );
14275 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
14278 void Player::SendQuestConfirmAccept(const Quest* pQuest, Player* pReceiver)
14280 if (pReceiver)
14282 std::string strTitle = pQuest->GetTitle();
14284 int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
14286 if (loc_idx >= 0)
14288 if (const QuestLocale* pLocale = sObjectMgr.GetQuestLocale(pQuest->GetQuestId()))
14290 if (pLocale->Title.size() > loc_idx && !pLocale->Title[loc_idx].empty())
14291 strTitle = pLocale->Title[loc_idx];
14295 WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8));
14296 data << uint32(pQuest->GetQuestId());
14297 data << strTitle;
14298 data << uint64(GetGUID());
14299 pReceiver->GetSession()->SendPacket(&data);
14301 sLog.outDebug("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
14305 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
14307 if( pPlayer )
14309 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
14310 data << uint64(pPlayer->GetGUID());
14311 data << uint8(msg); // valid values: 0-8
14312 GetSession()->SendPacket( &data );
14313 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
14317 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
14319 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
14320 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
14321 //data << pQuest->ReqItemId[item_idx];
14322 //data << count;
14323 GetSession()->SendPacket( &data );
14326 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
14328 assert(old_count + add_count < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
14330 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
14331 if (entry < 0)
14332 // client expected gameobject template id in form (id|0x80000000)
14333 entry = (-entry) | 0x80000000;
14335 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
14336 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
14337 data << uint32(pQuest->GetQuestId());
14338 data << uint32(entry);
14339 data << uint32(old_count + add_count);
14340 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
14341 data << uint64(guid);
14342 GetSession()->SendPacket(&data);
14344 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
14345 if( log_slot < MAX_QUEST_LOG_SIZE)
14346 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
14349 /*********************************************************/
14350 /*** LOAD SYSTEM ***/
14351 /*********************************************************/
14353 void Player::_LoadDeclinedNames(QueryResult* result)
14355 if(!result)
14356 return;
14358 if(m_declinedname)
14359 delete m_declinedname;
14361 m_declinedname = new DeclinedName;
14362 Field *fields = result->Fetch();
14363 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
14364 m_declinedname->name[i] = fields[i].GetCppString();
14366 delete result;
14369 void Player::_LoadArenaTeamInfo(QueryResult *result)
14371 // arenateamid, played_week, played_season, personal_rating
14372 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
14373 if (!result)
14374 return;
14378 Field *fields = result->Fetch();
14380 uint32 arenateamid = fields[0].GetUInt32();
14381 uint32 played_week = fields[1].GetUInt32();
14382 uint32 played_season = fields[2].GetUInt32();
14383 uint32 wons_season = fields[3].GetUInt32();
14384 uint32 personal_rating = fields[4].GetUInt32();
14386 ArenaTeam* aTeam = sObjectMgr.GetArenaTeamById(arenateamid);
14387 if(!aTeam)
14389 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid);
14390 continue;
14392 uint8 arenaSlot = aTeam->GetSlot();
14394 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_ID] = arenateamid; // TeamID
14395 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_TYPE] = aTeam->GetType(); // team type
14396 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_MEMBER] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
14397 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_GAMES_WEEK] = played_week; // Played Week
14398 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_GAMES_SEASON] = played_season; // Played Season
14399 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_WINS_SEASON] = wons_season; // wins season
14400 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING] = personal_rating; // Personal Rating
14402 } while (result->NextRow());
14403 delete result;
14406 void Player::_LoadEquipmentSets(QueryResult *result)
14408 // 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));
14409 if (!result)
14410 return;
14412 uint32 count = 0;
14415 Field *fields = result->Fetch();
14417 EquipmentSet eqSet;
14419 eqSet.Guid = fields[0].GetUInt64();
14420 uint32 index = fields[1].GetUInt32();
14421 eqSet.Name = fields[2].GetCppString();
14422 eqSet.IconName = fields[3].GetCppString();
14423 eqSet.state = EQUIPMENT_SET_UNCHANGED;
14425 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
14426 eqSet.Items[i] = fields[4+i].GetUInt32();
14428 m_EquipmentSets[index] = eqSet;
14430 ++count;
14432 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
14433 break;
14434 } while (result->NextRow());
14435 delete result;
14438 void Player::_LoadBGData(QueryResult* result)
14440 if (!result)
14441 return;
14443 // Expecting only one row
14444 Field *fields = result->Fetch();
14445 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
14446 m_bgData.bgInstanceID = fields[0].GetUInt32();
14447 m_bgData.bgTeam = fields[1].GetUInt32();
14448 m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
14449 fields[2].GetFloat(), // X
14450 fields[3].GetFloat(), // Y
14451 fields[4].GetFloat(), // Z
14452 fields[5].GetFloat()); // Orientation
14453 m_bgData.taxiPath[0] = fields[7].GetUInt32();
14454 m_bgData.taxiPath[1] = fields[8].GetUInt32();
14455 m_bgData.mountSpell = fields[9].GetUInt32();
14457 delete result;
14460 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
14462 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
14463 if(!result)
14464 return false;
14466 Field *fields = result->Fetch();
14468 x = fields[0].GetFloat();
14469 y = fields[1].GetFloat();
14470 z = fields[2].GetFloat();
14471 o = fields[3].GetFloat();
14472 mapid = fields[4].GetUInt32();
14473 in_flight = !fields[5].GetCppString().empty();
14475 delete result;
14476 return true;
14479 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
14481 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
14482 if( !result )
14483 return false;
14485 Field *fields = result->Fetch();
14487 data = StrSplit(fields[0].GetCppString(), " ");
14489 delete result;
14491 return true;
14494 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
14496 if(index >= data.size())
14497 return 0;
14499 return (uint32)atoi(data[index].c_str());
14502 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
14504 float result;
14505 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
14506 memcpy(&result, &temp, sizeof(result));
14508 return result;
14511 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14513 Tokens data;
14514 if(!LoadValuesArrayFromDB(data,guid))
14515 return 0;
14517 return GetUInt32ValueFromArray(data,index);
14520 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14522 float result;
14523 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14524 memcpy(&result, &temp, sizeof(result));
14526 return result;
14529 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14531 //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
14532 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points FROM characters WHERE guid = '%u'", guid);
14533 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14535 if(!result)
14537 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14538 return false;
14541 Field *fields = result->Fetch();
14543 uint32 dbAccountId = fields[1].GetUInt32();
14545 // check if the character's account in the db and the logged in account match.
14546 // player should be able to load/delete character only with correct account!
14547 if( dbAccountId != GetSession()->GetAccountId() )
14549 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14550 delete result;
14551 return false;
14554 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14556 m_name = fields[3].GetCppString();
14558 // check name limitations
14559 if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
14560 (GetSession()->GetSecurity() == SEC_PLAYER && sObjectMgr.IsReservedName(m_name)))
14562 delete result;
14563 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14564 return false;
14567 if(!LoadValues( fields[2].GetString()))
14569 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
14570 delete result;
14571 return false;
14574 // overwrite possible wrong/corrupted guid
14575 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14577 // overwrite some data fields
14578 uint32 bytes0 = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0xFF000000;
14579 bytes0 |= fields[4].GetUInt8(); // race
14580 bytes0 |= fields[5].GetUInt8() << 8; // class
14581 bytes0 |= fields[6].GetUInt8() << 16; // gender
14582 SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
14584 SetUInt32Value(UNIT_FIELD_LEVEL, fields[7].GetUInt8());
14585 SetUInt32Value(PLAYER_XP, fields[8].GetUInt32());
14586 SetUInt32Value(PLAYER_FIELD_COINAGE, fields[9].GetUInt32());
14587 SetUInt32Value(PLAYER_BYTES, fields[10].GetUInt32());
14588 SetUInt32Value(PLAYER_BYTES_2, fields[11].GetUInt32());
14589 SetUInt32Value(PLAYER_BYTES_3, (GetUInt32Value(PLAYER_BYTES_3) & ~1) | fields[6].GetUInt8());
14590 SetUInt32Value(PLAYER_FLAGS, fields[12].GetUInt32());
14592 InitDisplayIds();
14594 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14595 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14597 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
14598 SetVisibleItemSlot(slot, NULL);
14600 if (m_items[slot])
14602 delete m_items[slot];
14603 m_items[slot] = NULL;
14607 // update money limits
14608 if(GetMoney() > MAX_MONEY_AMOUNT)
14609 SetMoney(MAX_MONEY_AMOUNT);
14611 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14612 outDebugValues();
14614 //Need to call it to initialize m_team (m_team can be calculated from race)
14615 //Other way is to saves m_team into characters table.
14616 setFactionForRace(getRace());
14617 SetCharm(NULL);
14619 // load home bind and check in same time class/race pair, it used later for restore broken positions
14620 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14622 delete result;
14623 return false;
14626 InitPrimaryProfessions(); // to max set before any spell loaded
14628 // init saved position, and fix it later if problematic
14629 uint32 transGUID = fields[31].GetUInt32();
14630 Relocate(fields[13].GetFloat(),fields[14].GetFloat(),fields[15].GetFloat(),fields[17].GetFloat());
14631 SetLocationMapId(fields[16].GetUInt32());
14633 uint32 difficulty = fields[39].GetUInt32();
14634 if(difficulty >= MAX_DUNGEON_DIFFICULTY)
14635 difficulty = DUNGEON_DIFFICULTY_NORMAL;
14636 SetDungeonDifficulty(Difficulty(difficulty)); // may be changed in _LoadGroup
14638 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14640 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14642 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[40].GetUInt32();
14643 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
14644 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14646 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14648 // check arena teams integrity
14649 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14651 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14652 if(!arena_team_id)
14653 continue;
14655 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(arena_team_id))
14656 if(at->HaveMember(GetGUID()))
14657 continue;
14659 // arena team not exist or not member, cleanup fields
14660 for(int j = 0; j < ARENA_TEAM_END; ++j)
14661 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arena_slot * ARENA_TEAM_END) + j, 0);
14664 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14666 if(!IsPositionValid())
14668 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());
14669 RelocateToHomebind();
14671 transGUID = 0;
14673 m_movementInfo.t_x = 0.0f;
14674 m_movementInfo.t_y = 0.0f;
14675 m_movementInfo.t_z = 0.0f;
14676 m_movementInfo.t_o = 0.0f;
14677 m_movementInfo.t_time = 0;
14678 m_movementInfo.t_seat = -1;
14681 _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
14683 if(m_bgData.bgInstanceID) //saved in BattleGround
14685 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
14687 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14689 BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14690 AddBattleGroundQueueId(bgQueueTypeId);
14692 m_bgData.bgTypeID = currentBg->GetTypeID();
14694 //join player to battleground group
14695 currentBg->EventPlayerLoggedIn(this, GetGUID());
14696 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData.bgTeam);
14698 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14700 else
14702 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14703 SetLocationMapId(_loc.mapid);
14704 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14706 // We are not in BG anymore
14707 m_bgData.bgInstanceID = 0;
14710 else
14712 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14713 // if server restart after player save in BG or area
14714 // player can have current coordinates in to BG/Arena map, fix this
14715 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14717 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14718 SetLocationMapId(_loc.mapid);
14719 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14723 if (transGUID != 0)
14725 m_movementInfo.t_x = fields[27].GetFloat();
14726 m_movementInfo.t_y = fields[28].GetFloat();
14727 m_movementInfo.t_z = fields[29].GetFloat();
14728 m_movementInfo.t_o = fields[30].GetFloat();
14730 if( !MaNGOS::IsValidMapCoord(
14731 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14732 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14733 // transport size limited
14734 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14736 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14737 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14738 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14740 RelocateToHomebind();
14742 m_movementInfo.t_x = 0.0f;
14743 m_movementInfo.t_y = 0.0f;
14744 m_movementInfo.t_z = 0.0f;
14745 m_movementInfo.t_o = 0.0f;
14746 m_movementInfo.t_time = 0;
14747 m_movementInfo.t_seat = -1;
14749 transGUID = 0;
14753 if (transGUID != 0)
14755 for (MapManager::TransportSet::const_iterator iter = sMapMgr.m_Transports.begin(); iter != sMapMgr.m_Transports.end(); ++iter)
14757 if( (*iter)->GetGUIDLow() == transGUID)
14759 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14760 // client without expansion support
14761 if(GetSession()->Expansion() < transMapEntry->Expansion())
14763 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14764 break;
14767 m_transport = *iter;
14768 m_transport->AddPassenger(this);
14769 SetLocationMapId(m_transport->GetMapId());
14770 break;
14774 if(!m_transport)
14776 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14777 guid,transGUID);
14779 RelocateToHomebind();
14781 m_movementInfo.t_x = 0.0f;
14782 m_movementInfo.t_y = 0.0f;
14783 m_movementInfo.t_z = 0.0f;
14784 m_movementInfo.t_o = 0.0f;
14785 m_movementInfo.t_time = 0;
14786 m_movementInfo.t_seat = -1;
14788 transGUID = 0;
14791 else // not transport case
14793 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14794 // client without expansion support
14795 if(GetSession()->Expansion() < mapEntry->Expansion())
14797 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14798 RelocateToHomebind();
14802 // NOW player must have valid map
14803 // load the player's map here if it's not already loaded
14804 SetMap(sMapMgr.CreateMap(GetMapId(), this));
14806 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14807 if(GetInstanceId() && !sInstanceSaveMgr.GetInstanceSave(GetInstanceId()))
14809 AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(GetMapId());
14810 if(at)
14811 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14812 else
14813 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());
14816 SaveRecallPosition();
14818 time_t now = time(NULL);
14819 time_t logoutTime = time_t(fields[23].GetUInt64());
14821 // since last logout (in seconds)
14822 uint64 time_diff = uint64(now - logoutTime);
14824 // set value, including drunk invisibility detection
14825 // calculate sobering. after 15 minutes logged out, the player will be sober again
14826 float soberFactor;
14827 if(time_diff > 15*MINUTE)
14828 soberFactor = 0;
14829 else
14830 soberFactor = 1-time_diff/(15.0f*MINUTE);
14831 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14832 SetDrunkValue(newDrunkenValue);
14834 m_rest_bonus = fields[22].GetFloat();
14835 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14836 float bubble0 = 0.031;
14837 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14838 float bubble1 = 0.125;
14840 if(time_diff > 0)
14842 float bubble = fields[24].GetUInt32() > 0
14843 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14844 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14846 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14849 m_cinematic = fields[19].GetUInt32();
14850 m_Played_time[PLAYED_TIME_TOTAL]= fields[20].GetUInt32();
14851 m_Played_time[PLAYED_TIME_LEVEL]= fields[21].GetUInt32();
14853 m_resetTalentsCost = fields[25].GetUInt32();
14854 m_resetTalentsTime = time_t(fields[26].GetUInt64());
14856 // reserve some flags
14857 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14859 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14860 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14862 m_taxi.LoadTaxiMask( fields[18].GetString() ); // must be before InitTaxiNodesForLevel
14864 uint32 extraflags = fields[32].GetUInt32();
14866 m_stableSlots = fields[33].GetUInt32();
14867 if(m_stableSlots > MAX_PET_STABLES)
14869 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14870 m_stableSlots = MAX_PET_STABLES;
14873 m_atLoginFlags = fields[34].GetUInt32();
14875 // Honor system
14876 // Update Honor kills data
14877 m_lastHonorUpdateTime = logoutTime;
14878 UpdateHonorFields();
14880 m_deathExpireTime = (time_t)fields[37].GetUInt64();
14881 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14882 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14884 std::string taxi_nodes = fields[38].GetCppString();
14886 delete result;
14888 // clear channel spell data (if saved at channel spell casting)
14889 SetChannelObjectGUID(0);
14890 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14892 // clear charm/summon related fields
14893 SetCharm(NULL);
14894 SetPet(NULL);
14895 SetTargetGUID(0);
14896 SetChannelObjectGUID(0);
14897 SetCharmerGUID(0);
14898 SetOwnerGUID(0);
14899 SetCreatorGUID(0);
14901 // reset some aura modifiers before aura apply
14902 SetFarSightGUID(0);
14903 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14904 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14906 // cleanup aura list explicitly before skill load wher some spells can be applied
14907 RemoveAllAuras();
14909 _LoadSkills(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS));
14911 // make sure the unit is considered out of combat for proper loading
14912 ClearInCombat();
14914 // make sure the unit is considered not in duel for proper loading
14915 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14916 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14918 // remember loaded power/health values to restore after stats initialization and modifier applying
14919 uint32 savedHealth = GetHealth();
14920 uint32 savedPower[MAX_POWERS];
14921 for(uint32 i = 0; i < MAX_POWERS; ++i)
14922 savedPower[i] = GetPower(Powers(i));
14924 // reset stats before loading any modifiers
14925 InitStatsForLevel();
14926 InitTaxiNodesForLevel();
14927 InitGlyphsForLevel();
14928 InitRunes();
14930 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14932 // Mail
14933 _LoadMail();
14935 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14936 _LoadGlyphAuras();
14938 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14939 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14940 m_deathState = DEAD;
14942 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14944 // after spell load, learn rewarded spell if need also
14945 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14946 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14948 // after spell and quest load
14949 InitTalentForLevel();
14950 learnDefaultSpells();
14952 // must be before inventory (some items required reputation check)
14953 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14955 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14957 // update items with duration and realtime
14958 UpdateItemDuration(time_diff, true);
14960 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14962 // unread mails and next delivery time, actual mails not loaded
14963 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14965 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14967 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14968 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14969 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14971 if(!HasTitle(curTitle))
14972 SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
14975 // Not finish taxi flight path
14976 if(m_bgData.HasTaxiPath())
14978 m_taxi.ClearTaxiDestinations();
14979 for (int i = 0; i < 2; ++i)
14980 m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
14982 else if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14984 // problems with taxi path loading
14985 TaxiNodesEntry const* nodeEntry = NULL;
14986 if(uint32 node_id = m_taxi.GetTaxiSource())
14987 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14989 if(!nodeEntry) // don't know taxi start node, to homebind
14991 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14992 RelocateToHomebind();
14994 else // have start node, to it
14996 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14997 SetLocationMapId(nodeEntry->map_id);
14998 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
15001 //we can be relocated from taxi and still have an outdated Map pointer!
15002 //so we need to get a new Map pointer!
15003 SetMap(sMapMgr.CreateMap(GetMapId(), this));
15004 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
15006 m_taxi.ClearTaxiDestinations();
15009 if(uint32 node_id = m_taxi.GetTaxiSource())
15011 // save source node as recall coord to prevent recall and fall from sky
15012 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
15013 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
15014 m_recallMap = nodeEntry->map_id;
15015 m_recallX = nodeEntry->x;
15016 m_recallY = nodeEntry->y;
15017 m_recallZ = nodeEntry->z;
15019 // flight will started later
15022 // has to be called after last Relocate() in Player::LoadFromDB
15023 SetFallInformation(0, GetPositionZ());
15025 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
15027 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
15028 // Do now before stats re-calculation cleanup for ghost state unexpected auras
15029 if(!isAlive())
15030 RemoveAllAurasOnDeath();
15032 //apply all stat bonuses from items and auras
15033 SetCanModifyStats(true);
15034 UpdateAllStats();
15036 // restore remembered power/health values (but not more max values)
15037 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
15038 for(uint32 i = 0; i < MAX_POWERS; ++i)
15039 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
15041 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
15042 outDebugValues();
15044 // GM state
15045 if(GetSession()->GetSecurity() > SEC_PLAYER)
15047 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
15049 default:
15050 case 0: break; // disable
15051 case 1: SetGameMaster(true); break; // enable
15052 case 2: // save state
15053 if(extraflags & PLAYER_EXTRA_GM_ON)
15054 SetGameMaster(true);
15055 break;
15058 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
15060 default:
15061 case 0: SetGMVisible(false); break; // invisible
15062 case 1: break; // visible
15063 case 2: // save state
15064 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
15065 SetGMVisible(false);
15066 break;
15069 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
15071 default:
15072 case 0: break; // disable
15073 case 1: SetAcceptTicket(true); break; // enable
15074 case 2: // save state
15075 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
15076 SetAcceptTicket(true);
15077 break;
15080 switch(sWorld.getConfig(CONFIG_GM_CHAT))
15082 default:
15083 case 0: break; // disable
15084 case 1: SetGMChat(true); break; // enable
15085 case 2: // save state
15086 if(extraflags & PLAYER_EXTRA_GM_CHAT)
15087 SetGMChat(true);
15088 break;
15091 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
15093 default:
15094 case 0: break; // disable
15095 case 1: SetAcceptWhispers(true); break; // enable
15096 case 2: // save state
15097 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
15098 SetAcceptWhispers(true);
15099 break;
15103 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
15105 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
15106 m_achievementMgr.CheckAllAchievementCriteria();
15108 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
15110 return true;
15113 bool Player::isAllowedToLoot(Creature* creature)
15115 if(Player* recipient = creature->GetLootRecipient())
15117 if (recipient == this)
15118 return true;
15119 if( Group* otherGroup = recipient->GetGroup())
15121 Group* thisGroup = GetGroup();
15122 if(!thisGroup)
15123 return false;
15124 return thisGroup == otherGroup;
15126 return false;
15128 else
15129 // prevent other players from looting if the recipient got disconnected
15130 return !creature->hasLootRecipient();
15133 void Player::_LoadActions(QueryResult *result)
15135 m_actionButtons.clear();
15137 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
15139 if(result)
15143 Field *fields = result->Fetch();
15145 uint8 button = fields[0].GetUInt8();
15146 uint32 action = fields[1].GetUInt32();
15147 uint8 type = fields[2].GetUInt8();
15149 if(ActionButton* ab = addActionButton(button, action, type))
15150 ab->uState = ACTIONBUTTON_UNCHANGED;
15151 else
15153 sLog.outError( " ...at loading, and will deleted in DB also");
15155 // Will deleted in DB at next save (it can create data until save but marked as deleted)
15156 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
15159 while( result->NextRow() );
15161 delete result;
15165 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
15167 //RemoveAllAuras(); -- some spells casted before aura load, for example in LoadSkills, aura list explcitly cleaned early
15169 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15171 if(result)
15175 Field *fields = result->Fetch();
15176 uint64 caster_guid = fields[0].GetUInt64();
15177 uint32 spellid = fields[1].GetUInt32();
15178 uint32 effindex = fields[2].GetUInt32();
15179 uint32 stackcount = fields[3].GetUInt32();
15180 int32 damage = (int32)fields[4].GetUInt32();
15181 int32 maxduration = (int32)fields[5].GetUInt32();
15182 int32 remaintime = (int32)fields[6].GetUInt32();
15183 int32 remaincharges = (int32)fields[7].GetUInt32();
15185 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
15186 if(!spellproto)
15188 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
15189 continue;
15192 if(effindex >= 3)
15194 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
15195 continue;
15198 // negative effects should continue counting down after logout
15199 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
15201 if (remaintime/IN_MILISECONDS <= int32(timediff))
15202 continue;
15204 remaintime -= timediff*IN_MILISECONDS;
15207 // prevent wrong values of remaincharges
15208 if(spellproto->procCharges)
15210 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
15211 remaincharges = spellproto->procCharges;
15213 else
15214 remaincharges = 0;
15217 for(uint32 i=0; i<stackcount; ++i)
15219 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
15220 if(!damage)
15221 damage = aura->GetModifier()->m_amount;
15223 // reset stolen single target auras
15224 if (caster_guid != GetGUID() && aura->IsSingleTarget())
15225 aura->SetIsSingleTarget(false);
15227 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
15228 AddAura(aura);
15229 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
15232 while( result->NextRow() );
15234 delete result;
15237 if(getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
15238 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
15241 void Player::_LoadGlyphAuras()
15243 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
15245 if (uint32 glyph = GetGlyph(i))
15247 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
15249 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
15251 if(gp->TypeFlags == gs->TypeFlags)
15253 CastSpell(this, gp->SpellId, true);
15254 continue;
15256 else
15257 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
15259 else
15260 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
15262 else
15263 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
15265 // On any error remove glyph
15266 SetGlyph(i, 0);
15271 void Player::LoadCorpse()
15273 if( isAlive() )
15275 sObjectAccessor.ConvertCorpseForPlayer(GetGUID());
15277 else
15279 if(Corpse *corpse = GetCorpse())
15281 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
15283 else
15285 //Prevent Dead Player login without corpse
15286 ResurrectPlayer(0.5f);
15291 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
15293 //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());
15294 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
15295 //NOTE: the "order by `bag`" is important because it makes sure
15296 //the bagMap is filled before items in the bags are loaded
15297 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
15298 //expected to be equipped before offhand items (TODO: fixme)
15300 uint32 zone = GetZoneId();
15302 if (result)
15304 std::list<Item*> problematicItems;
15306 // prevent items from being added to the queue when stored
15307 m_itemUpdateQueueBlocked = true;
15310 Field *fields = result->Fetch();
15311 uint32 bag_guid = fields[1].GetUInt32();
15312 uint8 slot = fields[2].GetUInt8();
15313 uint32 item_guid = fields[3].GetUInt32();
15314 uint32 item_id = fields[4].GetUInt32();
15316 ItemPrototype const * proto = ObjectMgr::GetItemPrototype(item_id);
15318 if(!proto)
15320 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15321 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
15322 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
15323 continue;
15326 Item *item = NewItemOrBag(proto);
15328 if(!item->LoadFromDB(item_guid, GetGUID(), result))
15330 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
15331 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15332 item->FSetState(ITEM_REMOVED);
15333 item->SaveToDB(); // it also deletes item object !
15334 continue;
15337 // not allow have in alive state item limited to another map/zone
15338 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
15340 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15341 item->FSetState(ITEM_REMOVED);
15342 item->SaveToDB(); // it also deletes item object !
15343 continue;
15346 // "Conjured items disappear if you are logged out for more than 15 minutes"
15347 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
15349 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15350 item->FSetState(ITEM_REMOVED);
15351 item->SaveToDB(); // it also deletes item object !
15352 continue;
15355 bool success = true;
15357 // the item/bag is not in a bag
15358 if (!bag_guid)
15360 item->SetContainer( NULL );
15361 item->SetSlot(slot);
15363 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
15365 ItemPosCountVec dest;
15366 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
15367 item = StoreItem(dest, item, true);
15368 else
15369 success = false;
15371 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
15373 uint16 dest;
15374 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
15375 QuickEquipItem(dest, item);
15376 else
15377 success = false;
15379 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
15381 ItemPosCountVec dest;
15382 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
15383 item = BankItem(dest, item, true);
15384 else
15385 success = false;
15388 if(success)
15390 // store bags that may contain items in them
15391 if(item->IsBag() && IsBagPos(item->GetPos()))
15392 bagMap[item_guid] = (Bag*)item;
15395 // the item/bag in a bag
15396 else
15398 item->SetSlot(NULL_SLOT);
15399 // the item is in a bag, find the bag
15400 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
15401 if(itr != bagMap.end() && slot < itr->second->GetBagSize())
15403 ItemPosCountVec dest;
15404 if( CanStoreItem( itr->second->GetSlot(), slot, dest, item, false ) == EQUIP_ERR_OK )
15405 item = StoreItem(dest, item, true);
15406 else
15407 success = false;
15409 else
15410 success = false;
15413 // item's state may have changed after stored
15414 if (success)
15415 item->SetState(ITEM_UNCHANGED, this);
15416 else
15418 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);
15419 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15420 problematicItems.push_back(item);
15422 } while (result->NextRow());
15424 delete result;
15425 m_itemUpdateQueueBlocked = false;
15427 // send by mail problematic items
15428 while(!problematicItems.empty())
15430 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
15432 // fill mail
15433 MailDraft draft(subject);
15435 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
15437 Item* item = problematicItems.front();
15438 problematicItems.pop_front();
15440 draft.AddItem(item);
15443 draft.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
15446 //if(isAlive())
15447 _ApplyAllItemMods();
15450 // load mailed item which should receive current player
15451 void Player::_LoadMailedItems(Mail *mail)
15453 // data needs to be at first place for Item::LoadFromDB
15454 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);
15455 if(!result)
15456 return;
15460 Field *fields = result->Fetch();
15461 uint32 item_guid_low = fields[1].GetUInt32();
15462 uint32 item_template = fields[2].GetUInt32();
15464 mail->AddItem(item_guid_low, item_template);
15466 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(item_template);
15468 if(!proto)
15470 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);
15471 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15472 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
15473 continue;
15476 Item *item = NewItemOrBag(proto);
15478 if(!item->LoadFromDB(item_guid_low, 0, result))
15480 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
15481 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15482 item->FSetState(ITEM_REMOVED);
15483 item->SaveToDB(); // it also deletes item object !
15484 continue;
15487 AddMItem(item);
15488 } while (result->NextRow());
15490 delete result;
15493 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
15495 //set a count of unread mails
15496 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" UI64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
15497 if (resultUnread)
15499 Field *fieldMail = resultUnread->Fetch();
15500 unReadMails = fieldMail[0].GetUInt8();
15501 delete resultUnread;
15504 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
15505 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
15506 if (resultDelivery)
15508 Field *fieldMail = resultDelivery->Fetch();
15509 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
15510 delete resultDelivery;
15514 void Player::_LoadMail()
15516 m_mail.clear();
15517 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15518 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());
15519 if(result)
15523 Field *fields = result->Fetch();
15524 Mail *m = new Mail;
15525 m->messageID = fields[0].GetUInt32();
15526 m->messageType = fields[1].GetUInt8();
15527 m->sender = fields[2].GetUInt32();
15528 m->receiver = fields[3].GetUInt32();
15529 m->subject = fields[4].GetCppString();
15530 m->itemTextId = fields[5].GetUInt32();
15531 bool has_items = fields[6].GetBool();
15532 m->expire_time = (time_t)fields[7].GetUInt64();
15533 m->deliver_time = (time_t)fields[8].GetUInt64();
15534 m->money = fields[9].GetUInt32();
15535 m->COD = fields[10].GetUInt32();
15536 m->checked = fields[11].GetUInt32();
15537 m->stationery = fields[12].GetUInt8();
15538 m->mailTemplateId = fields[13].GetInt16();
15540 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15542 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15543 m->mailTemplateId = 0;
15546 m->state = MAIL_STATE_UNCHANGED;
15548 if (has_items)
15549 _LoadMailedItems(m);
15551 m_mail.push_back(m);
15552 } while( result->NextRow() );
15553 delete result;
15557 void Player::LoadPet()
15559 //fixme: the pet should still be loaded if the player is not in world
15560 // just not added to the map
15561 if(IsInWorld())
15563 Pet *pet = new Pet;
15564 if(!pet->LoadPetFromDB(this,0,0,true))
15565 delete pet;
15569 void Player::_LoadQuestStatus(QueryResult *result)
15571 mQuestStatus.clear();
15573 uint32 slot = 0;
15575 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15576 //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());
15578 if(result)
15582 Field *fields = result->Fetch();
15584 uint32 quest_id = fields[0].GetUInt32();
15585 // used to be new, no delete?
15586 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15587 if( pQuest )
15589 // find or create
15590 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15592 uint32 qstatus = fields[1].GetUInt32();
15593 if(qstatus < MAX_QUEST_STATUS)
15594 questStatusData.m_status = QuestStatus(qstatus);
15595 else
15597 questStatusData.m_status = QUEST_STATUS_NONE;
15598 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15601 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15602 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15604 time_t quest_time = time_t(fields[4].GetUInt64());
15606 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15608 AddTimedQuest( quest_id );
15610 if (quest_time <= sWorld.GetGameTime())
15611 questStatusData.m_timer = 1;
15612 else
15613 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
15615 else
15616 quest_time = 0;
15618 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15619 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15620 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15621 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15622 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15623 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15624 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15625 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15627 questStatusData.uState = QUEST_UNCHANGED;
15629 // add to quest log
15630 if (slot < MAX_QUEST_LOG_SIZE &&
15631 ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
15632 questStatusData.m_status == QUEST_STATUS_COMPLETE ||
15633 questStatusData.m_status == QUEST_STATUS_FAILED) &&
15634 (!questStatusData.m_rewarded || pQuest->IsRepeatable())))
15636 SetQuestSlot(slot, quest_id, quest_time);
15638 if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
15639 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
15641 if (questStatusData.m_status == QUEST_STATUS_FAILED)
15642 SetQuestSlotState(slot, QUEST_STATE_FAIL);
15644 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15645 if(questStatusData.m_creatureOrGOcount[idx])
15646 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
15648 ++slot;
15651 if(questStatusData.m_rewarded)
15653 // learn rewarded spell if unknown
15654 learnQuestRewardedSpells(pQuest);
15656 // set rewarded title if any
15657 if(pQuest->GetCharTitleId())
15659 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15660 SetTitle(titleEntry);
15663 if(pQuest->GetBonusTalents())
15664 m_questRewardTalentCount += pQuest->GetBonusTalents();
15667 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15670 while( result->NextRow() );
15672 delete result;
15675 // clear quest log tail
15676 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15677 SetQuestSlot(i, 0);
15680 void Player::_LoadDailyQuestStatus(QueryResult *result)
15682 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15683 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15685 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15687 if(result)
15689 uint32 quest_daily_idx = 0;
15693 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15695 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15696 break;
15699 Field *fields = result->Fetch();
15701 uint32 quest_id = fields[0].GetUInt32();
15703 // save _any_ from daily quest times (it must be after last reset anyway)
15704 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15706 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15707 if( !pQuest )
15708 continue;
15710 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15711 ++quest_daily_idx;
15713 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15715 while( result->NextRow() );
15717 delete result;
15720 m_DailyQuestChanged = false;
15723 void Player::_LoadSpells(QueryResult *result)
15725 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15727 if(result)
15731 Field *fields = result->Fetch();
15733 addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool());
15735 while( result->NextRow() );
15737 delete result;
15741 void Player::_LoadGroup(QueryResult *result)
15743 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15744 if (result)
15746 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15747 delete result;
15749 if (Group* group = sObjectMgr.GetGroupByLeader(leaderGuid))
15751 uint8 subgroup = group->GetMemberGroup(GetGUID());
15752 SetGroup(group, subgroup);
15753 if (getLevel() >= LEVELREQUIREMENT_HEROIC)
15755 // the group leader may change the instance difficulty while the player is offline
15756 SetDungeonDifficulty(group->GetDungeonDifficulty());
15757 SetRaidDifficulty(group->GetRaidDifficulty());
15763 void Player::_LoadBoundInstances(QueryResult *result)
15765 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15766 m_boundInstances[i].clear();
15768 Group *group = GetGroup();
15770 //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));
15771 if(result)
15775 Field *fields = result->Fetch();
15776 bool perm = fields[1].GetBool();
15777 uint32 mapId = fields[2].GetUInt32();
15778 uint32 instanceId = fields[0].GetUInt32();
15779 uint8 difficulty = fields[3].GetUInt8();
15781 time_t resetTime = (time_t)fields[4].GetUInt64();
15782 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15783 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15784 // and in that case it is not used
15786 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15787 if(!mapEntry || !mapEntry->IsDungeon())
15789 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15790 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15791 continue;
15794 if(difficulty >= MAX_DIFFICULTY)
15796 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15797 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15798 continue;
15801 MapDifficulty const* mapDiff = GetMapDifficultyData(mapId,Difficulty(difficulty));
15802 if(!mapDiff)
15804 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15805 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15806 continue;
15809 if(!perm && group)
15811 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);
15812 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15813 continue;
15816 // since non permanent binds are always solo bind, they can always be reset
15817 InstanceSave *save = sInstanceSaveMgr.AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, !perm, true);
15818 if(save) BindToInstance(save, perm, true);
15819 } while(result->NextRow());
15820 delete result;
15824 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
15826 // some instances only have one difficulty
15827 MapDifficulty const* mapDiff = GetMapDifficultyData(mapid,difficulty);
15828 if(!mapDiff)
15829 return NULL;
15831 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15832 if(itr != m_boundInstances[difficulty].end())
15833 return &itr->second;
15834 else
15835 return NULL;
15838 void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
15840 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15841 UnbindInstance(itr, difficulty, unload);
15844 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
15846 if(itr != m_boundInstances[difficulty].end())
15848 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15849 itr->second.save->RemovePlayer(this); // save can become invalid
15850 m_boundInstances[difficulty].erase(itr++);
15854 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15856 if(save)
15858 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15859 if(bind.save)
15861 // update the save when the group kills a boss
15862 if(permanent != bind.perm || save != bind.save)
15863 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());
15865 else
15866 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15868 if(bind.save != save)
15870 if(bind.save) bind.save->RemovePlayer(this);
15871 save->AddPlayer(this);
15874 if(permanent) save->SetCanReset(false);
15876 bind.save = save;
15877 bind.perm = permanent;
15878 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());
15879 return &bind;
15881 else
15882 return NULL;
15885 void Player::SendRaidInfo()
15887 uint32 counter = 0;
15889 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15891 size_t p_counter = data.wpos();
15892 data << uint32(counter); // placeholder
15894 time_t now = time(NULL);
15896 for(int i = 0; i < MAX_DIFFICULTY; ++i)
15898 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15900 if(itr->second.perm)
15902 InstanceSave *save = itr->second.save;
15903 data << uint32(save->GetMapId()); // map id
15904 data << uint32(save->GetDifficulty()); // difficulty
15905 data << uint64(save->GetInstanceId()); // instance id
15906 data << uint8(1); // expired = 0
15907 data << uint8(0); // extended = 1
15908 data << uint32(save->GetResetTime() - now); // reset time
15909 ++counter;
15913 data.put<uint32>(p_counter, counter);
15914 GetSession()->SendPacket(&data);
15918 - called on every successful teleportation to a map
15920 void Player::SendSavedInstances()
15922 bool hasBeenSaved = false;
15923 WorldPacket data;
15925 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15927 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15929 if(itr->second.perm) // only permanent binds are sent
15931 hasBeenSaved = true;
15932 break;
15937 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15938 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15939 data << uint32(hasBeenSaved);
15940 GetSession()->SendPacket(&data);
15942 if(!hasBeenSaved)
15943 return;
15945 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15947 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15949 if(itr->second.perm)
15951 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15952 data << uint32(itr->second.save->GetMapId());
15953 GetSession()->SendPacket(&data);
15959 /// convert the player's binds to the group
15960 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15962 bool has_binds = false;
15963 bool has_solo = false;
15965 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15966 assert(player_guid);
15968 // copy all binds to the group, when changing leader it's assumed the character
15969 // will not have any solo binds
15971 if(player)
15973 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15975 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15977 has_binds = true;
15978 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15979 // permanent binds are not removed
15980 if(!itr->second.perm)
15982 // increments itr in call
15983 player->UnbindInstance(itr, Difficulty(i), true);
15984 has_solo = true;
15986 else
15987 ++itr;
15992 // if the player's not online we don't know what binds it has
15993 if(!player || !group || has_binds) CharacterDatabase.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid));
15994 // the following should not get executed when changing leaders
15995 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15998 bool Player::_LoadHomeBind(QueryResult *result)
16000 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
16001 if(!info)
16003 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
16004 return false;
16007 bool ok = false;
16008 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
16009 if (result)
16011 Field *fields = result->Fetch();
16012 m_homebindMapId = fields[0].GetUInt32();
16013 m_homebindZoneId = fields[1].GetUInt16();
16014 m_homebindX = fields[2].GetFloat();
16015 m_homebindY = fields[3].GetFloat();
16016 m_homebindZ = fields[4].GetFloat();
16017 delete result;
16019 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
16021 // accept saved data only for valid position (and non instanceable), and accessable
16022 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
16023 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
16025 ok = true;
16027 else
16028 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
16031 if(!ok)
16033 m_homebindMapId = info->mapId;
16034 m_homebindZoneId = info->zoneId;
16035 m_homebindX = info->positionX;
16036 m_homebindY = info->positionY;
16037 m_homebindZ = info->positionZ;
16039 CharacterDatabase.PExecute("INSERT INTO character_homebind (guid,map,zone,position_x,position_y,position_z) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GetGUIDLow(), m_homebindMapId, (uint32)m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
16042 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
16043 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
16045 return true;
16048 /*********************************************************/
16049 /*** SAVE SYSTEM ***/
16050 /*********************************************************/
16052 void Player::SaveToDB()
16054 // we should assure this: assert((m_nextSave != sWorld.getConfig(CONFIG_INTERVAL_SAVE)));
16055 // delay auto save at any saves (manual, in code, or autosave)
16056 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
16058 //lets allow only players in world to be saved
16059 if(IsBeingTeleportedFar())
16061 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
16062 return;
16065 // first save/honor gain after midnight will also update the player's honor fields
16066 UpdateHonorFields();
16068 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
16069 outDebugValues();
16071 CharacterDatabase.BeginTransaction();
16073 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
16075 std::string sql_name = m_name;
16076 CharacterDatabase.escape_string(sql_name);
16078 std::ostringstream ss;
16079 ss << "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
16080 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
16081 "taximask, online, cinematic, "
16082 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
16083 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
16084 "death_expire_time, taxi_path, arena_pending_points) VALUES ("
16085 << GetGUIDLow() << ", "
16086 << GetSession()->GetAccountId() << ", '"
16087 << sql_name << "', "
16088 << (uint32)getRace() << ", "
16089 << (uint32)getClass() << ", "
16090 << (uint32)getGender() << ", "
16091 << getLevel() << ", "
16092 << GetUInt32Value(PLAYER_XP) << ", "
16093 << GetMoney() << ", "
16094 << GetUInt32Value(PLAYER_BYTES) << ", "
16095 << GetUInt32Value(PLAYER_BYTES_2) << ", "
16096 << GetUInt32Value(PLAYER_FLAGS) << ", ";
16098 if(!IsBeingTeleported())
16100 ss << GetMapId() << ", "
16101 << (uint32)GetDungeonDifficulty() << ", "
16102 << finiteAlways(GetPositionX()) << ", "
16103 << finiteAlways(GetPositionY()) << ", "
16104 << finiteAlways(GetPositionZ()) << ", "
16105 << finiteAlways(GetOrientation()) << ", '";
16107 else
16109 ss << GetTeleportDest().mapid << ", "
16110 << (uint32)GetDungeonDifficulty() << ", "
16111 << finiteAlways(GetTeleportDest().coord_x) << ", "
16112 << finiteAlways(GetTeleportDest().coord_y) << ", "
16113 << finiteAlways(GetTeleportDest().coord_z) << ", "
16114 << finiteAlways(GetTeleportDest().orientation) << ", '";
16117 uint16 i;
16118 for( i = 0; i < m_valuesCount; ++i )
16120 ss << GetUInt32Value(i) << " ";
16123 ss << "', ";
16125 ss << m_taxi << ", "; // string with TaxiMaskSize numbers
16127 ss << (IsInWorld() ? 1 : 0) << ", ";
16129 ss << m_cinematic << ", ";
16131 ss << m_Played_time[PLAYED_TIME_TOTAL] << ", ";
16132 ss << m_Played_time[PLAYED_TIME_LEVEL] << ", ";
16134 ss << finiteAlways(m_rest_bonus) << ", ";
16135 ss << (uint64)time(NULL) << ", ";
16136 ss << (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0) << ", ";
16137 //save, far from tavern/city
16138 //save, but in tavern/city
16139 ss << m_resetTalentsCost << ", ";
16140 ss << (uint64)m_resetTalentsTime << ", ";
16142 ss << finiteAlways(m_movementInfo.t_x) << ", ";
16143 ss << finiteAlways(m_movementInfo.t_y) << ", ";
16144 ss << finiteAlways(m_movementInfo.t_z) << ", ";
16145 ss << finiteAlways(m_movementInfo.t_o) << ", ";
16146 if (m_transport)
16147 ss << m_transport->GetGUIDLow();
16148 else
16149 ss << "0";
16150 ss << ", ";
16152 ss << m_ExtraFlags << ", ";
16154 ss << uint32(m_stableSlots) << ", "; // to prevent save uint8 as char
16156 ss << uint32(m_atLoginFlags) << ", ";
16158 ss << GetZoneId() << ", ";
16160 ss << (uint64)m_deathExpireTime << ", '";
16162 ss << m_taxi.SaveTaxiDestinationsToString() << "', ";
16163 ss << "'0' "; // arena_pending_points
16164 ss << ")";
16166 CharacterDatabase.Execute( ss.str().c_str() );
16168 if(m_mailsUpdated) //save mails only when needed
16169 _SaveMail();
16171 _SaveBGData();
16172 _SaveInventory();
16173 _SaveQuestStatus();
16174 _SaveDailyQuestStatus();
16175 _SaveSpells();
16176 _SaveSpellCooldowns();
16177 _SaveActions();
16178 _SaveAuras();
16179 _SaveSkills();
16180 m_achievementMgr.SaveToDB();
16181 m_reputationMgr.SaveToDB();
16182 _SaveEquipmentSets();
16183 GetSession()->SaveTutorialsData(); // changed only while character in game
16185 CharacterDatabase.CommitTransaction();
16187 // save pet (hunter pet level and experience and all type pets health/mana).
16188 if(Pet* pet = GetPet())
16189 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
16192 // fast save function for item/money cheating preventing - save only inventory and money state
16193 void Player::SaveInventoryAndGoldToDB()
16195 _SaveInventory();
16196 SaveGoldToDB();
16199 void Player::SaveGoldToDB()
16201 CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
16204 void Player::_SaveActions()
16206 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
16208 switch (itr->second.uState)
16210 case ACTIONBUTTON_NEW:
16211 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type) VALUES ('%u', '%u', '%u', '%u')",
16212 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.GetAction(), (uint32)itr->second.GetType() );
16213 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16214 ++itr;
16215 break;
16216 case ACTIONBUTTON_CHANGED:
16217 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' ",
16218 (uint32)itr->second.GetAction(), (uint32)itr->second.GetType(), GetGUIDLow(), (uint32)itr->first );
16219 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16220 ++itr;
16221 break;
16222 case ACTIONBUTTON_DELETED:
16223 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
16224 m_actionButtons.erase(itr++);
16225 break;
16226 default:
16227 ++itr;
16228 break;
16233 void Player::_SaveAuras()
16235 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
16237 AuraMap const& auras = GetAuras();
16239 if (auras.empty())
16240 return;
16242 spellEffectPair lastEffectPair = auras.begin()->first;
16243 uint32 stackCounter = 1;
16245 /* copied following sql-code partly from achievementmgr */
16246 bool first_round = true;
16247 std::ostringstream ss;
16248 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
16250 if(itr == auras.end() || lastEffectPair != itr->first)
16252 AuraMap::const_iterator itr2 = itr;
16253 // save previous spellEffectPair to db
16254 itr2--;
16256 //skip all auras from spells that are passive
16257 //do not save single target auras (unless they were cast by the player)
16258 if (!itr2->second->IsPassive() && (itr2->second->GetCasterGUID() == GetGUID() || !itr2->second->IsSingleTarget()))
16260 if (first_round)
16262 ss << "INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges)VALUES ";
16263 first_round = false;
16265 // next new/changed record prefix
16266 else
16267 ss << ", ";
16269 ss << "("<< GetGUIDLow() << "," << itr2->second->GetCasterGUID() << ","
16270 << (uint32)itr2->second->GetId() << "," << (uint32)itr2->second->GetEffIndex() << ","
16271 << stackCounter << "," << itr2->second->GetModifier()->m_amount << ","
16272 <<int(itr2->second->GetAuraMaxDuration()) << "," << int(itr2->second->GetAuraDuration()) << ","
16273 << int(itr2->second->GetAuraCharges()) << ")";
16276 if(itr == auras.end())
16277 break;
16280 if (lastEffectPair == itr->first)
16281 stackCounter++;
16282 else
16284 lastEffectPair = itr->first;
16285 stackCounter = 1;
16289 // if something changed execute
16290 if (!first_round)
16291 CharacterDatabase.Execute( ss.str().c_str() );
16294 void Player::_SaveInventory()
16296 // force items in buyback slots to new state
16297 // and remove those that aren't already
16298 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
16300 Item *item = m_items[i];
16301 if (!item || item->GetState() == ITEM_NEW) continue;
16302 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16303 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
16304 m_items[i]->FSetState(ITEM_NEW);
16307 // update enchantment durations
16308 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
16310 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
16313 // if no changes
16314 if (m_itemUpdateQueue.empty()) return;
16316 // do not save if the update queue is corrupt
16317 bool error = false;
16318 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16320 Item *item = m_itemUpdateQueue[i];
16321 if(!item || item->GetState() == ITEM_REMOVED) continue;
16322 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
16324 if (test == NULL)
16326 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());
16327 error = true;
16329 else if (test != item)
16331 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());
16332 error = true;
16336 if (error)
16338 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
16339 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
16340 return;
16343 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16345 Item *item = m_itemUpdateQueue[i];
16346 if(!item) continue;
16348 Bag *container = item->GetContainer();
16349 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
16351 switch(item->GetState())
16353 case ITEM_NEW:
16354 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());
16355 break;
16356 case ITEM_CHANGED:
16357 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());
16358 break;
16359 case ITEM_REMOVED:
16360 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16361 break;
16362 case ITEM_UNCHANGED:
16363 break;
16366 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
16368 m_itemUpdateQueue.clear();
16371 void Player::_SaveMail()
16373 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
16375 Mail *m = (*itr);
16376 if (m->state == MAIL_STATE_CHANGED)
16378 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'",
16379 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
16380 if(m->removedItems.size())
16382 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
16383 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
16384 m->removedItems.clear();
16386 m->state = MAIL_STATE_UNCHANGED;
16388 else if (m->state == MAIL_STATE_DELETED)
16390 if (m->HasItems())
16391 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
16392 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
16393 if (m->itemTextId)
16394 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
16395 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
16396 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
16400 //deallocate deleted mails...
16401 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
16403 if ((*itr)->state == MAIL_STATE_DELETED)
16405 Mail* m = *itr;
16406 m_mail.erase(itr);
16407 delete m;
16408 itr = m_mail.begin();
16410 else
16411 ++itr;
16414 m_mailsUpdated = false;
16417 void Player::_SaveQuestStatus()
16419 // we don't need transactions here.
16420 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
16422 switch (i->second.uState)
16424 case QUEST_NEW :
16425 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
16426 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
16427 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]);
16428 break;
16429 case QUEST_CHANGED :
16430 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' ",
16431 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 );
16432 break;
16433 case QUEST_UNCHANGED:
16434 break;
16436 i->second.uState = QUEST_UNCHANGED;
16440 void Player::_SaveDailyQuestStatus()
16442 if(!m_DailyQuestChanged)
16443 return;
16445 m_DailyQuestChanged = false;
16447 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
16449 // we don't need transactions here.
16450 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
16451 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
16452 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
16453 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
16454 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
16458 void Player::_SaveSkills()
16460 // we don't need transactions here.
16461 for( SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); )
16463 if(itr->second.uState == SKILL_UNCHANGED)
16465 ++itr;
16466 continue;
16469 if(itr->second.uState == SKILL_DELETED)
16471 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), itr->first );
16472 mSkillStatus.erase(itr++);
16473 continue;
16476 uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos));
16477 uint16 value = SKILL_VALUE(valueData);
16478 uint16 max = SKILL_MAX(valueData);
16480 switch (itr->second.uState)
16482 case SKILL_NEW:
16483 CharacterDatabase.PExecute("INSERT INTO character_skills (guid, skill, value, max) VALUES ('%u', '%u', '%u', '%u')",
16484 GetGUIDLow(), itr->first, value, max);
16485 break;
16486 case SKILL_CHANGED:
16487 CharacterDatabase.PExecute("UPDATE character_skills SET value = '%u',max = '%u'WHERE guid = '%u' AND skill = '%u' ",
16488 value, max, GetGUIDLow(), itr->first );
16489 break;
16491 itr->second.uState = SKILL_UNCHANGED;
16493 ++itr;
16497 void Player::_SaveSpells()
16499 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
16501 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
16502 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
16504 // add only changed/new not dependent spells
16505 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
16506 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);
16508 if (itr->second->state == PLAYERSPELL_REMOVED)
16510 delete itr->second;
16511 m_spells.erase(itr++);
16513 else
16515 itr->second->state = PLAYERSPELL_UNCHANGED;
16516 ++itr;
16522 void Player::outDebugValues() const
16524 if(!sLog.IsOutDebug()) // optimize disabled debug output
16525 return;
16527 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
16528 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
16529 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
16530 sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
16531 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
16532 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
16533 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
16534 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
16535 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
16536 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
16537 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
16538 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
16541 /*********************************************************/
16542 /*** FLOOD FILTER SYSTEM ***/
16543 /*********************************************************/
16545 void Player::UpdateSpeakTime()
16547 // ignore chat spam protection for GMs in any mode
16548 if(GetSession()->GetSecurity() > SEC_PLAYER)
16549 return;
16551 time_t current = time (NULL);
16552 if(m_speakTime > current)
16554 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
16555 if(!max_count)
16556 return;
16558 ++m_speakCount;
16559 if(m_speakCount >= max_count)
16561 // prevent overwrite mute time, if message send just before mutes set, for example.
16562 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
16563 if(GetSession()->m_muteTime < new_mute)
16564 GetSession()->m_muteTime = new_mute;
16566 m_speakCount = 0;
16569 else
16570 m_speakCount = 0;
16572 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
16575 bool Player::CanSpeak() const
16577 return GetSession()->m_muteTime <= time (NULL);
16580 /*********************************************************/
16581 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16582 /*********************************************************/
16584 void Player::SendAttackSwingNotInRange()
16586 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16587 GetSession()->SendPacket( &data );
16590 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16592 std::ostringstream ss;
16593 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16594 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16595 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16596 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16597 sLog.outDebug("%s", ss.str().c_str());
16598 CharacterDatabase.Execute(ss.str().c_str());
16601 void Player::SaveDataFieldToDB()
16603 std::ostringstream ss;
16604 ss<<"UPDATE characters SET data='";
16606 for(uint16 i = 0; i < m_valuesCount; ++i )
16608 ss << GetUInt32Value(i) << " ";
16610 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16612 CharacterDatabase.Execute(ss.str().c_str());
16615 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16617 std::ostringstream ss2;
16618 ss2<<"UPDATE characters SET data='";
16619 int i=0;
16620 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16622 ss2<<tokens[i]<<" ";
16624 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16626 return CharacterDatabase.Execute(ss2.str().c_str());
16629 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16631 char buf[11];
16632 snprintf(buf,11,"%u",value);
16634 if(index >= tokens.size())
16635 return;
16637 tokens[index] = buf;
16640 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16642 Tokens tokens;
16643 if(!LoadValuesArrayFromDB(tokens,guid))
16644 return;
16646 if(index >= tokens.size())
16647 return;
16649 char buf[11];
16650 snprintf(buf,11,"%u",value);
16651 tokens[index] = buf;
16653 SaveValuesArrayInDB(tokens,guid);
16656 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16658 uint32 temp;
16659 memcpy(&temp, &value, sizeof(value));
16660 Player::SetUInt32ValueInDB(index, temp, guid);
16663 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16665 // 0
16666 QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
16667 if(!result)
16668 return;
16670 Field* fields = result->Fetch();
16672 uint32 player_bytes2 = fields[0].GetUInt32();
16673 player_bytes2 &= ~0xFF;
16674 player_bytes2 |= facialHair;
16676 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));
16678 delete result;
16681 void Player::SendAttackSwingDeadTarget()
16683 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16684 GetSession()->SendPacket( &data );
16687 void Player::SendAttackSwingCantAttack()
16689 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16690 GetSession()->SendPacket( &data );
16693 void Player::SendAttackSwingCancelAttack()
16695 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16696 GetSession()->SendPacket( &data );
16699 void Player::SendAttackSwingBadFacingAttack()
16701 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16702 GetSession()->SendPacket( &data );
16705 void Player::SendAutoRepeatCancel(Unit *target)
16707 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
16708 data.append(target->GetPackGUID()); // may be it's target guid
16709 GetSession()->SendPacket( &data );
16712 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16714 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16715 data << Area;
16716 data << Experience;
16717 GetSession()->SendPacket(&data);
16720 void Player::SendDungeonDifficulty(bool IsInGroup)
16722 uint8 val = 0x00000001;
16723 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16724 data << (uint32)GetDungeonDifficulty();
16725 data << uint32(val);
16726 data << uint32(IsInGroup);
16727 GetSession()->SendPacket(&data);
16730 void Player::SendRaidDifficulty(bool IsInGroup)
16732 uint8 val = 0x00000001;
16733 WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
16734 data << uint32(GetRaidDifficulty());
16735 data << uint32(val);
16736 data << uint32(IsInGroup);
16737 GetSession()->SendPacket(&data);
16740 void Player::SendResetFailedNotify(uint32 mapid)
16742 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16743 data << uint32(mapid);
16744 GetSession()->SendPacket(&data);
16747 /// Reset all solo instances and optionally send a message on success for each
16748 void Player::ResetInstances(uint8 method, bool isRaid)
16750 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16752 // we assume that when the difficulty changes, all instances that can be reset will be
16753 Difficulty diff = GetDifficulty(isRaid);
16755 for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
16757 InstanceSave *p = itr->second.save;
16758 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16759 if(!entry || entry->IsRaid() != isRaid || !p->CanReset())
16761 ++itr;
16762 continue;
16765 if(method == INSTANCE_RESET_ALL)
16767 // the "reset all instances" method can only reset normal maps
16768 if(entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
16770 ++itr;
16771 continue;
16775 // if the map is loaded, reset it
16776 Map *map = sMapMgr.FindMap(p->GetMapId(), p->GetInstanceId());
16777 if(map && map->IsDungeon())
16778 ((InstanceMap*)map)->Reset(method);
16780 // since this is a solo instance there should not be any players inside
16781 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16782 SendResetInstanceSuccess(p->GetMapId());
16784 p->DeleteFromDB();
16785 m_boundInstances[diff].erase(itr++);
16787 // the following should remove the instance save from the manager and delete it as well
16788 p->RemovePlayer(this);
16792 void Player::SendResetInstanceSuccess(uint32 MapId)
16794 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16795 data << MapId;
16796 GetSession()->SendPacket(&data);
16799 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16801 // TODO: find what other fail reasons there are besides players in the instance
16802 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16803 data << reason;
16804 data << MapId;
16805 GetSession()->SendPacket(&data);
16808 /*********************************************************/
16809 /*** Update timers ***/
16810 /*********************************************************/
16812 ///checks the 15 afk reports per 5 minutes limit
16813 void Player::UpdateAfkReport(time_t currTime)
16815 if(m_bgData.bgAfkReportedTimer <= currTime)
16817 m_bgData.bgAfkReportedCount = 0;
16818 m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
16822 void Player::UpdateContestedPvP(uint32 diff)
16824 if(!m_contestedPvPTimer||isInCombat())
16825 return;
16826 if(m_contestedPvPTimer <= diff)
16828 ResetContestedPvP();
16830 else
16831 m_contestedPvPTimer -= diff;
16834 void Player::UpdatePvPFlag(time_t currTime)
16836 if(!IsPvP())
16837 return;
16838 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16839 return;
16841 UpdatePvP(false);
16844 void Player::UpdateDuelFlag(time_t currTime)
16846 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16847 return;
16849 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16850 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16852 duel->startTimer = 0;
16853 duel->startTime = currTime;
16854 duel->opponent->duel->startTimer = 0;
16855 duel->opponent->duel->startTime = currTime;
16858 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16860 if(!pet)
16861 pet = GetPet();
16863 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16864 return;
16866 // not save secondary permanent pet as current
16867 if (pet && m_temporaryUnsummonedPetNumber != pet->GetCharmInfo()->GetPetNumber() && mode == PET_SAVE_AS_CURRENT)
16868 mode = PET_SAVE_NOT_IN_SLOT;
16870 if(returnreagent && pet && mode != PET_SAVE_AS_CURRENT)
16872 //returning of reagents only for players, so best done here
16873 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16874 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16876 if(spellInfo)
16878 for(uint32 i = 0; i < 7; ++i)
16880 if(spellInfo->Reagent[i] > 0)
16882 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16883 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16884 if( msg == EQUIP_ERR_OK )
16886 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16887 if(IsInWorld())
16888 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16895 // only if current pet in slot
16896 switch(pet->getPetType())
16898 case MINI_PET:
16899 m_miniPet = 0;
16900 break;
16901 case GUARDIAN_PET:
16902 RemoveGuardian(pet);
16903 break;
16904 default:
16905 if(GetPetGUID() == pet->GetGUID())
16906 SetPet(NULL);
16907 break;
16910 pet->CombatStop();
16912 pet->SavePetToDB(mode);
16914 pet->AddObjectToRemoveList();
16915 pet->m_removed = true;
16917 if(pet->isControlled())
16919 RemovePetActionBar();
16921 if(GetGroup())
16922 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16926 void Player::RemoveMiniPet()
16928 if(Pet* pet = GetMiniPet())
16930 pet->Remove(PET_SAVE_AS_DELETED);
16931 m_miniPet = 0;
16935 Pet* Player::GetMiniPet()
16937 if(!m_miniPet)
16938 return NULL;
16939 return GetMap()->GetPet(m_miniPet);
16942 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16944 *data << (uint8)msgtype;
16945 *data << (uint32)language;
16946 *data << (uint64)GetGUID();
16947 *data << (uint32)language; //language 2.1.0 ?
16948 *data << (uint64)GetGUID();
16949 *data << (uint32)(text.length()+1);
16950 *data << text;
16951 *data << (uint8)chatTag();
16954 void Player::Say(const std::string& text, const uint32 language)
16956 WorldPacket data(SMSG_MESSAGECHAT, 200);
16957 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16958 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16961 void Player::Yell(const std::string& text, const uint32 language)
16963 WorldPacket data(SMSG_MESSAGECHAT, 200);
16964 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16965 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16968 void Player::TextEmote(const std::string& text)
16970 WorldPacket data(SMSG_MESSAGECHAT, 200);
16971 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16972 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16975 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16977 if (language != LANG_ADDON) // if not addon data
16978 language = LANG_UNIVERSAL; // whispers should always be readable
16980 Player *rPlayer = sObjectMgr.GetPlayer(receiver);
16982 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16983 if(!rPlayer->isDND() || isGameMaster())
16985 WorldPacket data(SMSG_MESSAGECHAT, 200);
16986 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16987 rPlayer->GetSession()->SendPacket(&data);
16989 // not send confirmation for addon messages
16990 if (language != LANG_ADDON)
16992 data.Initialize(SMSG_MESSAGECHAT, 200);
16993 rPlayer->BuildPlayerChat(&data, CHAT_MSG_WHISPER_INFORM, text, language);
16994 GetSession()->SendPacket(&data);
16997 else
16999 // announce to player that player he is whispering to is dnd and cannot receive his message
17000 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
17003 if(!isAcceptWhispers())
17005 SetAcceptWhispers(true);
17006 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
17009 // announce to player that player he is whispering to is afk
17010 if(rPlayer->isAFK())
17011 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
17013 // if player whisper someone, auto turn of dnd to be able to receive an answer
17014 if(isDND() && !rPlayer->isGameMaster())
17015 ToggleDND();
17018 void Player::PetSpellInitialize()
17020 Pet* pet = GetPet();
17022 if(!pet)
17023 return;
17025 sLog.outDebug("Pet Spells Groups");
17027 CharmInfo *charmInfo = pet->GetCharmInfo();
17029 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17030 data << uint64(pet->GetGUID());
17031 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
17032 data << uint32(0);
17033 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17035 // action bar loop
17036 charmInfo->BuildActionBar(&data);
17038 size_t spellsCountPos = data.wpos();
17040 // spells count
17041 uint8 addlist = 0;
17042 data << uint8(addlist); // placeholder
17044 if (pet->IsPermanentPetFor(this))
17046 // spells loop
17047 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
17049 if(itr->second.state == PETSPELL_REMOVED)
17050 continue;
17052 data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
17053 ++addlist;
17057 data.put<uint8>(spellsCountPos, addlist);
17059 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
17060 data << uint8(cooldownsCount);
17062 time_t curTime = time(NULL);
17064 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
17066 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
17068 data << uint32(itr->first); // spellid
17069 data << uint16(0); // spell category?
17070 data << uint32(cooldown); // cooldown
17071 data << uint32(0); // category cooldown
17074 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
17076 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
17078 data << uint32(itr->first); // spellid
17079 data << uint16(0); // spell category?
17080 data << uint32(0); // cooldown
17081 data << uint32(cooldown); // category cooldown
17084 GetSession()->SendPacket(&data);
17087 void Player::SendPetGUIDs()
17089 if(!GetPetGUID())
17090 return;
17092 // Later this function might get modified for multiple guids
17093 WorldPacket data(SMSG_PET_GUIDS, 12);
17094 data << uint32(1); // count
17095 data << uint64(GetPetGUID());
17096 GetSession()->SendPacket(&data);
17099 void Player::PossessSpellInitialize()
17101 Unit* charm = GetCharm();
17103 if(!charm)
17104 return;
17106 CharmInfo *charmInfo = charm->GetCharmInfo();
17108 if(!charmInfo)
17110 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17111 return;
17114 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17115 data << uint64(charm->GetGUID());
17116 data << uint16(0);
17117 data << uint32(0);
17118 data << uint32(0);
17120 charmInfo->BuildActionBar(&data);
17122 data << uint8(0); // spells count
17123 data << uint8(0); // cooldowns count
17125 GetSession()->SendPacket(&data);
17128 void Player::CharmSpellInitialize()
17130 Unit* charm = GetCharm();
17132 if(!charm)
17133 return;
17135 CharmInfo *charmInfo = charm->GetCharmInfo();
17136 if(!charmInfo)
17138 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17139 return;
17142 uint8 addlist = 0;
17144 if(charm->GetTypeId() != TYPEID_PLAYER)
17146 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
17148 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
17150 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17152 if(charmInfo->GetCharmSpell(i)->GetAction())
17153 ++addlist;
17158 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
17159 data << uint64(charm->GetGUID());
17160 data << uint16(0);
17161 data << uint32(0);
17163 if(charm->GetTypeId() != TYPEID_PLAYER)
17164 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17165 else
17166 data << uint8(0) << uint8(0) << uint16(0);
17168 charmInfo->BuildActionBar(&data);
17170 data << uint8(addlist);
17172 if(addlist)
17174 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17176 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
17177 if(cspell->GetAction())
17178 data << uint32(cspell->packedData);
17182 data << uint8(0); // cooldowns count
17184 GetSession()->SendPacket(&data);
17187 void Player::RemovePetActionBar()
17189 WorldPacket data(SMSG_PET_SPELLS, 8);
17190 data << uint64(0);
17191 SendDirectMessage(&data);
17194 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
17196 if (!mod || !spellInfo)
17197 return false;
17199 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
17201 // prevent apply to any spell except spell that trigger expire
17202 if(spell)
17204 if(mod->lastAffected != spell)
17205 return false;
17207 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
17208 return false;
17211 return mod->isAffectedOnSpell(spellInfo);
17214 void Player::AddSpellMod(SpellModifier* mod, bool apply)
17216 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
17218 for(int eff=0;eff<96;++eff)
17220 uint64 _mask = 0;
17221 uint32 _mask2= 0;
17222 if (eff<64) _mask = uint64(1) << (eff- 0);
17223 else _mask2= uint32(1) << (eff-64);
17224 if ( mod->mask & _mask || mod->mask2 & _mask2)
17226 int32 val = 0;
17227 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
17229 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
17230 val += (*itr)->value;
17232 val += apply ? mod->value : -(mod->value);
17233 WorldPacket data(Opcode, (1+1+4));
17234 data << uint8(eff);
17235 data << uint8(mod->op);
17236 data << int32(val);
17237 SendDirectMessage(&data);
17241 if (apply)
17242 m_spellMods[mod->op].push_back(mod);
17243 else
17245 if (mod->charges == -1)
17246 --m_SpellModRemoveCount;
17247 m_spellMods[mod->op].remove(mod);
17248 delete mod;
17252 void Player::RemoveSpellMods(Spell const* spell)
17254 if(!spell || (m_SpellModRemoveCount == 0))
17255 return;
17257 for(int i=0;i<MAX_SPELLMOD;++i)
17259 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
17261 SpellModifier *mod = *itr;
17262 ++itr;
17264 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
17266 RemoveAurasDueToSpell(mod->spellId);
17267 if (m_spellMods[i].empty())
17268 break;
17269 else
17270 itr = m_spellMods[i].begin();
17276 // send Proficiency
17277 void Player::SendProficiency(uint8 pr1, uint32 pr2)
17279 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
17280 data << pr1 << pr2;
17281 GetSession()->SendPacket (&data);
17284 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
17286 QueryResult *result = NULL;
17287 if(type==10)
17288 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17289 else
17290 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17291 if(result)
17293 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.
17294 { // and SendPetitionQueryOpcode reads data from the DB
17295 Field *fields = result->Fetch();
17296 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
17297 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
17299 // send update if charter owner in game
17300 Player* owner = sObjectMgr.GetPlayer(ownerguid);
17301 if(owner)
17302 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
17304 } while ( result->NextRow() );
17306 delete result;
17308 if(type==10)
17309 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17310 else
17311 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17314 CharacterDatabase.BeginTransaction();
17315 if(type == 10)
17317 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
17318 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
17320 else
17322 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17323 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17325 CharacterDatabase.CommitTransaction();
17328 void Player::LeaveAllArenaTeams(uint64 guid)
17330 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));
17331 if(!result)
17332 return;
17336 Field *fields = result->Fetch();
17337 uint32 at_id = fields[0].GetUInt32();
17338 if(at_id != 0)
17340 ArenaTeam * at = sObjectMgr.GetArenaTeamById(at_id);
17341 if(at)
17342 at->DelMember(guid);
17344 } while (result->NextRow());
17346 delete result;
17349 void Player::SetRestBonus (float rest_bonus_new)
17351 // Prevent resting on max level
17352 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
17353 rest_bonus_new = 0;
17355 if(rest_bonus_new < 0)
17356 rest_bonus_new = 0;
17358 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
17360 if(rest_bonus_new > rest_bonus_max)
17361 m_rest_bonus = rest_bonus_max;
17362 else
17363 m_rest_bonus = rest_bonus_new;
17365 // update data for client
17366 if(m_rest_bonus>10)
17367 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
17368 else if(m_rest_bonus<=1)
17369 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
17371 //RestTickUpdate
17372 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
17375 void Player::HandleStealthedUnitsDetection()
17377 std::list<Unit*> stealthedUnits;
17379 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17380 Cell cell(p);
17381 cell.data.Part.reserved = ALL_DISTRICT;
17382 cell.SetNoCreate();
17384 MaNGOS::AnyStealthedCheck u_check;
17385 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
17387 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
17388 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
17390 CellLock<GridReadGuard> cell_lock(cell, p);
17391 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17392 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17394 WorldObject const* viewPoint = GetViewPoint();
17396 for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
17398 if((*i)==this)
17399 continue;
17401 bool hasAtClient = HaveAtClient((*i));
17402 bool hasDetected = (*i)->isVisibleForOrDetect(this, viewPoint, true);
17404 if (hasDetected)
17406 if(!hasAtClient)
17408 (*i)->SendCreateUpdateToPlayer(this);
17409 m_clientGUIDs.insert((*i)->GetGUID());
17411 #ifdef MANGOS_DEBUG
17412 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17413 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
17414 #endif
17416 // target aura duration for caster show only if target exist at caster client
17417 // send data at target visibility change (adding to client)
17418 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
17419 SendAurasForTarget(*i);
17422 else
17424 if(hasAtClient)
17426 (*i)->DestroyForPlayer(this);
17427 m_clientGUIDs.erase((*i)->GetGUID());
17433 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
17435 if(nodes.size() < 2)
17436 return false;
17438 // 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
17439 if(GetSession()->isLogingOut() || isInCombat())
17441 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17442 data << uint32(ERR_TAXIPLAYERBUSY);
17443 GetSession()->SendPacket(&data);
17444 return false;
17447 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
17448 return false;
17450 // taximaster case
17451 if(npc)
17453 // not let cheating with start flight mounted
17454 if(IsMounted())
17456 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17457 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
17458 GetSession()->SendPacket(&data);
17459 return false;
17462 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17464 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17465 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
17466 GetSession()->SendPacket(&data);
17467 return false;
17470 // 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
17471 if(IsNonMeleeSpellCasted(false))
17473 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17474 data << uint32(ERR_TAXIPLAYERBUSY);
17475 GetSession()->SendPacket(&data);
17476 return false;
17479 // cast case or scripted call case
17480 else
17482 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
17484 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17485 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
17487 if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
17488 if (spell->m_spellInfo->Id != spellid)
17489 InterruptSpell(CURRENT_GENERIC_SPELL,false);
17491 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
17493 if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
17494 if (spell->m_spellInfo->Id != spellid)
17495 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
17498 uint32 sourcenode = nodes[0];
17500 // starting node too far away (cheat?)
17501 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
17502 if (!node)
17504 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17505 data << uint32(ERR_TAXINOSUCHPATH);
17506 GetSession()->SendPacket(&data);
17507 return false;
17510 // check node starting pos data set case if provided
17511 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
17513 if (node->map_id != GetMapId() ||
17514 (node->x - GetPositionX())*(node->x - GetPositionX())+
17515 (node->y - GetPositionY())*(node->y - GetPositionY())+
17516 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
17517 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
17519 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17520 data << uint32(ERR_TAXITOOFARAWAY);
17521 GetSession()->SendPacket(&data);
17522 return false;
17525 // node must have pos if taxi master case (npc != NULL)
17526 else if (npc)
17528 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17529 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17530 GetSession()->SendPacket(&data);
17531 return false;
17534 // Prepare to flight start now
17536 // stop combat at start taxi flight if any
17537 CombatStop();
17539 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17540 TradeCancel(true);
17542 // clean not finished taxi path if any
17543 m_taxi.ClearTaxiDestinations();
17545 // 0 element current node
17546 m_taxi.AddTaxiDestination(sourcenode);
17548 // fill destinations path tail
17549 uint32 sourcepath = 0;
17550 uint32 totalcost = 0;
17552 uint32 prevnode = sourcenode;
17553 uint32 lastnode = 0;
17555 for(uint32 i = 1; i < nodes.size(); ++i)
17557 uint32 path, cost;
17559 lastnode = nodes[i];
17560 sObjectMgr.GetTaxiPath(prevnode, lastnode, path, cost);
17562 if(!path)
17564 m_taxi.ClearTaxiDestinations();
17565 return false;
17568 totalcost += cost;
17570 if(prevnode == sourcenode)
17571 sourcepath = path;
17573 m_taxi.AddTaxiDestination(lastnode);
17575 prevnode = lastnode;
17578 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
17579 uint32 mount_display_id = sObjectMgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
17581 // in spell case allow 0 model
17582 if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
17584 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17585 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17586 GetSession()->SendPacket(&data);
17587 m_taxi.ClearTaxiDestinations();
17588 return false;
17591 uint32 money = GetMoney();
17593 if (npc)
17594 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17596 if(money < totalcost)
17598 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17599 data << uint32(ERR_TAXINOTENOUGHMONEY);
17600 GetSession()->SendPacket(&data);
17601 m_taxi.ClearTaxiDestinations();
17602 return false;
17605 //Checks and preparations done, DO FLIGHT
17606 ModifyMoney(-(int32)totalcost);
17607 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
17608 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
17610 // prevent stealth flight
17611 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17613 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17614 data << uint32(ERR_TAXIOK);
17615 GetSession()->SendPacket(&data);
17617 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17619 GetSession()->SendDoFlight(mount_display_id, sourcepath);
17621 return true;
17624 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
17626 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
17627 if(!entry)
17628 return false;
17630 std::vector<uint32> nodes;
17632 nodes.resize(2);
17633 nodes[0] = entry->from;
17634 nodes[1] = entry->to;
17636 return ActivateTaxiPathTo(nodes,NULL,spellid);
17639 void Player::ContinueTaxiFlight()
17641 uint32 sourceNode = m_taxi.GetTaxiSource();
17642 if (!sourceNode)
17643 return;
17645 sLog.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
17647 uint32 mountDisplayId = sObjectMgr.GetTaxiMountDisplayId(sourceNode, GetTeam(),true);
17648 uint32 path = m_taxi.GetCurrentTaxiPath();
17650 // search appropriate start path node
17651 uint32 startNode = 0;
17653 TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
17655 float distPrev = MAP_SIZE*MAP_SIZE;
17656 float distNext =
17657 (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
17658 (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
17659 (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
17661 for(uint32 i = 1; i < nodeList.size(); ++i)
17663 TaxiPathNode const& node = nodeList[i];
17664 TaxiPathNode const& prevNode = nodeList[i-1];
17666 // skip nodes at another map
17667 if(node.mapid != GetMapId())
17668 continue;
17670 distPrev = distNext;
17672 distNext =
17673 (node.x-GetPositionX())*(node.x-GetPositionX())+
17674 (node.y-GetPositionY())*(node.y-GetPositionY())+
17675 (node.z-GetPositionZ())*(node.z-GetPositionZ());
17677 float distNodes =
17678 (node.x-prevNode.x)*(node.x-prevNode.x)+
17679 (node.y-prevNode.y)*(node.y-prevNode.y)+
17680 (node.z-prevNode.z)*(node.z-prevNode.z);
17682 if(distNext + distPrev < distNodes)
17684 startNode = i;
17685 break;
17689 GetSession()->SendDoFlight(mountDisplayId, path, startNode);
17692 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17694 // last check 2.0.10
17695 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17696 data << GetGUID();
17697 data << uint8(0x0); // flags (0x1, 0x2)
17698 time_t curTime = time(NULL);
17699 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17701 if (itr->second->state == PLAYERSPELL_REMOVED)
17702 continue;
17703 uint32 unSpellId = itr->first;
17704 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17705 if (!spellInfo)
17707 ASSERT(spellInfo);
17708 continue;
17711 // Not send cooldown for this spells
17712 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17713 continue;
17715 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17717 data << uint32(unSpellId);
17718 data << uint32(unTimeMs); // in m.secs
17719 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17722 GetSession()->SendPacket(&data);
17725 void Player::InitDataForForm(bool reapplyMods)
17727 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17728 if(ssEntry && ssEntry->attackSpeed)
17730 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17731 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17732 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17734 else
17735 SetRegularAttackTime();
17737 switch(m_form)
17739 case FORM_CAT:
17741 if(getPowerType()!=POWER_ENERGY)
17742 setPowerType(POWER_ENERGY);
17743 break;
17745 case FORM_BEAR:
17746 case FORM_DIREBEAR:
17748 if(getPowerType()!=POWER_RAGE)
17749 setPowerType(POWER_RAGE);
17750 break;
17752 default: // 0, for example
17754 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17755 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17756 setPowerType(Powers(cEntry->powerType));
17757 break;
17761 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17762 if (!reapplyMods)
17763 UpdateEquipSpellsAtFormChange();
17765 UpdateAttackPowerAndDamage();
17766 UpdateAttackPowerAndDamage(true);
17769 void Player::InitDisplayIds()
17771 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
17772 if(!info)
17774 sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
17775 return;
17778 uint8 gender = getGender();
17779 switch(gender)
17781 case GENDER_FEMALE:
17782 SetDisplayId(info->displayId_f );
17783 SetNativeDisplayId(info->displayId_f );
17784 break;
17785 case GENDER_MALE:
17786 SetDisplayId(info->displayId_m );
17787 SetNativeDisplayId(info->displayId_m );
17788 break;
17789 default:
17790 sLog.outError("Invalid gender %u for player",gender);
17791 return;
17795 // Return true is the bought item has a max count to force refresh of window by caller
17796 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot)
17798 // cheating attempt
17799 if (count < 1) count = 1;
17801 if (!isAlive())
17802 return false;
17804 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
17805 if (!pProto)
17807 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17808 return false;
17811 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
17812 if (!pCreature)
17814 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17815 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17816 return false;
17819 VendorItemData const* vItems = pCreature->GetVendorItems();
17820 if(!vItems || vItems->Empty())
17822 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17823 return false;
17826 size_t vendor_slot = vItems->FindItemSlot(item);
17827 if (vendor_slot >= vItems->GetItemCount())
17829 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17830 return false;
17833 VendorItem const* crItem = vItems->m_items[vendor_slot];
17835 // check current item amount if it limited
17836 if (crItem->maxcount != 0)
17838 if (pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17840 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17841 return false;
17845 if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17847 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17848 return false;
17851 if (crItem->ExtendedCost)
17853 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17854 if (!iece)
17856 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17857 return false;
17860 // honor points price
17861 if (GetHonorPoints() < (iece->reqhonorpoints * count))
17863 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17864 return false;
17867 // arena points price
17868 if (GetArenaPoints() < (iece->reqarenapoints * count))
17870 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17871 return false;
17874 // item base price
17875 for (uint8 i = 0; i < 5; ++i)
17877 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17879 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17880 return false;
17884 // check for personal arena rating requirement
17885 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17887 // probably not the proper equip err
17888 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17889 return false;
17893 uint32 price = pProto->BuyPrice * count;
17895 // reputation discount
17896 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17898 if (GetMoney() < price)
17900 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17901 return false;
17904 if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
17906 ItemPosCountVec dest;
17907 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17908 if (msg != EQUIP_ERR_OK)
17910 SendEquipError( msg, NULL, NULL );
17911 return false;
17914 ModifyMoney( -(int32)price );
17915 if (crItem->ExtendedCost) // case for new honor system
17917 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17918 if (iece->reqhonorpoints)
17919 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17920 if (iece->reqarenapoints)
17921 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17922 for (uint8 i = 0; i < 5; ++i)
17924 if (iece->reqitem[i])
17925 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17929 if (Item *it = StoreNewItem( dest, item, true ))
17931 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17933 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17934 data << uint64(pCreature->GetGUID());
17935 data << uint32(vendor_slot+1); // numbered from 1 at client
17936 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17937 data << uint32(count);
17938 GetSession()->SendPacket(&data);
17940 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17943 else if (IsEquipmentPos(bag, slot))
17945 if (pProto->BuyCount * count != 1)
17947 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17948 return false;
17951 uint16 dest;
17952 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17953 if (msg != EQUIP_ERR_OK)
17955 SendEquipError( msg, NULL, NULL );
17956 return false;
17959 ModifyMoney( -(int32)price );
17960 if (crItem->ExtendedCost) // case for new honor system
17962 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17963 if (iece->reqhonorpoints)
17964 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17965 if (iece->reqarenapoints)
17966 ModifyArenaPoints( - int32(iece->reqarenapoints));
17967 for (uint8 i = 0; i < 5; ++i)
17969 if(iece->reqitem[i])
17970 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17974 if (Item *it = EquipNewItem( dest, item, true ))
17976 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17978 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17979 data << uint64(pCreature->GetGUID());
17980 data << uint32(vendor_slot + 1); // numbered from 1 at client
17981 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17982 data << uint32(count);
17983 GetSession()->SendPacket(&data);
17985 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17987 AutoUnequipOffhandIfNeed();
17990 else
17992 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17993 return false;
17996 return crItem->maxcount != 0;
17999 uint32 Player::GetMaxPersonalArenaRatingRequirement()
18001 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
18002 // the personal rating of the arena team must match the required limit as well
18003 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
18004 uint32 max_personal_rating = 0;
18005 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
18007 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(GetArenaTeamId(i)))
18009 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING);
18010 uint32 t_rating = at->GetRating();
18011 p_rating = p_rating < t_rating ? p_rating : t_rating;
18012 if(max_personal_rating < p_rating)
18013 max_personal_rating = p_rating;
18016 return max_personal_rating;
18019 void Player::UpdateHomebindTime(uint32 time)
18021 // GMs never get homebind timer online
18022 if (m_InstanceValid || isGameMaster())
18024 if(m_HomebindTimer) // instance valid, but timer not reset
18026 // hide reminder
18027 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
18028 data << uint32(0);
18029 data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
18030 GetSession()->SendPacket(&data);
18032 // instance is valid, reset homebind timer
18033 m_HomebindTimer = 0;
18035 else if (m_HomebindTimer > 0)
18037 if (time >= m_HomebindTimer)
18039 // teleport to nearest graveyard
18040 RepopAtGraveyard();
18042 else
18043 m_HomebindTimer -= time;
18045 else
18047 // instance is invalid, start homebind timer
18048 m_HomebindTimer = 60000;
18049 // send message to player
18050 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
18051 data << uint32(m_HomebindTimer);
18052 data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
18053 GetSession()->SendPacket(&data);
18054 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
18058 void Player::UpdatePvP(bool state, bool ovrride)
18060 if(!state || ovrride)
18062 SetPvP(state);
18063 pvpInfo.endTimer = 0;
18065 else
18067 if(pvpInfo.endTimer != 0)
18068 pvpInfo.endTimer = time(NULL);
18069 else
18070 SetPvP(state);
18074 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
18076 // init cooldown values
18077 uint32 cat = 0;
18078 int32 rec = -1;
18079 int32 catrec = -1;
18081 // some special item spells without correct cooldown in SpellInfo
18082 // cooldown information stored in item prototype
18083 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
18085 if(itemId)
18087 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
18089 for(int idx = 0; idx < 5; ++idx)
18091 if(proto->Spells[idx].SpellId == spellInfo->Id)
18093 cat = proto->Spells[idx].SpellCategory;
18094 rec = proto->Spells[idx].SpellCooldown;
18095 catrec = proto->Spells[idx].SpellCategoryCooldown;
18096 break;
18102 // if no cooldown found above then base at DBC data
18103 if(rec < 0 && catrec < 0)
18105 cat = spellInfo->Category;
18106 rec = spellInfo->RecoveryTime;
18107 catrec = spellInfo->CategoryRecoveryTime;
18110 time_t curTime = time(NULL);
18112 time_t catrecTime;
18113 time_t recTime;
18115 // overwrite time for selected category
18116 if(infinityCooldown)
18118 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
18119 // but not allow ignore until reset or re-login
18120 catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
18121 recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
18123 else
18125 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
18126 // prevent 0 cooldowns set by another way
18127 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
18128 rec = GetAttackTime(RANGED_ATTACK);
18130 // Now we have cooldown data (if found any), time to apply mods
18131 if(rec > 0)
18132 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
18134 if(catrec > 0)
18135 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
18137 // replace negative cooldowns by 0
18138 if (rec < 0) rec = 0;
18139 if (catrec < 0) catrec = 0;
18141 // no cooldown after applying spell mods
18142 if( rec == 0 && catrec == 0)
18143 return;
18145 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
18146 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
18149 // self spell cooldown
18150 if(recTime > 0)
18151 AddSpellCooldown(spellInfo->Id, itemId, recTime);
18153 // category spells
18154 if (cat && catrec > 0)
18156 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
18157 if(i_scstore != sSpellCategoryStore.end())
18159 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
18161 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
18162 continue;
18164 AddSpellCooldown(*i_scset, itemId, catrecTime);
18170 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
18172 SpellCooldown sc;
18173 sc.end = end_time;
18174 sc.itemid = itemid;
18175 m_spellCooldowns[spellid] = sc;
18178 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
18180 // start cooldowns at server side, if any
18181 AddSpellAndCategoryCooldowns(spellInfo, itemId, spell);
18183 // Send activate cooldown timer (possible 0) at client side
18184 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
18185 data << uint32(spellInfo->Id);
18186 data << uint64(GetGUID());
18187 SendDirectMessage(&data);
18190 void Player::UpdatePotionCooldown(Spell* spell)
18192 // no potion used i combat or still in combat
18193 if(!m_lastPotionId || isInCombat())
18194 return;
18196 // Call not from spell cast, send cooldown event for item spells if no in combat
18197 if(!spell)
18199 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
18200 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
18201 for(int idx = 0; idx < 5; ++idx)
18202 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
18203 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
18204 SendCooldownEvent(spellInfo,m_lastPotionId);
18206 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
18207 else
18208 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
18210 m_lastPotionId = 0;
18213 //slot to be excluded while counting
18214 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
18216 if(!enchantmentcondition)
18217 return true;
18219 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
18221 if(!Condition)
18222 return true;
18224 uint8 curcount[4] = {0, 0, 0, 0};
18226 //counting current equipped gem colors
18227 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
18229 if(i == slot)
18230 continue;
18231 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
18232 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
18234 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18236 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18237 if(!enchant_id)
18238 continue;
18240 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18241 if(!enchantEntry)
18242 continue;
18244 uint32 gemid = enchantEntry->GemID;
18245 if(!gemid)
18246 continue;
18248 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
18249 if(!gemProto)
18250 continue;
18252 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
18253 if(!gemProperty)
18254 continue;
18256 uint8 GemColor = gemProperty->color;
18258 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
18260 if(tmpcolormask & GemColor)
18261 ++curcount[b];
18267 bool activate = true;
18269 for(int i = 0; i < 5; ++i)
18271 if(!Condition->Color[i])
18272 continue;
18274 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
18276 // if have <CompareColor> use them as count, else use <value> from Condition
18277 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
18279 switch(Condition->Comparator[i])
18281 case 2: // requires less <color> than (<value> || <comparecolor>) gems
18282 activate &= (_cur_gem < _cmp_gem) ? true : false;
18283 break;
18284 case 3: // requires more <color> than (<value> || <comparecolor>) gems
18285 activate &= (_cur_gem > _cmp_gem) ? true : false;
18286 break;
18287 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
18288 activate &= (_cur_gem >= _cmp_gem) ? true : false;
18289 break;
18293 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");
18295 return activate;
18298 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
18300 //cycle all equipped items
18301 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18303 //enchants for the slot being socketed are handled by Player::ApplyItemMods
18304 if(slot == exceptslot)
18305 continue;
18307 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18309 if(!pItem || !pItem->GetProto()->Socket[0].Color)
18310 continue;
18312 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18314 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18315 if(!enchant_id)
18316 continue;
18318 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18319 if(!enchantEntry)
18320 continue;
18322 uint32 condition = enchantEntry->EnchantmentCondition;
18323 if(condition)
18325 //was enchant active with/without item?
18326 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
18327 //should it now be?
18328 if(wasactive != EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
18330 // ignore item gem conditions
18331 //if state changed, (dis)apply enchant
18332 ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true);
18339 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
18340 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
18342 //cycle all equipped items
18343 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18345 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
18346 if(slot == exceptslot)
18347 continue;
18349 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18351 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
18352 continue;
18354 //cycle all (gem)enchants
18355 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18357 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18358 if(!enchant_id) //if no enchant go to next enchant(slot)
18359 continue;
18361 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18362 if(!enchantEntry)
18363 continue;
18365 //only metagems to be (de)activated, so only enchants with condition
18366 uint32 condition = enchantEntry->EnchantmentCondition;
18367 if(condition)
18368 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
18373 void Player::SetBattleGroundEntryPoint()
18375 // Taxi path store
18376 if (!m_taxi.empty())
18378 m_bgData.mountSpell = 0;
18379 m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
18380 m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
18382 // On taxi we don't need check for dungeon
18383 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18384 return;
18386 else
18388 m_bgData.ClearTaxiPath();
18390 // Mount spell id storing
18391 if (IsMounted())
18393 AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED);
18394 if (!auras.empty())
18395 m_bgData.mountSpell = (*auras.begin())->GetId();
18397 else
18398 m_bgData.mountSpell = 0;
18400 // If map is dungeon find linked graveyard
18401 if(GetMap()->IsDungeon())
18403 if (const WorldSafeLocsEntry* entry = sObjectMgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
18405 m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
18406 return;
18408 else
18409 sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
18411 // If new entry point is not BG or arena set it
18412 else if (!GetMap()->IsBattleGroundOrArena())
18414 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18415 return;
18419 // In error cases use homebind position
18420 m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
18423 void Player::LeaveBattleground(bool teleportToEntryPoint)
18425 if(BattleGround *bg = GetBattleGround())
18427 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
18429 // call after remove to be sure that player resurrected for correct cast
18430 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
18432 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
18434 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
18435 if(IsBeingTeleportedFar())
18437 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
18438 return;
18441 CastSpell(this, 26013, true); // Deserter
18447 bool Player::CanJoinToBattleground() const
18449 // check Deserter debuff
18450 if(GetDummyAura(26013))
18451 return false;
18453 return true;
18456 bool Player::CanReportAfkDueToLimit()
18458 // a player can complain about 15 people per 5 minutes
18459 if(m_bgData.bgAfkReportedCount++ >= 15)
18460 return false;
18462 return true;
18465 ///This player has been blamed to be inactive in a battleground
18466 void Player::ReportedAfkBy(Player* reporter)
18468 BattleGround *bg = GetBattleGround();
18469 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
18470 return;
18472 // check if player has 'Idle' or 'Inactive' debuff
18473 if(m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680, 0) && !HasAura(43681, 0) && reporter->CanReportAfkDueToLimit())
18475 m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
18476 // 3 players have to complain to apply debuff
18477 if(m_bgData.bgAfkReporter.size() >= 3)
18479 // cast 'Idle' spell
18480 CastSpell(this, 43680, true);
18481 m_bgData.bgAfkReporter.clear();
18486 WorldObject const* Player::GetViewPoint() const
18488 if(uint64 far_sight = GetFarSight())
18490 WorldObject const* viewPoint = GetMap()->GetWorldObject(far_sight);
18491 return viewPoint ? viewPoint : this; // always expected not NULL
18493 else
18494 return this;
18497 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
18499 // gamemaster in GM mode see all, including ghosts
18500 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
18501 return true;
18503 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
18504 if (InBattleGround())
18506 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
18507 return false;
18508 return true;
18511 // Live player see live player or dead player with not realized corpse
18512 if(pl->isAlive() || pl->m_deathTimer > 0)
18514 return isAlive() || m_deathTimer > 0;
18517 // Ghost see other friendly ghosts, that's for sure
18518 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
18519 return true;
18521 // Dead player see live players near own corpse
18522 if(isAlive())
18524 Corpse *corpse = pl->GetCorpse();
18525 if(corpse)
18527 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
18528 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
18529 return true;
18533 // and not see any other
18534 return false;
18537 bool Player::IsVisibleGloballyFor( Player* u ) const
18539 if(!u)
18540 return false;
18542 // Always can see self
18543 if (u==this)
18544 return true;
18546 // Visible units, always are visible for all players
18547 if (GetVisibility() == VISIBILITY_ON)
18548 return true;
18550 // GMs are visible for higher gms (or players are visible for gms)
18551 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
18552 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
18554 // non faction visibility non-breakable for non-GMs
18555 if (GetVisibility() == VISIBILITY_OFF)
18556 return false;
18558 // non-gm stealth/invisibility not hide from global player lists
18559 return true;
18562 template<class T>
18563 inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/)
18567 template<>
18568 inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
18570 if (p->GetPetGUID()==t->GetGUID() && ((Creature*)t)->isPet())
18571 ((Pet*)t)->Remove(PET_SAVE_NOT_IN_SLOT, true);
18574 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target)
18576 if(HaveAtClient(target))
18578 if(!target->isVisibleForInState(this, viewPoint, true))
18580 if (target->GetTypeId()==TYPEID_UNIT)
18581 BeforeVisibilityDestroy<Creature>((Creature*)target,this);
18583 target->DestroyForPlayer(this);
18584 m_clientGUIDs.erase(target->GetGUID());
18586 #ifdef MANGOS_DEBUG
18587 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18588 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18589 #endif
18592 else
18594 if(target->isVisibleForInState(this, viewPoint, false))
18596 target->SendCreateUpdateToPlayer(this);
18597 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
18598 m_clientGUIDs.insert(target->GetGUID());
18600 #ifdef MANGOS_DEBUG
18601 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18602 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18603 #endif
18605 // target aura duration for caster show only if target exist at caster client
18606 // send data at target visibility change (adding to client)
18607 if(target!=this && target->isType(TYPEMASK_UNIT))
18608 SendAurasForTarget((Unit*)target);
18610 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
18611 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18616 template<class T>
18617 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
18619 s64.insert(target->GetGUID());
18622 template<>
18623 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
18625 if(!target->IsTransport())
18626 s64.insert(target->GetGUID());
18629 template<class T>
18630 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
18632 if(HaveAtClient(target))
18634 if(!target->isVisibleForInState(this,viewPoint,true))
18636 BeforeVisibilityDestroy<T>(target,this);
18638 target->BuildOutOfRangeUpdateBlock(&data);
18639 m_clientGUIDs.erase(target->GetGUID());
18641 #ifdef MANGOS_DEBUG
18642 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18643 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));
18644 #endif
18647 else
18649 if(target->isVisibleForInState(this,viewPoint,false))
18651 visibleNow.insert(target);
18652 target->BuildCreateUpdateBlockForPlayer(&data, this);
18653 UpdateVisibilityOf_helper(m_clientGUIDs,target);
18655 #ifdef MANGOS_DEBUG
18656 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18657 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));
18658 #endif
18663 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18664 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18665 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18666 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18667 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18669 void Player::InitPrimaryProfessions()
18671 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
18674 void Player::SendComboPoints()
18676 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
18677 if (combotarget)
18679 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
18680 data.append(combotarget->GetPackGUID());
18681 data << uint8(m_comboPoints);
18682 GetSession()->SendPacket(&data);
18686 void Player::AddComboPoints(Unit* target, int8 count)
18688 if(!count)
18689 return;
18691 // without combo points lost (duration checked in aura)
18692 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18694 if(target->GetGUID() == m_comboTarget)
18696 m_comboPoints += count;
18698 else
18700 if(m_comboTarget)
18701 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
18702 target2->RemoveComboPointHolder(GetGUIDLow());
18704 m_comboTarget = target->GetGUID();
18705 m_comboPoints = count;
18707 target->AddComboPointHolder(GetGUIDLow());
18710 if (m_comboPoints > 5) m_comboPoints = 5;
18711 if (m_comboPoints < 0) m_comboPoints = 0;
18713 SendComboPoints();
18716 void Player::ClearComboPoints()
18718 if(!m_comboTarget)
18719 return;
18721 // without combopoints lost (duration checked in aura)
18722 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18724 m_comboPoints = 0;
18726 SendComboPoints();
18728 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18729 target->RemoveComboPointHolder(GetGUIDLow());
18731 m_comboTarget = 0;
18734 void Player::SetGroup(Group *group, int8 subgroup)
18736 if(group == NULL)
18737 m_group.unlink();
18738 else
18740 // never use SetGroup without a subgroup unless you specify NULL for group
18741 assert(subgroup >= 0);
18742 m_group.link(group, this);
18743 m_group.setSubGroup((uint8)subgroup);
18747 void Player::SendInitialPacketsBeforeAddToMap()
18749 GetSocial()->SendSocialList();
18751 // Homebind
18752 WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
18753 data << m_homebindX << m_homebindY << m_homebindZ;
18754 data << (uint32) m_homebindMapId;
18755 data << (uint32) m_homebindZoneId;
18756 GetSession()->SendPacket(&data);
18758 // SMSG_SET_PROFICIENCY
18759 // SMSG_SET_PCT_SPELL_MODIFIER
18760 // SMSG_SET_FLAT_SPELL_MODIFIER
18762 SendTalentsInfoData(false);
18764 data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4+4);
18765 data << uint32(0);
18766 data << uint32(0);
18767 GetSession()->SendPacket(&data);
18769 SendInitialSpells();
18771 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
18772 data << uint32(0); // count, for(count) uint32;
18773 GetSession()->SendPacket(&data);
18775 SendInitialActionButtons();
18776 m_reputationMgr.SendInitialReputations();
18778 if(!isAlive())
18779 SendCorpseReclaimDelay(true);
18781 SendInitWorldStates(GetZoneId(), GetAreaId());
18783 SendEquipmentSetList();
18785 m_achievementMgr.SendAllAchievementData();
18787 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
18788 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18789 data << (float)0.01666667f; // game speed
18790 data << uint32(0); // added in 3.1.2
18791 GetSession()->SendPacket( &data );
18793 // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
18794 // SMSG_PET_GUIDS
18795 // SMSG_POWER_UPDATE
18797 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18798 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || HasAuraType(SPELL_AURA_FLY) || isInFlight())
18799 m_movementInfo.AddMovementFlag(MOVEMENTFLAG_FLYING);
18801 m_mover = this;
18804 void Player::SendInitialPacketsAfterAddToMap()
18806 // update zone
18807 uint32 newzone, newarea;
18808 GetZoneAndAreaId(newzone,newarea);
18809 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
18811 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18812 data << uint32(0x00000000); // on blizz it increments periodically
18813 GetSession()->SendPacket(&data);
18815 CastSpell(this, 836, true); // LOGINEFFECT
18817 // set some aura effects that send packet to player client after add player to map
18818 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18819 // same auras state lost at far teleport, send it one more time in this case also
18820 static const AuraType auratypes[] =
18822 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18823 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18824 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18826 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18828 Unit::AuraList const& auraList = GetAurasByType(*itr);
18829 if(!auraList.empty())
18830 auraList.front()->ApplyModifier(true,true);
18833 if(HasAuraType(SPELL_AURA_MOD_STUN))
18834 SetMovement(MOVE_ROOT);
18836 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18837 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18839 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
18840 data2.append(GetPackGUID());
18841 data2 << (uint32)2;
18842 SendMessageToSet(&data2,true);
18845 SendAurasForTarget(this);
18846 SendEnchantmentDurations(); // must be after add to map
18847 SendItemDurations(); // must be after add to map
18850 void Player::SendUpdateToOutOfRangeGroupMembers()
18852 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18853 return;
18854 if(Group* group = GetGroup())
18855 group->UpdatePlayerOutOfRange(this);
18857 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18858 m_auraUpdateMask = 0;
18859 if(Pet *pet = GetPet())
18860 pet->ResetAuraUpdateMask();
18863 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18865 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18866 data << uint32(mapid);
18867 data << uint8(reason); // transfer abort reason
18868 switch(reason)
18870 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18871 case TRANSFER_ABORT_DIFFICULTY:
18872 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18873 data << uint8(arg);
18874 break;
18876 GetSession()->SendPacket(&data);
18879 void Player::SendInstanceResetWarning( uint32 mapid, Difficulty difficulty, uint32 time )
18881 // type of warning, based on the time remaining until reset
18882 uint32 type;
18883 if(time > 3600)
18884 type = RAID_INSTANCE_WELCOME;
18885 else if(time > 900 && time <= 3600)
18886 type = RAID_INSTANCE_WARNING_HOURS;
18887 else if(time > 300 && time <= 900)
18888 type = RAID_INSTANCE_WARNING_MIN;
18889 else
18890 type = RAID_INSTANCE_WARNING_MIN_SOON;
18892 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
18893 data << uint32(type);
18894 data << uint32(mapid);
18895 data << uint32(difficulty); // difficulty
18896 data << uint32(time);
18897 if(type == RAID_INSTANCE_WELCOME)
18899 data << uint8(0); // is your (1)
18900 data << uint8(0); // is extended (1), ignored if prev field is 0
18902 GetSession()->SendPacket(&data);
18905 void Player::ApplyEquipCooldown( Item * pItem )
18907 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
18909 _Spell const& spellData = pItem->GetProto()->Spells[i];
18911 // no spell
18912 if( !spellData.SpellId )
18913 continue;
18915 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18916 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18917 continue;
18919 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18921 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18922 data << pItem->GetGUID();
18923 data << uint32(spellData.SpellId);
18924 GetSession()->SendPacket(&data);
18928 void Player::resetSpells()
18930 // not need after this call
18931 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18932 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
18934 // make full copy of map (spells removed and marked as deleted at another spell remove
18935 // and we can't use original map for safe iterative with visit each spell at loop end
18936 PlayerSpellMap smap = GetSpellMap();
18938 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18939 removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
18941 learnDefaultSpells();
18942 learnQuestRewardedSpells();
18945 void Player::learnDefaultSpells()
18947 // learn default race/class spells
18948 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(),getClass());
18949 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18951 uint32 tspell = *itr;
18952 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18953 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18954 addSpell(tspell,true,true,true,false);
18955 else // but send in normal spell in game learn case
18956 learnSpell(tspell,true);
18960 void Player::learnQuestRewardedSpells(Quest const* quest)
18962 uint32 spell_id = quest->GetRewSpellCast();
18964 // skip quests without rewarded spell
18965 if( !spell_id )
18966 return;
18968 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18969 if(!spellInfo)
18970 return;
18972 // check learned spells state
18973 bool found = false;
18974 for(int i=0; i < 3; ++i)
18976 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18978 found = true;
18979 break;
18983 // skip quests with not teaching spell or already known spell
18984 if(!found)
18985 return;
18987 // prevent learn non first rank unknown profession and second specialization for same profession)
18988 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18989 if( sSpellMgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18991 // not have first rank learned (unlearned prof?)
18992 uint32 first_spell = sSpellMgr.GetFirstSpellInChain(learned_0);
18993 if( !HasSpell(first_spell) )
18994 return;
18996 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18997 if(!learnedInfo)
18998 return;
19000 // specialization
19001 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
19003 // search other specialization for same prof
19004 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
19006 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
19007 continue;
19009 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
19010 if(!itrInfo)
19011 return;
19013 // compare only specializations
19014 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
19015 continue;
19017 // compare same chain spells
19018 if(sSpellMgr.GetFirstSpellInChain(itr->first) != first_spell)
19019 continue;
19021 // now we have 2 specialization, learn possible only if found is lesser specialization rank
19022 if(!sSpellMgr.IsHighRankOfSpell(learned_0,itr->first))
19023 return;
19028 CastSpell( this, spell_id, true);
19031 void Player::learnQuestRewardedSpells()
19033 // learn spells received from quest completing
19034 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
19036 // skip no rewarded quests
19037 if(!itr->second.m_rewarded)
19038 continue;
19040 Quest const* quest = sObjectMgr.GetQuestTemplate(itr->first);
19041 if( !quest )
19042 continue;
19044 learnQuestRewardedSpells(quest);
19048 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
19050 uint32 raceMask = getRaceMask();
19051 uint32 classMask = getClassMask();
19052 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
19054 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
19055 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
19056 continue;
19057 // Check race if set
19058 if (pAbility->racemask && !(pAbility->racemask & raceMask))
19059 continue;
19060 // Check class if set
19061 if (pAbility->classmask && !(pAbility->classmask & classMask))
19062 continue;
19064 if (sSpellStore.LookupEntry(pAbility->spellId))
19066 // need unlearn spell
19067 if (skill_value < pAbility->req_skill_value)
19068 removeSpell(pAbility->spellId);
19069 // need learn
19070 else if (!IsInWorld())
19071 addSpell(pAbility->spellId,true,true,true,false);
19072 else
19073 learnSpell(pAbility->spellId,true);
19078 void Player::SendAurasForTarget(Unit *target)
19080 if(target->GetVisibleAuras()->empty()) // speedup things
19081 return;
19083 WorldPacket data(SMSG_AURA_UPDATE_ALL);
19084 data.append(target->GetPackGUID());
19086 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
19087 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
19089 for(uint32 j = 0; j < 3; ++j)
19091 if(Aura *aura = target->GetAura(itr->second, j))
19093 data << uint8(aura->GetAuraSlot());
19094 data << uint32(aura->GetId());
19096 if(aura->GetId())
19098 uint8 auraFlags = aura->GetAuraFlags();
19099 // flags
19100 data << uint8(auraFlags);
19101 // level
19102 data << uint8(aura->GetAuraLevel());
19103 // charges
19104 if (aura->GetAuraCharges())
19105 data << uint8(aura->GetAuraCharges() * aura->GetStackAmount());
19106 else
19107 data << uint8(aura->GetStackAmount());
19109 if(!(auraFlags & AFLAG_NOT_CASTER))
19111 data << uint8(0); // packed GUID of someone (caster?)
19114 if(auraFlags & AFLAG_DURATION) // include aura duration
19116 data << uint32(aura->GetAuraMaxDuration());
19117 data << uint32(aura->GetAuraDuration());
19120 break;
19125 GetSession()->SendPacket(&data);
19128 void Player::SetDailyQuestStatus( uint32 quest_id )
19130 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19132 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
19134 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
19135 m_lastDailyQuestTime = time(NULL); // last daily quest time
19136 m_DailyQuestChanged = true;
19137 break;
19142 void Player::ResetDailyQuestStatus()
19144 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19145 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
19147 // DB data deleted in caller
19148 m_DailyQuestChanged = false;
19149 m_lastDailyQuestTime = 0;
19152 BattleGround* Player::GetBattleGround() const
19154 if(GetBattleGroundId()==0)
19155 return NULL;
19157 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
19160 bool Player::InArena() const
19162 BattleGround *bg = GetBattleGround();
19163 if(!bg || !bg->isArena())
19164 return false;
19166 return true;
19169 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
19171 // get a template bg instead of running one
19172 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
19173 if(!bg)
19174 return false;
19176 // limit check leel to dbc compatible level range
19177 uint32 level = getLevel();
19178 if (level > DEFAULT_MAX_LEVEL)
19179 level = DEFAULT_MAX_LEVEL;
19181 if(level < bg->GetMinLevel() || level > bg->GetMaxLevel())
19182 return false;
19184 return true;
19187 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
19189 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
19190 if(!vendor_faction || !vendor_faction->faction)
19191 return 1.0f;
19193 ReputationRank rank = GetReputationRank(vendor_faction->faction);
19194 if(rank <= REP_NEUTRAL)
19195 return 1.0f;
19197 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
19200 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
19202 uint32 racemask = getRaceMask();
19203 uint32 classmask = getClassMask();
19205 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
19206 if (bounds.first==bounds.second)
19207 return true;
19209 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
19211 // skip wrong race skills
19212 if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
19213 continue;
19215 // skip wrong class skills
19216 if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
19217 continue;
19219 return true;
19222 return false;
19225 bool Player::HasQuestForGO(int32 GOId) const
19227 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
19229 uint32 questid = GetQuestSlotQuestId(i);
19230 if ( questid == 0 )
19231 continue;
19233 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
19234 if(qs_itr == mQuestStatus.end())
19235 continue;
19237 QuestStatusData const& qs = qs_itr->second;
19239 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
19241 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
19242 if(!qinfo)
19243 continue;
19245 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
19246 continue;
19248 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
19250 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
19251 continue;
19253 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
19254 return true;
19258 return false;
19261 void Player::UpdateForQuestWorldObjects()
19263 if(m_clientGUIDs.empty())
19264 return;
19266 UpdateData udata;
19267 WorldPacket packet;
19268 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
19270 if(IS_GAMEOBJECT_GUID(*itr))
19272 GameObject *obj = GetMap()->GetGameObject(*itr);
19273 if(obj)
19274 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
19276 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
19278 Creature *obj = GetMap()->GetCreatureOrPetOrVehicle(*itr);
19279 if(!obj)
19280 continue;
19282 // check if this unit requires quest specific flags
19283 if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
19284 continue;
19286 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(obj->GetEntry());
19287 for(SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
19289 if(_itr->second.questStart || _itr->second.questEnd)
19291 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
19292 break;
19297 udata.BuildPacket(&packet);
19298 GetSession()->SendPacket(&packet);
19301 void Player::SummonIfPossible(bool agree)
19303 if(!agree)
19305 m_summon_expire = 0;
19306 return;
19309 // expire and auto declined
19310 if(m_summon_expire < time(NULL))
19311 return;
19313 // stop taxi flight at summon
19314 if(isInFlight())
19316 GetMotionMaster()->MovementExpired();
19317 m_taxi.ClearTaxiDestinations();
19320 // drop flag at summon
19321 // 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
19322 if(BattleGround *bg = GetBattleGround())
19323 bg->EventPlayerDroppedFlag(this);
19325 m_summon_expire = 0;
19327 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
19329 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
19332 void Player::RemoveItemDurations( Item *item )
19334 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
19336 if(*itr==item)
19338 m_itemDuration.erase(itr);
19339 break;
19344 void Player::AddItemDurations( Item *item )
19346 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
19348 m_itemDuration.push_back(item);
19349 item->SendTimeUpdate(this);
19353 void Player::AutoUnequipOffhandIfNeed()
19355 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
19356 if(!offItem)
19357 return;
19359 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
19360 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
19361 return;
19363 ItemPosCountVec off_dest;
19364 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
19365 if( off_msg == EQUIP_ERR_OK )
19367 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19368 StoreItem( off_dest, offItem, true );
19370 else
19372 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19373 CharacterDatabase.BeginTransaction();
19374 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
19375 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
19376 CharacterDatabase.CommitTransaction();
19378 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
19379 MailDraft(subject).AddItem(offItem).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
19383 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
19385 if(spellInfo->EquippedItemClass < 0)
19386 return true;
19388 // scan other equipped items for same requirements (mostly 2 daggers/etc)
19389 // for optimize check 2 used cases only
19390 switch(spellInfo->EquippedItemClass)
19392 case ITEM_CLASS_WEAPON:
19394 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
19395 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19396 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19397 return true;
19398 break;
19400 case ITEM_CLASS_ARMOR:
19402 // tabard not have dependent spells
19403 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
19404 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19405 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19406 return true;
19408 // shields can be equipped to offhand slot
19409 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
19410 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19411 return true;
19413 // ranged slot can have some armor subclasses
19414 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
19415 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19416 return true;
19418 break;
19420 default:
19421 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
19422 break;
19425 return false;
19428 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
19430 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
19431 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
19432 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
19433 return true;
19435 // Check no reagent use mask
19436 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
19437 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
19438 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
19439 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
19440 return true;
19442 return false;
19445 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
19447 AuraMap& auras = GetAuras();
19448 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
19450 Aura* aura = itr->second;
19452 // skip passive (passive item dependent spells work in another way) and not self applied auras
19453 SpellEntry const* spellInfo = aura->GetSpellProto();
19454 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
19456 ++itr;
19457 continue;
19460 // skip if not item dependent or have alternative item
19461 if(HasItemFitToSpellReqirements(spellInfo,pItem))
19463 ++itr;
19464 continue;
19467 // no alt item, remove aura, restart check
19468 RemoveAurasDueToSpell(aura->GetId());
19469 itr = auras.begin();
19472 // currently casted spells can be dependent from item
19473 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
19474 if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
19475 if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
19476 InterruptSpell(CurrentSpellTypes(i));
19479 uint32 Player::GetResurrectionSpellId()
19481 // search priceless resurrection possibilities
19482 uint32 prio = 0;
19483 uint32 spell_id = 0;
19484 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
19485 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
19487 // Soulstone Resurrection // prio: 3 (max, non death persistent)
19488 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
19490 switch((*itr)->GetId())
19492 case 20707: spell_id = 3026; break; // rank 1
19493 case 20762: spell_id = 20758; break; // rank 2
19494 case 20763: spell_id = 20759; break; // rank 3
19495 case 20764: spell_id = 20760; break; // rank 4
19496 case 20765: spell_id = 20761; break; // rank 5
19497 case 27239: spell_id = 27240; break; // rank 6
19498 case 47883: spell_id = 47882; break; // rank 7
19499 default:
19500 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
19501 continue;
19504 prio = 3;
19506 // Twisting Nether // prio: 2 (max)
19507 else if((*itr)->GetId()==23701 && roll_chance_i(10))
19509 prio = 2;
19510 spell_id = 23700;
19514 // Reincarnation (passive spell) // prio: 1
19515 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
19516 spell_id = 21169;
19518 return spell_id;
19521 // Used in triggers for check "Only to targets that grant experience or honor" req
19522 bool Player::isHonorOrXPTarget(Unit* pVictim)
19524 uint32 v_level = pVictim->getLevel();
19525 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
19527 // Victim level less gray level
19528 if(v_level<=k_grey)
19529 return false;
19531 if(pVictim->GetTypeId() == TYPEID_UNIT)
19533 if (((Creature*)pVictim)->isTotem() ||
19534 ((Creature*)pVictim)->isPet() ||
19535 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
19536 return false;
19538 return true;
19541 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
19543 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
19545 // prepare data for near group iteration (PvP and !PvP cases)
19546 uint32 xp = 0;
19547 bool honored_kill = false;
19549 if(Group *pGroup = GetGroup())
19551 uint32 count = 0;
19552 uint32 sum_level = 0;
19553 Player* member_with_max_level = NULL;
19554 Player* not_gray_member_with_max_level = NULL;
19556 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
19558 if(member_with_max_level)
19560 /// not get Xp in PvP or no not gray players in group
19561 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
19563 /// skip in check PvP case (for speed, not used)
19564 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
19565 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
19566 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
19568 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19570 Player* pGroupGuy = itr->getSource();
19571 if(!pGroupGuy)
19572 continue;
19574 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
19575 continue; // member (alive or dead) or his corpse at req. distance
19577 // honor can be in PvP and !PvP (racial leader) cases (for alive)
19578 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
19579 honored_kill = true;
19581 // xp and reputation only in !PvP case
19582 if(!PvP)
19584 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
19586 // if is in dungeon then all receive full reputation at kill
19587 // rewarded any alive/dead/near_corpse group member
19588 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
19590 // XP updated only for alive group member
19591 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
19592 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
19594 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
19596 pGroupGuy->GiveXP(itr_xp, pVictim);
19597 if(Pet* pet = pGroupGuy->GetPet())
19598 pet->GivePetXP(itr_xp/2);
19601 // quest objectives updated only for alive group member or dead but with not released body
19602 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19604 // normal creature (not pet/etc) can be only in !PvP case
19605 if(pVictim->GetTypeId()==TYPEID_UNIT)
19606 pGroupGuy->KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19612 else // if (!pGroup)
19614 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
19616 // honor can be in PvP and !PvP (racial leader) cases
19617 if(RewardHonor(pVictim,1))
19618 honored_kill = true;
19620 // xp and reputation only in !PvP case
19621 if(!PvP)
19623 RewardReputation(pVictim,1);
19624 GiveXP(xp, pVictim);
19626 if(Pet* pet = GetPet())
19627 pet->GivePetXP(xp);
19629 // normal creature (not pet/etc) can be only in !PvP case
19630 if(pVictim->GetTypeId()==TYPEID_UNIT)
19631 KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19634 return xp || honored_kill;
19637 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
19639 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
19641 // prepare data for near group iteration
19642 if(Group *pGroup = GetGroup())
19644 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19646 Player* pGroupGuy = itr->getSource();
19647 if(!pGroupGuy)
19648 continue;
19650 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
19651 continue; // member (alive or dead) or his corpse at req. distance
19653 // quest objectives updated only for alive group member or dead but with not released body
19654 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19655 pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
19658 else // if (!pGroup)
19659 KilledMonsterCredit(creature_id, creature_guid);
19662 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
19664 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
19665 return true;
19667 if (isAlive())
19668 return false;
19670 Corpse* corpse = GetCorpse();
19671 if (!corpse)
19672 return false;
19674 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
19677 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
19679 Item* item = GetWeaponForAttack(attType,true,true);
19681 // unarmed only with base attack
19682 if(attType != BASE_ATTACK && !item)
19683 return 0;
19685 // weapon skill or (unarmed for base attack)
19686 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
19687 return GetBaseSkillValue(skill);
19690 void Player::ResurectUsingRequestData()
19692 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
19693 if(IS_PLAYER_GUID(m_resurrectGUID))
19694 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
19696 //we cannot resurrect player when we triggered far teleport
19697 //player will be resurrected upon teleportation
19698 if(IsBeingTeleportedFar())
19700 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
19701 return;
19704 ResurrectPlayer(0.0f,false);
19706 if(GetMaxHealth() > m_resurrectHealth)
19707 SetHealth( m_resurrectHealth );
19708 else
19709 SetHealth( GetMaxHealth() );
19711 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
19712 SetPower(POWER_MANA, m_resurrectMana );
19713 else
19714 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
19716 SetPower(POWER_RAGE, 0 );
19718 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
19720 SpawnCorpseBones();
19723 void Player::SetClientControl(Unit* target, uint8 allowMove)
19725 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
19726 data.append(target->GetPackGUID());
19727 data << uint8(allowMove);
19728 GetSession()->SendPacket(&data);
19731 void Player::UpdateZoneDependentAuras( uint32 newZone )
19733 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19734 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newZone);
19735 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19736 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
19737 if( !HasAura(itr->second->spellId,0) )
19738 CastSpell(this,itr->second->spellId,true);
19741 void Player::UpdateAreaDependentAuras( uint32 newArea )
19743 // remove auras from spells with area limitations
19744 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
19746 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19747 if(sSpellMgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
19748 RemoveAura(iter);
19749 else
19750 ++iter;
19753 // some auras applied at subzone enter
19754 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newArea);
19755 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19756 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
19757 if( !HasAura(itr->second->spellId,0) )
19758 CastSpell(this,itr->second->spellId,true);
19761 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
19763 if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
19764 (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
19766 return copseReclaimDelay[0];
19769 time_t now = time(NULL);
19770 // 0..2 full period
19771 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
19772 return copseReclaimDelay[count];
19775 void Player::UpdateCorpseReclaimDelay()
19777 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
19779 if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
19780 (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
19781 return;
19783 time_t now = time(NULL);
19784 if(now < m_deathExpireTime)
19786 // full and partly periods 1..3
19787 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
19788 if(count < MAX_DEATH_COUNT)
19789 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19790 else
19791 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19793 else
19794 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19797 void Player::SendCorpseReclaimDelay(bool load)
19799 Corpse* corpse = GetCorpse();
19800 if(!corpse)
19801 return;
19803 uint32 delay;
19804 if(load)
19806 if(corpse->GetGhostTime() > m_deathExpireTime)
19807 return;
19809 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19811 uint32 count;
19812 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19813 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19815 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19816 if(count>=MAX_DEATH_COUNT)
19817 count = MAX_DEATH_COUNT-1;
19819 else
19820 count=0;
19822 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19824 time_t now = time(NULL);
19825 if(now >= expected_time)
19826 return;
19828 delay = expected_time-now;
19830 else
19831 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19833 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19834 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19835 data << uint32(delay*IN_MILISECONDS);
19836 GetSession()->SendPacket( &data );
19839 Player* Player::GetNextRandomRaidMember(float radius)
19841 Group *pGroup = GetGroup();
19842 if(!pGroup)
19843 return NULL;
19845 std::vector<Player*> nearMembers;
19846 nearMembers.reserve(pGroup->GetMembersCount());
19848 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19850 Player* Target = itr->getSource();
19852 // IsHostileTo check duel and controlled by enemy
19853 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19854 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19855 nearMembers.push_back(Target);
19858 if (nearMembers.empty())
19859 return NULL;
19861 uint32 randTarget = urand(0,nearMembers.size()-1);
19862 return nearMembers[randTarget];
19865 PartyResult Player::CanUninviteFromGroup() const
19867 const Group* grp = GetGroup();
19868 if(!grp)
19869 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19871 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19872 return PARTY_RESULT_YOU_NOT_LEADER;
19874 if(InBattleGround())
19875 return PARTY_RESULT_INVITE_RESTRICTED;
19877 return PARTY_RESULT_OK;
19880 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
19882 //we must move references from m_group to m_originalGroup
19883 SetOriginalGroup(GetGroup(), GetSubGroup());
19885 m_group.unlink();
19886 m_group.link(group, this);
19887 m_group.setSubGroup((uint8)subgroup);
19890 void Player::RemoveFromBattleGroundRaid()
19892 //remove existing reference
19893 m_group.unlink();
19894 if( Group* group = GetOriginalGroup() )
19896 m_group.link(group, this);
19897 m_group.setSubGroup(GetOriginalSubGroup());
19899 SetOriginalGroup(NULL);
19902 void Player::SetOriginalGroup(Group *group, int8 subgroup)
19904 if( group == NULL )
19905 m_originalGroup.unlink();
19906 else
19908 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19909 assert(subgroup >= 0);
19910 m_originalGroup.link(group, this);
19911 m_originalGroup.setSubGroup((uint8)subgroup);
19915 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19917 LiquidData liquid_status;
19918 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
19919 if (!res)
19921 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
19922 // Small hack for enable breath in WMO
19923 if (IsInWater())
19924 m_MirrorTimerFlags|=UNDERWATER_INWATER;
19925 return;
19928 // All liquids type - check under water position
19929 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
19931 if ( res & LIQUID_MAP_UNDER_WATER)
19932 m_MirrorTimerFlags |= UNDERWATER_INWATER;
19933 else
19934 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
19937 // Allow travel in dark water on taxi or transport
19938 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
19939 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
19940 else
19941 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
19943 // in lava check, anywhere in lava level
19944 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
19946 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19947 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
19948 else
19949 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
19951 // in slime check, anywhere in slime level
19952 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
19954 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19955 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
19956 else
19957 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
19961 void Player::SetCanParry( bool value )
19963 if(m_canParry==value)
19964 return;
19966 m_canParry = value;
19967 UpdateParryPercentage();
19970 void Player::SetCanBlock( bool value )
19972 if(m_canBlock==value)
19973 return;
19975 m_canBlock = value;
19976 UpdateBlockPercentage();
19979 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19981 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19982 if(itr->pos == pos)
19983 return true;
19985 return false;
19988 bool Player::CanUseBattleGroundObject()
19990 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19991 // maybe gameobject code should handle that ForceReaction usage
19992 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19993 return ( //InBattleGround() && // in battleground - not need, check in other cases
19994 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19995 //player cannot use object when he is invulnerable (immune)
19996 !isTotalImmune() && // not totally immune
19997 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19998 !HasStealthAura() && // not stealthed
19999 !HasInvisibilityAura() && // not invisible
20000 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
20001 isAlive() // live player
20005 bool Player::CanCaptureTowerPoint()
20007 return ( !HasStealthAura() && // not stealthed
20008 !HasInvisibilityAura() && // not invisible
20009 isAlive() // live player
20013 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
20015 uint32 level = getLevel();
20017 if(level > GT_MAX_LEVEL)
20018 level = GT_MAX_LEVEL; // max level in this dbc
20020 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
20021 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
20022 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
20024 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
20025 return 0;
20027 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
20029 if(!bsc) // shouldn't happen
20030 return 0xFFFFFFFF;
20032 float cost = 0;
20034 if(hairstyle != newhairstyle)
20035 cost += bsc->cost; // full price
20037 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
20038 cost += bsc->cost * 0.5f; // +1/2 of price
20040 if(facialhair != newfacialhair)
20041 cost += bsc->cost * 0.75f; // +3/4 of price
20043 return uint32(cost);
20046 void Player::InitGlyphsForLevel()
20048 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
20049 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
20050 if(gs->Order)
20051 SetGlyphSlot(gs->Order - 1, gs->Id);
20053 uint32 level = getLevel();
20054 uint32 value = 0;
20056 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
20057 if(level >= 15)
20058 value |= (0x01 | 0x02);
20059 if(level >= 30)
20060 value |= 0x08;
20061 if(level >= 50)
20062 value |= 0x04;
20063 if(level >= 70)
20064 value |= 0x10;
20065 if(level >= 80)
20066 value |= 0x20;
20068 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
20071 void Player::EnterVehicle(Vehicle *vehicle)
20073 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
20074 if(!ve)
20075 return;
20077 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
20078 if(!veSeat)
20079 return;
20081 vehicle->SetCharmerGUID(GetGUID());
20082 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20083 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20084 vehicle->setFaction(getFaction());
20086 SetCharm(vehicle); // charm
20087 SetFarSightGUID(vehicle->GetGUID()); // set view
20089 SetClientControl(vehicle, 1); // redirect controls to vehicle
20090 SetMover(vehicle);
20092 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
20093 GetSession()->SendPacket(&data);
20095 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
20096 data.append(GetPackGUID());
20097 data << uint32(0); // counter?
20098 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
20099 data << uint16(0); // special flags
20100 data << uint32(getMSTime()); // time
20101 data << vehicle->GetPositionX(); // x
20102 data << vehicle->GetPositionY(); // y
20103 data << vehicle->GetPositionZ(); // z
20104 data << vehicle->GetOrientation(); // o
20105 // transport part, TODO: load/calculate seat offsets
20106 data << uint64(vehicle->GetGUID()); // transport guid
20107 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
20108 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
20109 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
20110 data << float(0); // transport orientation
20111 data << uint32(getMSTime()); // transport time
20112 data << uint8(0); // seat
20113 // end of transport part
20114 data << uint32(0); // fall time
20115 GetSession()->SendPacket(&data);
20117 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
20118 data << uint64(vehicle->GetGUID());
20119 data << uint16(0);
20120 data << uint32(0);
20121 data << uint32(0x00000101);
20123 for(uint32 i = 0; i < 10; ++i)
20124 data << uint16(0) << uint8(0) << uint8(i+8);
20126 data << uint8(0);
20127 data << uint8(0);
20128 GetSession()->SendPacket(&data);
20131 void Player::ExitVehicle(Vehicle *vehicle)
20133 vehicle->SetCharmerGUID(0);
20134 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20135 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20136 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
20138 SetCharm(NULL);
20139 SetFarSightGUID(0);
20141 SetClientControl(vehicle, 0);
20142 SetMover(NULL);
20144 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
20145 data.append(GetPackGUID());
20146 data << uint32(0); // counter?
20147 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
20148 data << uint16(0x40); // special flags
20149 data << uint32(getMSTime()); // time
20150 data << vehicle->GetPositionX(); // x
20151 data << vehicle->GetPositionY(); // y
20152 data << vehicle->GetPositionZ(); // z
20153 data << vehicle->GetOrientation(); // o
20154 data << uint32(0); // fall time
20155 GetSession()->SendPacket(&data);
20157 RemovePetActionBar();
20159 // maybe called at dummy aura remove?
20160 // CastSpell(this, 45472, true); // Parachute
20163 bool Player::isTotalImmune()
20165 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
20167 uint32 immuneMask = 0;
20168 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
20170 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
20171 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
20172 return true;
20174 return false;
20177 bool Player::HasTitle(uint32 bitIndex)
20179 if (bitIndex > MAX_TITLE_INDEX)
20180 return false;
20182 uint32 fieldIndexOffset = bitIndex / 32;
20183 uint32 flag = 1 << (bitIndex % 32);
20184 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20187 void Player::SetTitle(CharTitlesEntry const* title, bool lost)
20189 uint32 fieldIndexOffset = title->bit_index / 32;
20190 uint32 flag = 1 << (title->bit_index % 32);
20192 if(lost)
20194 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20195 return;
20197 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20199 else
20201 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20202 return;
20204 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20207 WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
20208 data << uint32(title->bit_index);
20209 data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
20210 GetSession()->SendPacket(&data);
20213 void Player::ConvertRune(uint8 index, RuneType newType)
20215 SetCurrentRune(index, newType);
20217 WorldPacket data(SMSG_CONVERT_RUNE, 2);
20218 data << uint8(index);
20219 data << uint8(newType);
20220 GetSession()->SendPacket(&data);
20223 void Player::ResyncRunes(uint8 count)
20225 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
20226 for(uint32 i = 0; i < count; ++i)
20228 data << uint8(GetCurrentRune(i)); // rune type
20229 data << uint8(255 - ((GetRuneCooldown(i) / REGEN_TIME_FULL) * 51)); // passed cooldown time (0-255)
20231 GetSession()->SendPacket(&data);
20234 void Player::AddRunePower(uint8 index)
20236 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
20237 data << uint32(1 << index); // mask (0x00-0x3F probably)
20238 GetSession()->SendPacket(&data);
20241 static RuneType runeSlotTypes[MAX_RUNES] = {
20242 /*0*/ RUNE_BLOOD,
20243 /*1*/ RUNE_BLOOD,
20244 /*2*/ RUNE_UNHOLY,
20245 /*3*/ RUNE_UNHOLY,
20246 /*4*/ RUNE_FROST,
20247 /*5*/ RUNE_FROST
20250 void Player::InitRunes()
20252 if(getClass() != CLASS_DEATH_KNIGHT)
20253 return;
20255 m_runes = new Runes;
20257 m_runes->runeState = 0;
20259 for(uint32 i = 0; i < MAX_RUNES; ++i)
20261 SetBaseRune(i, runeSlotTypes[i]); // init base types
20262 SetCurrentRune(i, runeSlotTypes[i]); // init current types
20263 SetRuneCooldown(i, 0); // reset cooldowns
20264 m_runes->SetRuneState(i);
20267 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
20268 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
20272 bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType ) const
20274 for(uint32 i = 0; i < MAX_RUNES; ++i)
20275 if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
20276 return false;
20278 return true;
20281 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
20283 Loot loot;
20284 loot.FillLoot (loot_id,store,this,true);
20286 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
20287 for(uint32 i = 0; i < max_slot; ++i)
20289 LootItem* lootItem = loot.LootItemInSlot(i,this);
20291 ItemPosCountVec dest;
20292 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
20293 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
20294 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20295 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
20296 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20297 if(msg != EQUIP_ERR_OK)
20299 SendEquipError( msg, NULL, NULL );
20300 continue;
20303 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
20304 SendNewItem(pItem, lootItem->count, false, false, broadcast);
20308 uint32 Player::CalculateTalentsPoints() const
20310 uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
20312 if(getClass() != CLASS_DEATH_KNIGHT)
20313 return uint32(base_talent * sWorld.getRate(RATE_TALENT));
20315 uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
20316 talentPointsForLevel += m_questRewardTalentCount;
20318 if(talentPointsForLevel > base_talent)
20319 talentPointsForLevel = base_talent;
20321 return uint32(talentPointsForLevel * sWorld.getRate(RATE_TALENT));
20324 bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
20326 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
20327 uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
20328 return v_map != 571 || HasSpell(54197); // Cold Weather Flying
20331 struct DoPlayerLearnSpell
20333 DoPlayerLearnSpell(Player& _player) : player(_player) {}
20334 void operator() (uint32 spell_id) { player.learnSpell(spell_id,false); }
20335 Player& player;
20338 void Player::learnSpellHighRank(uint32 spellid)
20340 learnSpell(spellid,false);
20342 DoPlayerLearnSpell worker(*this);
20343 sSpellMgr.doForHighRanks(spellid,worker);
20346 void Player::_LoadSkills(QueryResult *result)
20348 // 0 1 2
20349 // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
20351 uint32 count = 0;
20352 if (result)
20356 Field *fields = result->Fetch();
20358 uint16 skill = fields[0].GetUInt16();
20359 uint16 value = fields[1].GetUInt16();
20360 uint16 max = fields[2].GetUInt16();
20362 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(skill);
20363 if(!pSkill)
20365 sLog.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill);
20366 continue;
20369 // set fixed skill ranges
20370 switch(GetSkillRangeType(pSkill,false))
20372 case SKILL_RANGE_LANGUAGE: // 300..300
20373 value = max = 300;
20374 break;
20375 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
20376 value = max = 1;
20377 break;
20378 default:
20379 break;
20382 if(value == 0)
20384 sLog.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
20385 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill );
20386 continue;
20389 // enable unlearn button for primary professions only
20390 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
20391 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,1));
20392 else
20393 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,0));
20395 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),MAKE_SKILL_VALUE(value, max));
20396 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20398 mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
20400 learnSkillRewardedSpells(skill, value);
20402 ++count;
20404 if(count >= PLAYER_MAX_SKILLS) // client limit
20406 sLog.outError("Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS);
20407 break;
20409 } while (result->NextRow());
20410 delete result;
20413 for (; count < PLAYER_MAX_SKILLS; ++count)
20415 SetUInt32Value(PLAYER_SKILL_INDEX(count), 0);
20416 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),0);
20417 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20420 // special settings
20421 if(getClass()==CLASS_DEATH_KNIGHT)
20423 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
20424 if(base_level < 1)
20425 base_level = 1;
20426 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
20427 if(base_skill < 1)
20428 base_skill = 1; // skill mast be known and then > 0 in any case
20430 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
20431 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
20432 if(GetPureSkillValue (SKILL_AXES) < base_skill)
20433 SetSkill(SKILL_AXES, base_skill,base_skill);
20434 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
20435 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
20436 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
20437 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
20438 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
20439 SetSkill(SKILL_SWORDS, base_skill,base_skill);
20440 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
20441 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
20442 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
20443 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
20444 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
20445 SetSkill(SKILL_UNARMED, base_skill,base_skill);
20449 uint32 Player::GetPhaseMaskForSpawn() const
20451 uint32 phase = PHASEMASK_NORMAL;
20452 if(!isGameMaster())
20453 phase = GetPhaseMask();
20454 else
20456 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
20457 if(!phases.empty())
20458 phase = phases.front()->GetMiscValue();
20461 // some aura phases include 1 normal map in addition to phase itself
20462 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
20463 return n_phase;
20465 return PHASEMASK_NORMAL;
20468 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
20470 ItemPrototype const* pProto = pItem->GetProto();
20472 // proto based limitations
20473 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
20474 return res;
20476 // check unique-equipped on gems
20477 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
20479 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
20480 if(!enchant_id)
20481 continue;
20482 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
20483 if(!enchantEntry)
20484 continue;
20486 ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID);
20487 if(!pGem)
20488 continue;
20490 // include for check equip another gems with same limit category for not equipped item (and then not counted)
20491 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
20492 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
20494 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
20495 return res;
20498 return EQUIP_ERR_OK;
20501 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
20503 // check unique-equipped on item
20504 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
20506 // there is an equip limit on this item
20507 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
20508 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20511 // check unique-equipped limit
20512 if (itemProto->ItemLimitCategory)
20514 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
20515 if(!limitEntry)
20516 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20518 if(limit_count > limitEntry->maxCount)
20519 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
20521 // there is an equip limit on this item
20522 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
20523 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20526 return EQUIP_ERR_OK;
20529 void Player::HandleFall(MovementInfo const& movementInfo)
20531 // calculate total z distance of the fall
20532 float z_diff = m_lastFallZ - movementInfo.z;
20533 sLog.outDebug("zDiff = %f", z_diff);
20535 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
20536 // 14.57 can be calculated by resolving damageperc formula below to 0
20537 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
20538 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
20539 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
20541 //Safe fall, fall height reduction
20542 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
20544 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
20546 if(damageperc >0 )
20548 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
20550 float height = movementInfo.z;
20551 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
20553 if (damage > 0)
20555 //Prevent fall damage from being more than the player maximum health
20556 if (damage > GetMaxHealth())
20557 damage = GetMaxHealth();
20559 // Gust of Wind
20560 if (GetDummyAura(43621))
20561 damage = GetMaxHealth()/2;
20563 uint32 original_health = GetHealth();
20564 uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
20566 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
20567 if (isAlive() && final_damage < original_health)
20568 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
20571 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
20572 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.z, height, GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall);
20577 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
20579 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
20582 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
20584 uint32 CurTalentPoints = GetFreeTalentPoints();
20586 if(CurTalentPoints == 0)
20587 return;
20589 if (talentRank >= MAX_TALENT_RANK)
20590 return;
20592 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
20594 if(!talentInfo)
20595 return;
20597 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
20599 if(!talentTabInfo)
20600 return;
20602 // prevent learn talent for different class (cheating)
20603 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
20604 return;
20606 // find current max talent rank
20607 int32 curtalent_maxrank = 0;
20608 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20610 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20612 curtalent_maxrank = k + 1;
20613 break;
20617 // we already have same or higher talent rank learned
20618 if(curtalent_maxrank >= (talentRank + 1))
20619 return;
20621 // check if we have enough talent points
20622 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20623 return;
20625 // Check if it requires another talent
20626 if (talentInfo->DependsOn > 0)
20628 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20630 bool hasEnoughRank = false;
20631 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20633 if (depTalentInfo->RankID[i] != 0)
20634 if (HasSpell(depTalentInfo->RankID[i]))
20635 hasEnoughRank = true;
20637 if (!hasEnoughRank)
20638 return;
20642 // Find out how many points we have in this field
20643 uint32 spentPoints = 0;
20645 uint32 tTab = talentInfo->TalentTab;
20646 if (talentInfo->Row > 0)
20648 unsigned int numRows = sTalentStore.GetNumRows();
20649 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20651 // Someday, someone needs to revamp
20652 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20653 if (tmpTalent) // the way talents are tracked
20655 if (tmpTalent->TalentTab == tTab)
20657 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20659 if (tmpTalent->RankID[j] != 0)
20661 if (HasSpell(tmpTalent->RankID[j]))
20663 spentPoints += j + 1;
20672 // not have required min points spent in talent tree
20673 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
20674 return;
20676 // spell not set in talent.dbc
20677 uint32 spellid = talentInfo->RankID[talentRank];
20678 if( spellid == 0 )
20680 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20681 return;
20684 // already known
20685 if(HasSpell(spellid))
20686 return;
20688 // learn! (other talent ranks will unlearned at learning)
20689 learnSpell(spellid, false);
20690 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20692 // update free talent points
20693 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20696 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
20698 Pet *pet = GetPet();
20700 if(!pet)
20701 return;
20703 if(petGuid != pet->GetGUID())
20704 return;
20706 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
20708 if(CurTalentPoints == 0)
20709 return;
20711 if (talentRank >= MAX_PET_TALENT_RANK)
20712 return;
20714 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
20716 if(!talentInfo)
20717 return;
20719 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
20721 if(!talentTabInfo)
20722 return;
20724 CreatureInfo const *ci = pet->GetCreatureInfo();
20726 if(!ci)
20727 return;
20729 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20731 if(!pet_family)
20732 return;
20734 if(pet_family->petTalentType < 0) // not hunter pet
20735 return;
20737 // prevent learn talent for different family (cheating)
20738 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20739 return;
20741 // find current max talent rank
20742 int32 curtalent_maxrank = 0;
20743 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20745 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20747 curtalent_maxrank = k + 1;
20748 break;
20752 // we already have same or higher talent rank learned
20753 if(curtalent_maxrank >= (talentRank + 1))
20754 return;
20756 // check if we have enough talent points
20757 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20758 return;
20760 // Check if it requires another talent
20761 if (talentInfo->DependsOn > 0)
20763 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20765 bool hasEnoughRank = false;
20766 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20768 if (depTalentInfo->RankID[i] != 0)
20769 if (pet->HasSpell(depTalentInfo->RankID[i]))
20770 hasEnoughRank = true;
20772 if (!hasEnoughRank)
20773 return;
20777 // Find out how many points we have in this field
20778 uint32 spentPoints = 0;
20780 uint32 tTab = talentInfo->TalentTab;
20781 if (talentInfo->Row > 0)
20783 unsigned int numRows = sTalentStore.GetNumRows();
20784 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20786 // Someday, someone needs to revamp
20787 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20788 if (tmpTalent) // the way talents are tracked
20790 if (tmpTalent->TalentTab == tTab)
20792 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20794 if (tmpTalent->RankID[j] != 0)
20796 if (pet->HasSpell(tmpTalent->RankID[j]))
20798 spentPoints += j + 1;
20807 // not have required min points spent in talent tree
20808 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
20809 return;
20811 // spell not set in talent.dbc
20812 uint32 spellid = talentInfo->RankID[talentRank];
20813 if( spellid == 0 )
20815 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20816 return;
20819 // already known
20820 if(pet->HasSpell(spellid))
20821 return;
20823 // learn! (other talent ranks will unlearned at learning)
20824 pet->learnSpell(spellid);
20825 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20827 // update free talent points
20828 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20831 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
20833 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
20835 if(apply)
20836 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
20837 else
20838 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
20842 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
20844 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
20845 SetFallInformation(minfo.fallTime, minfo.z);
20848 void Player::UnsummonPetTemporaryIfAny()
20850 Pet* pet = GetPet();
20851 if(!pet)
20852 return;
20854 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
20856 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
20857 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
20860 RemovePet(pet, PET_SAVE_AS_CURRENT);
20863 void Player::ResummonPetTemporaryUnSummonedIfAny()
20865 if(!m_temporaryUnsummonedPetNumber)
20866 return;
20868 // not resummon in not appropriate state
20869 if(IsPetNeedBeTemporaryUnsummoned())
20870 return;
20872 if(GetPetGUID())
20873 return;
20875 Pet* NewPet = new Pet;
20876 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
20877 delete NewPet;
20879 m_temporaryUnsummonedPetNumber = 0;
20882 bool Player::canSeeSpellClickOn(Creature const *c) const
20884 if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
20885 return false;
20887 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(c->GetEntry());
20888 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
20889 if(itr->second.IsFitToRequirements(this))
20890 return true;
20892 return false;
20895 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
20897 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
20898 *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
20899 *data << uint8(m_activeSpec); // talent group index (0 or 1)
20901 if(m_specsCount)
20903 // loop through all specs (only 1 for now)
20904 for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
20906 uint8 talentIdCount = 0;
20907 size_t pos = data->wpos();
20908 *data << uint8(talentIdCount); // [PH], talentIdCount
20910 // find class talent tabs (all players have 3 talent tabs)
20911 uint32 const* talentTabIds = GetTalentTabPages(getClass());
20913 for(uint32 i = 0; i < 3; ++i)
20915 uint32 talentTabId = talentTabIds[i];
20917 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20919 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20920 if(!talentInfo)
20921 continue;
20923 // skip another tab talents
20924 if(talentInfo->TalentTab != talentTabId)
20925 continue;
20927 // find max talent rank
20928 int32 curtalent_maxrank = -1;
20929 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20931 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20933 curtalent_maxrank = k;
20934 break;
20938 // not learned talent
20939 if(curtalent_maxrank < 0)
20940 continue;
20942 *data << uint32(talentInfo->TalentID); // Talent.dbc
20943 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20945 ++talentIdCount;
20949 data->put<uint8>(pos, talentIdCount); // put real count
20951 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
20953 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
20954 *data << uint16(GetGlyph(i)); // GlyphProperties.dbc
20959 void Player::BuildPetTalentsInfoData(WorldPacket *data)
20961 uint32 unspentTalentPoints = 0;
20962 size_t pointsPos = data->wpos();
20963 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
20965 uint8 talentIdCount = 0;
20966 size_t countPos = data->wpos();
20967 *data << uint8(talentIdCount); // [PH], talentIdCount
20969 Pet *pet = GetPet();
20970 if(!pet)
20971 return;
20973 unspentTalentPoints = pet->GetFreeTalentPoints();
20975 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
20977 CreatureInfo const *ci = pet->GetCreatureInfo();
20978 if(!ci)
20979 return;
20981 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20982 if(!pet_family || pet_family->petTalentType < 0)
20983 return;
20985 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
20987 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
20988 if(!talentTabInfo)
20989 continue;
20991 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20992 continue;
20994 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20996 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20997 if(!talentInfo)
20998 continue;
21000 // skip another tab talents
21001 if(talentInfo->TalentTab != talentTabId)
21002 continue;
21004 // find max talent rank
21005 int32 curtalent_maxrank = -1;
21006 for(int32 k = 4; k > -1; --k)
21008 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
21010 curtalent_maxrank = k;
21011 break;
21015 // not learned talent
21016 if(curtalent_maxrank < 0)
21017 continue;
21019 *data << uint32(talentInfo->TalentID); // Talent.dbc
21020 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
21022 ++talentIdCount;
21025 data->put<uint8>(countPos, talentIdCount); // put real count
21027 break;
21031 void Player::SendTalentsInfoData(bool pet)
21033 WorldPacket data(SMSG_TALENTS_INFO, 50);
21034 data << uint8(pet ? 1 : 0);
21035 if(pet)
21036 BuildPetTalentsInfoData(&data);
21037 else
21038 BuildPlayerTalentsInfoData(&data);
21039 GetSession()->SendPacket(&data);
21042 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
21044 uint32 slotUsedMask = 0;
21045 size_t slotUsedMaskPos = data->wpos();
21046 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
21048 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21050 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
21052 if(!item)
21053 continue;
21055 slotUsedMask |= (1 << i);
21057 *data << uint32(item->GetEntry()); // item entry
21059 uint16 enchantmentMask = 0;
21060 size_t enchantmentMaskPos = data->wpos();
21061 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
21063 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
21065 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
21067 if(!enchId)
21068 continue;
21070 enchantmentMask |= (1 << j);
21072 *data << uint16(enchId); // enchantmentId?
21075 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
21077 *data << uint16(0); // ?
21078 *data << uint8(0); // PGUID!
21079 *data << uint32(0); // seed?
21082 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
21085 void Player::SendEquipmentSetList()
21087 uint32 count = 0;
21088 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
21089 size_t count_pos = data.wpos();
21090 data << uint32(count); // count placeholder
21091 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21093 if(itr->second.state==EQUIPMENT_SET_DELETED)
21094 continue;
21095 data.appendPackGUID(itr->second.Guid);
21096 data << uint32(itr->first);
21097 data << itr->second.Name;
21098 data << itr->second.IconName;
21099 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21100 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
21102 ++count; // client have limit but it checked at loading and set
21104 data.put<uint32>(count_pos, count);
21105 GetSession()->SendPacket(&data);
21108 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
21110 if(eqset.Guid != 0)
21112 bool found = false;
21114 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21116 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
21118 found = true;
21119 break;
21123 if(!found) // something wrong...
21125 sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
21126 return;
21130 EquipmentSet& eqslot = m_EquipmentSets[index];
21132 EquipmentSetUpdateState old_state = eqslot.state;
21134 eqslot = eqset;
21136 if(eqset.Guid == 0)
21138 eqslot.Guid = sObjectMgr.GenerateEquipmentSetGuid();
21140 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
21141 data << uint32(index);
21142 data.appendPackGUID(eqslot.Guid);
21143 GetSession()->SendPacket(&data);
21146 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
21149 void Player::_SaveEquipmentSets()
21151 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
21153 uint32 index = itr->first;
21154 EquipmentSet& eqset = itr->second;
21155 switch(eqset.state)
21157 case EQUIPMENT_SET_UNCHANGED:
21158 ++itr;
21159 break; // nothing do
21160 case EQUIPMENT_SET_CHANGED:
21161 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'",
21162 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],
21163 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);
21164 eqset.state = EQUIPMENT_SET_UNCHANGED;
21165 ++itr;
21166 break;
21167 case EQUIPMENT_SET_NEW:
21168 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')",
21169 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],
21170 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]);
21171 eqset.state = EQUIPMENT_SET_UNCHANGED;
21172 ++itr;
21173 break;
21174 case EQUIPMENT_SET_DELETED:
21175 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
21176 m_EquipmentSets.erase(itr++);
21177 break;
21182 void Player::_SaveBGData()
21184 CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
21185 if (m_bgData.bgInstanceID)
21187 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
21188 CharacterDatabase.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
21189 GetGUIDLow(), m_bgData.bgInstanceID, m_bgData.bgTeam, m_bgData.joinPos.coord_x, m_bgData.joinPos.coord_y, m_bgData.joinPos.coord_z,
21190 m_bgData.joinPos.orientation, m_bgData.joinPos.mapid, m_bgData.taxiPath[0], m_bgData.taxiPath[1], m_bgData.mountSpell);
21194 void Player::DeleteEquipmentSet(uint64 setGuid)
21196 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21198 if(itr->second.Guid == setGuid)
21200 if(itr->second.state == EQUIPMENT_SET_NEW)
21201 m_EquipmentSets.erase(itr);
21202 else
21203 itr->second.state = EQUIPMENT_SET_DELETED;
21204 break;
21209 void Player::ActivateSpec(uint32 specNum)
21211 if(GetActiveSpec() == specNum)
21212 return;
21214 resetTalents(true);
21217 void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
21219 m_atLoginFlags &= ~f;
21221 if(in_db_also)
21222 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
21225 void Player::SendClearCooldown( uint32 spell_id, Unit* target )
21227 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
21228 data << uint32(spell_id);
21229 data << uint64(target->GetGUID());
21230 SendDirectMessage(&data);
21233 void Player::BuildTeleportAckMsg( WorldPacket *data, float x, float y, float z, float ang ) const
21235 data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
21236 data->append(GetPackGUID());
21237 *data << uint32(0); // this value increments every time
21238 *data << uint32(m_movementInfo.GetMovementFlags()); // movement flags
21239 *data << uint16(0); // 2.3.0
21240 *data << uint32(getMSTime()); // time
21241 *data << x;
21242 *data << y;
21243 *data << z;
21244 *data << ang;
21245 *data << uint32(0);
21248 bool Player::HasMovementFlag( MovementFlags f ) const
21250 return m_movementInfo.HasMovementFlag(f);
21253 void Player::SetFarSightGUID( uint64 guid )
21255 if(GetFarSight() == guid)
21256 return;
21258 SetUInt64Value(PLAYER_FARSIGHT, guid);
21260 // need triggering load grids around new view point
21261 UpdateVisibilityForPlayer();
21264 void Player::UpdateVisibilityForPlayer()
21266 WorldObject const* viewPoint = GetViewPoint();
21267 Map* m = GetMap();
21269 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
21270 Cell cell(p);
21272 m->UpdatePlayerVisibility(this, cell, p);
21274 if (this != viewPoint)
21276 CellPair pView(MaNGOS::ComputeCellPair(viewPoint->GetPositionX(), viewPoint->GetPositionY()));
21277 Cell cellView(pView);
21279 m->UpdateObjectsVisibilityFor(this, cellView, pView);
21281 else
21282 m->UpdateObjectsVisibilityFor(this, cell, p);
21285 void Player::SendDuelCountdown(uint32 counter)
21287 WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
21288 data << uint32(counter); // seconds
21289 GetSession()->SendPacket(&data);
21292 bool Player::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
21294 switch(spellInfo->Effect[index])
21296 case SPELL_EFFECT_ATTACK_ME:
21297 return true;
21298 default:
21299 break;
21301 switch(spellInfo->EffectApplyAuraName[index])
21303 case SPELL_AURA_MOD_TAUNT:
21304 return true;
21305 default:
21306 break;
21308 return Unit::IsImmunedToSpellEffect(spellInfo, index);
21311 void Player::SetHomebindToCurrentPos()
21313 m_homebindMapId = GetMapId();
21314 m_homebindZoneId = GetZoneId();
21315 m_homebindX = GetPositionX();
21316 m_homebindY = GetPositionY();
21317 m_homebindZ = GetPositionZ();
21319 // update sql homebind
21320 CharacterDatabase.PExecute("UPDATE character_homebind SET map = '%u', zone = '%u', position_x = '%f', position_y = '%f', position_z = '%f' WHERE guid = '%u'",
21321 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ, GetGUIDLow());