[9362] Make specs work at least for action bars
[getmangos.git] / src / game / Player.cpp
blob635ee064879ca06e5cfeaf34ec4f0e78294db9a4
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 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, -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(0, 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 // just skip, reported in ObjectMgr::LoadItemPrototypes
705 ItemPrototype const* iProto = ObjectMgr::GetItemPrototype(item_id);
706 if(!iProto)
707 continue;
709 // BuyCount by default
710 int32 count = iProto->BuyCount;
712 // special amount for foor/drink
713 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
715 switch(iProto->Spells[0].SpellCategory)
717 case 11: // food
718 count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4;
719 break;
720 case 59: // drink
721 count = 2;
722 break;
724 if(iProto->Stackable < count)
725 count = iProto->Stackable;
727 // special amount for daggers
728 else if(iProto->Class==ITEM_CLASS_WEAPON && iProto->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER)
730 count = 2; // will placed to 2 slots
733 StoreNewItemInBestSlots(item_id, count);
737 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
738 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
740 // bags and main-hand weapon must equipped at this moment
741 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
742 // or ammo not equipped in special bag
743 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
745 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
747 uint16 eDest;
748 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
749 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
750 if( msg == EQUIP_ERR_OK )
752 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
753 EquipItem( eDest, pItem, true);
755 // move other items to more appropriate slots (ammo not equipped in special bag)
756 else
758 ItemPosCountVec sDest;
759 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
760 if( msg == EQUIP_ERR_OK )
762 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
763 pItem = StoreItem( sDest, pItem, true);
766 // if this is ammo then use it
767 msg = CanUseAmmo( pItem->GetEntry() );
768 if( msg == EQUIP_ERR_OK )
769 SetAmmo( pItem->GetEntry() );
773 // all item positions resolved
775 return true;
778 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
780 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
782 // attempt equip by one
783 while(titem_amount > 0)
785 uint16 eDest;
786 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
787 if( msg != EQUIP_ERR_OK )
788 break;
790 EquipNewItem( eDest, titem_id, true);
791 AutoUnequipOffhandIfNeed();
792 --titem_amount;
795 if(titem_amount == 0)
796 return true; // equipped
798 // attempt store
799 ItemPosCountVec sDest;
800 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
801 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
802 if( msg == EQUIP_ERR_OK )
804 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
805 return true; // stored
808 // item can't be added
809 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
810 return false;
813 // helper function, mainly for script side, but can be used for simple task in mangos also.
814 Item* Player::StoreNewItemInInventorySlot(uint32 itemEntry, uint32 amount)
816 ItemPosCountVec vDest;
818 uint8 msg = CanStoreNewItem(INVENTORY_SLOT_BAG_0, NULL_SLOT, vDest, itemEntry, amount);
820 if (msg == EQUIP_ERR_OK)
822 if (Item* pItem = StoreNewItem(vDest, itemEntry, true, Item::GenerateItemRandomPropertyId(itemEntry)))
823 return pItem;
826 return NULL;
829 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
831 if (int(MaxValue) == DISABLED_MIRROR_TIMER)
833 if (int(CurrentValue) != DISABLED_MIRROR_TIMER)
834 StopMirrorTimer(Type);
835 return;
837 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
838 data << (uint32)Type;
839 data << CurrentValue;
840 data << MaxValue;
841 data << Regen;
842 data << (uint8)0;
843 data << (uint32)0; // spell id
844 GetSession()->SendPacket( &data );
847 void Player::StopMirrorTimer(MirrorTimerType Type)
849 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
850 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
851 data << (uint32)Type;
852 GetSession()->SendPacket( &data );
855 uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
857 if(!isAlive() || isGameMaster())
858 return 0;
860 // Absorb, resist some environmental damage type
861 uint32 absorb = 0;
862 uint32 resist = 0;
863 if (type == DAMAGE_LAVA)
864 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
865 else if (type == DAMAGE_SLIME)
866 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
868 damage-=absorb+resist;
870 DealDamageMods(this,damage,&absorb);
872 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
873 data << uint64(GetGUID());
874 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
875 data << uint32(damage);
876 data << uint32(absorb);
877 data << uint32(resist);
878 SendMessageToSet(&data, true);
880 uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
882 if(!isAlive())
884 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
886 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
887 DurabilityLossAll(0.10f,false);
888 // durability lost message
889 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
890 GetSession()->SendPacket(&data2);
893 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
896 return final_damage;
899 int32 Player::getMaxTimer(MirrorTimerType timer)
901 switch (timer)
903 case FATIGUE_TIMER:
904 if (GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_TIMERBAR_FATIGUE_GMLEVEL))
905 return DISABLED_MIRROR_TIMER;
906 return sWorld.getConfig(CONFIG_TIMERBAR_FATIGUE_MAX)*IN_MILISECONDS;
907 case BREATH_TIMER:
909 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) ||
910 GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_TIMERBAR_BREATH_GMLEVEL))
911 return DISABLED_MIRROR_TIMER;
912 int32 UnderWaterTime = sWorld.getConfig(CONFIG_TIMERBAR_BREATH_MAX)*IN_MILISECONDS;
913 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
914 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
915 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
916 return UnderWaterTime;
918 case FIRE_TIMER:
920 if (!isAlive() || GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_TIMERBAR_FIRE_GMLEVEL))
921 return DISABLED_MIRROR_TIMER;
922 return sWorld.getConfig(CONFIG_TIMERBAR_FIRE_MAX)*IN_MILISECONDS;
924 default:
925 return 0;
927 return 0;
930 void Player::UpdateMirrorTimers()
932 // Desync flags for update on next HandleDrowning
933 if (m_MirrorTimerFlags)
934 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
937 void Player::HandleDrowning(uint32 time_diff)
939 if (!m_MirrorTimerFlags)
940 return;
942 // In water
943 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
945 // Breath timer not activated - activate it
946 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
948 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
949 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
951 else // If activated - do tick
953 m_MirrorTimer[BREATH_TIMER]-=time_diff;
954 // Timer limit - need deal damage
955 if (m_MirrorTimer[BREATH_TIMER] < 0)
957 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
958 // Calculate and deal damage
959 // TODO: Check this formula
960 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
961 EnvironmentalDamage(DAMAGE_DROWNING, damage);
963 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
964 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
967 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
969 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
970 // Need breath regen
971 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
972 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
973 StopMirrorTimer(BREATH_TIMER);
974 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
975 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
978 // In dark water
979 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
981 // Fatigue timer not activated - activate it
982 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
984 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
985 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
987 else
989 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
990 // Timer limit - need deal damage or teleport ghost to graveyard
991 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
993 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
994 if (isAlive()) // Calculate and deal damage
996 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
997 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
999 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
1000 RepopAtGraveyard();
1002 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
1003 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
1006 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
1008 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
1009 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
1010 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
1011 StopMirrorTimer(FATIGUE_TIMER);
1012 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
1013 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
1016 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
1018 // Breath timer not activated - activate it
1019 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
1020 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
1021 else
1023 m_MirrorTimer[FIRE_TIMER]-=time_diff;
1024 if (m_MirrorTimer[FIRE_TIMER] < 0)
1026 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
1027 // Calculate and deal damage
1028 // TODO: Check this formula
1029 uint32 damage = urand(600, 700);
1030 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
1031 EnvironmentalDamage(DAMAGE_LAVA, damage);
1032 else
1033 EnvironmentalDamage(DAMAGE_SLIME, damage);
1037 else
1038 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
1040 // Recheck timers flag
1041 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1042 for (int i = 0; i< MAX_TIMERS; ++i)
1043 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1045 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1046 break;
1048 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1051 ///The player sobers by 256 every 10 seconds
1052 void Player::HandleSobering()
1054 m_drunkTimer = 0;
1056 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1057 SetDrunkValue(drunk);
1060 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1062 if(value >= 23000)
1063 return DRUNKEN_SMASHED;
1064 if(value >= 12800)
1065 return DRUNKEN_DRUNK;
1066 if(value & 0xFFFE)
1067 return DRUNKEN_TIPSY;
1068 return DRUNKEN_SOBER;
1071 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1073 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1075 m_drunk = newDrunkenValue;
1076 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1078 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1080 // special drunk invisibility detection
1081 if(newDrunkenState >= DRUNKEN_DRUNK)
1082 m_detectInvisibilityMask |= (1<<6);
1083 else
1084 m_detectInvisibilityMask &= ~(1<<6);
1086 if(newDrunkenState == oldDrunkenState)
1087 return;
1089 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1090 data << uint64(GetGUID());
1091 data << uint32(newDrunkenState);
1092 data << uint32(itemId);
1094 SendMessageToSet(&data, true);
1097 void Player::Update( uint32 p_time )
1099 if(!IsInWorld())
1100 return;
1102 // undelivered mail
1103 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1105 SendNewMail();
1106 ++unReadMails;
1108 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1109 m_nextMailDelivereTime = 0;
1112 //used to implement delayed far teleports
1113 SetCanDelayTeleport(true);
1114 Unit::Update( p_time );
1115 SetCanDelayTeleport(false);
1117 // update player only attacks
1118 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1120 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1123 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1125 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1128 time_t now = time (NULL);
1130 UpdatePvPFlag(now);
1132 UpdateContestedPvP(p_time);
1134 UpdateDuelFlag(now);
1136 CheckDuelDistance(now);
1138 UpdateAfkReport(now);
1140 // Update items that have just a limited lifetime
1141 if (now>m_Last_tick)
1142 UpdateItemDuration(uint32(now- m_Last_tick));
1144 if (!m_timedquests.empty())
1146 std::set<uint32>::iterator iter = m_timedquests.begin();
1147 while (iter != m_timedquests.end())
1149 QuestStatusData& q_status = mQuestStatus[*iter];
1150 if( q_status.m_timer <= p_time )
1152 uint32 quest_id = *iter;
1153 ++iter; // current iter will be removed in FailQuest
1154 FailQuest(quest_id);
1156 else
1158 q_status.m_timer -= p_time;
1159 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1160 ++iter;
1165 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1167 Unit *pVictim = getVictim();
1168 if (pVictim && !IsNonMeleeSpellCasted(false))
1170 // default combat reach 10
1171 // TODO add weapon,skill check
1173 float pldistance = ATTACK_DISTANCE;
1175 if (isAttackReady(BASE_ATTACK))
1177 if(!IsWithinDistInMap(pVictim, pldistance))
1179 setAttackTimer(BASE_ATTACK,100);
1180 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1182 SendAttackSwingNotInRange();
1183 m_swingErrorMsg = 1;
1186 //120 degrees of radiant range
1187 else if( !HasInArc( 2*M_PI_F/3, pVictim ))
1189 setAttackTimer(BASE_ATTACK,100);
1190 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1192 SendAttackSwingBadFacingAttack();
1193 m_swingErrorMsg = 2;
1196 else
1198 m_swingErrorMsg = 0; // reset swing error state
1200 // prevent base and off attack in same time, delay attack at 0.2 sec
1201 if(haveOffhandWeapon())
1203 uint32 off_att = getAttackTimer(OFF_ATTACK);
1204 if(off_att < ATTACK_DISPLAY_DELAY)
1205 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1207 AttackerStateUpdate(pVictim, BASE_ATTACK);
1208 resetAttackTimer(BASE_ATTACK);
1212 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1214 if(!IsWithinDistInMap(pVictim, pldistance))
1216 setAttackTimer(OFF_ATTACK,100);
1218 else if( !HasInArc( 2*M_PI_F/3, pVictim ))
1220 setAttackTimer(OFF_ATTACK,100);
1222 else
1224 // prevent base and off attack in same time, delay attack at 0.2 sec
1225 uint32 base_att = getAttackTimer(BASE_ATTACK);
1226 if(base_att < ATTACK_DISPLAY_DELAY)
1227 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1228 // do attack
1229 AttackerStateUpdate(pVictim, OFF_ATTACK);
1230 resetAttackTimer(OFF_ATTACK);
1234 Unit *owner = pVictim->GetOwner();
1235 Unit *u = owner ? owner : pVictim;
1236 if(u->IsPvP() && (!duel || duel->opponent != u))
1238 UpdatePvP(true);
1239 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1244 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1246 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1248 int time_inn = time(NULL)-GetTimeInnEnter();
1249 if (time_inn >= 10) //freeze update
1251 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1252 //speed collect rest bonus (section/in hour)
1253 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1254 UpdateInnerTime(time(NULL));
1259 if (m_regenTimer)
1261 if(p_time >= m_regenTimer)
1262 m_regenTimer = 0;
1263 else
1264 m_regenTimer -= p_time;
1267 if (m_weaponChangeTimer > 0)
1269 if(p_time >= m_weaponChangeTimer)
1270 m_weaponChangeTimer = 0;
1271 else
1272 m_weaponChangeTimer -= p_time;
1275 if (m_zoneUpdateTimer > 0)
1277 if(p_time >= m_zoneUpdateTimer)
1279 uint32 newzone, newarea;
1280 GetZoneAndAreaId(newzone,newarea);
1282 if( m_zoneUpdateId != newzone )
1283 UpdateZone(newzone,newarea); // also update area
1284 else
1286 // use area updates as well
1287 // needed for free far all arenas for example
1288 if( m_areaUpdateId != newarea )
1289 UpdateArea(newarea);
1291 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1294 else
1295 m_zoneUpdateTimer -= p_time;
1298 if (isAlive())
1300 // if no longer casting, set regen power as soon as it is up.
1301 if (!IsUnderLastManaUseEffect())
1302 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
1304 if (!m_regenTimer)
1305 RegenerateAll();
1308 if (m_deathState == JUST_DIED)
1310 KillPlayer();
1313 if(m_nextSave > 0)
1315 if(p_time >= m_nextSave)
1317 // m_nextSave reseted in SaveToDB call
1318 SaveToDB();
1319 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1321 else
1323 m_nextSave -= p_time;
1327 //Handle Water/drowning
1328 HandleDrowning(p_time);
1330 //Handle detect stealth players
1331 if (m_DetectInvTimer > 0)
1333 if (p_time >= m_DetectInvTimer)
1335 HandleStealthedUnitsDetection();
1336 m_DetectInvTimer = 3000;
1338 else
1339 m_DetectInvTimer -= p_time;
1342 // Played time
1343 if (now > m_Last_tick)
1345 uint32 elapsed = uint32(now - m_Last_tick);
1346 m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
1347 m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
1348 m_Last_tick = now;
1351 if (m_drunk)
1353 m_drunkTimer += p_time;
1355 if (m_drunkTimer > 10*IN_MILISECONDS)
1356 HandleSobering();
1359 // not auto-free ghost from body in instances
1360 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1362 if(p_time >= m_deathTimer)
1364 m_deathTimer = 0;
1365 BuildPlayerRepop();
1366 RepopAtGraveyard();
1368 else
1369 m_deathTimer -= p_time;
1372 UpdateEnchantTime(p_time);
1373 UpdateHomebindTime(p_time);
1375 // group update
1376 SendUpdateToOutOfRangeGroupMembers();
1378 Pet* pet = GetPet();
1379 if(pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1381 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1384 //we should execute delayed teleports only for alive(!) players
1385 //because we don't want player's ghost teleported from graveyard
1386 if(IsHasDelayedTeleport() && isAlive())
1387 TeleportTo(m_teleport_dest, m_teleport_options);
1390 void Player::setDeathState(DeathState s)
1392 uint32 ressSpellId = 0;
1394 bool cur = isAlive();
1396 if(s == JUST_DIED && cur)
1398 // drunken state is cleared on death
1399 SetDrunkValue(0);
1400 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1401 ClearComboPoints();
1403 clearResurrectRequestData();
1405 // remove form before other mods to prevent incorrect stats calculation
1406 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1408 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1409 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1411 // remove uncontrolled pets
1412 RemoveMiniPet();
1414 // save value before aura remove in Unit::setDeathState
1415 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1417 // passive spell
1418 if(!ressSpellId)
1419 ressSpellId = GetResurrectionSpellId();
1420 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1421 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1422 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1424 Unit::setDeathState(s);
1426 // restore resurrection spell id for player after aura remove
1427 if(s == JUST_DIED && cur && ressSpellId)
1428 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1430 if(isAlive() && !cur)
1432 //clear aura case after resurrection by another way (spells will be applied before next death)
1433 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1435 // restore default warrior stance
1436 if(getClass()== CLASS_WARRIOR)
1437 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1441 bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1443 // 0 1 2 3 4 5 6 7
1444 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
1445 // 8 9 10 11 12 13 14
1446 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
1447 // 15 16 17 18 19 20
1448 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive "
1450 Field *fields = result->Fetch();
1452 uint32 guid = fields[0].GetUInt32();
1453 uint8 pRace = fields[2].GetUInt8();
1454 uint8 pClass = fields[3].GetUInt8();
1456 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(pRace, pClass);
1457 if(!info)
1459 sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
1460 return false;
1463 *p_data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
1464 *p_data << fields[1].GetString(); // name
1465 *p_data << uint8(pRace); // race
1466 *p_data << uint8(pClass); // class
1467 *p_data << uint8(fields[4].GetUInt8()); // gender
1469 uint32 playerBytes = fields[5].GetUInt32();
1470 *p_data << uint8(playerBytes); // skin
1471 *p_data << uint8(playerBytes >> 8); // face
1472 *p_data << uint8(playerBytes >> 16); // hair style
1473 *p_data << uint8(playerBytes >> 24); // hair color
1475 uint32 playerBytes2 = fields[6].GetUInt32();
1476 *p_data << uint8(playerBytes2 & 0xFF); // facial hair
1478 *p_data << uint8(fields[7].GetUInt8()); // level
1479 *p_data << uint32(fields[8].GetUInt32()); // zone
1480 *p_data << uint32(fields[9].GetUInt32()); // map
1482 *p_data << fields[10].GetFloat(); // x
1483 *p_data << fields[11].GetFloat(); // y
1484 *p_data << fields[12].GetFloat(); // z
1486 *p_data << uint32(fields[13].GetUInt32()); // guild id
1488 uint32 char_flags = 0;
1489 uint32 playerFlags = fields[14].GetUInt32();
1490 uint32 atLoginFlags = fields[15].GetUInt32();
1491 if(playerFlags & PLAYER_FLAGS_HIDE_HELM)
1492 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1493 if(playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
1494 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1495 if(playerFlags & PLAYER_FLAGS_GHOST)
1496 char_flags |= CHARACTER_FLAG_GHOST;
1497 if(atLoginFlags & AT_LOGIN_RENAME)
1498 char_flags |= CHARACTER_FLAG_RENAME;
1499 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
1501 if(!fields[20].GetCppString().empty())
1502 char_flags |= CHARACTER_FLAG_DECLINED;
1504 else
1505 char_flags |= CHARACTER_FLAG_DECLINED;
1507 *p_data << uint32(char_flags); // character flags
1508 // character customize flags
1509 *p_data << uint32(atLoginFlags & AT_LOGIN_CUSTOMIZE ? CHAR_CUSTOMIZE_FLAG_CUSTOMIZE : CHAR_CUSTOMIZE_FLAG_NONE);
1510 // First login
1511 *p_data << uint8(atLoginFlags & AT_LOGIN_FIRST ? 1 : 0);
1513 // Pets info
1515 uint32 petDisplayId = 0;
1516 uint32 petLevel = 0;
1517 uint32 petFamily = 0;
1519 // show pet at selection character in character list only for non-ghost character
1520 if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1522 uint32 entry = fields[16].GetUInt32();
1523 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1524 if(cInfo)
1526 petDisplayId = fields[17].GetUInt32();
1527 petLevel = fields[18].GetUInt32();
1528 petFamily = cInfo->family;
1532 *p_data << uint32(petDisplayId);
1533 *p_data << uint32(petLevel);
1534 *p_data << uint32(petFamily);
1537 // TODO: do not access data field here
1538 Tokens data = StrSplit(fields[19].GetCppString(), " ");
1540 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1542 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1543 uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
1544 const ItemPrototype * proto = ObjectMgr::GetItemPrototype(item_id);
1545 if(!proto)
1547 *p_data << uint32(0);
1548 *p_data << uint8(0);
1549 *p_data << uint32(0);
1550 continue;
1553 SpellItemEnchantmentEntry const *enchant = NULL;
1555 uint32 enchants = GetUInt32ValueFromArray(data, visualbase + 1);
1556 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1558 // values stored in 2 uint16
1559 uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16);
1560 if(!enchantId)
1561 continue;
1563 if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId)))
1564 break;
1567 *p_data << uint32(proto->DisplayInfoID);
1568 *p_data << uint8(proto->InventoryType);
1569 *p_data << uint32(enchant ? enchant->aura_id : 0);
1571 *p_data << uint32(0); // first bag display id
1572 *p_data << uint8(0); // first bag inventory type
1573 *p_data << uint32(0); // enchant?
1575 return true;
1578 bool Player::ToggleAFK()
1580 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1582 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1584 // afk player not allowed in battleground
1585 if(state && InBattleGround())
1586 LeaveBattleground();
1588 return state;
1591 bool Player::ToggleDND()
1593 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1595 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1598 uint8 Player::chatTag() const
1600 // it's bitmask
1601 // 0x8 - ??
1602 // 0x4 - gm
1603 // 0x2 - dnd
1604 // 0x1 - afk
1605 if(isGMChat())
1606 return 4;
1607 else if(isDND())
1608 return 3;
1609 if(isAFK())
1610 return 1;
1611 else
1612 return 0;
1615 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1617 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1619 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1620 return false;
1623 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1624 Pet* pet = GetPet();
1626 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1628 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1629 // don't let gm level > 1 either
1630 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1631 return false;
1633 // client without expansion support
1634 if(GetSession()->Expansion() < mEntry->Expansion())
1636 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1638 if(GetTransport())
1639 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1641 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1643 return false; // normal client can't teleport to this map...
1645 else
1647 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1650 // if we were on a transport, leave
1651 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1653 m_transport->RemovePassenger(this);
1654 m_transport = NULL;
1655 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
1658 // The player was ported to another map and looses the duel immediately.
1659 // We have to perform this check before the teleport, otherwise the
1660 // ObjectAccessor won't find the flag.
1661 if (duel && GetMapId() != mapid)
1663 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1664 if (obj)
1665 DuelComplete(DUEL_FLED);
1668 // reset movement flags at teleport, because player will continue move with these flags after teleport
1669 m_movementInfo.SetMovementFlags(MOVEFLAG_NONE);
1671 if ((GetMapId() == mapid) && (!m_transport))
1673 //lets reset far teleport flag if it wasn't reset during chained teleports
1674 SetSemaphoreTeleportFar(false);
1675 //setup delayed teleport flag
1676 SetDelayedTeleportFlag(IsCanDelayTeleport());
1677 //if teleport spell is casted in Unit::Update() func
1678 //then we need to delay it until update process will be finished
1679 if(IsHasDelayedTeleport())
1681 SetSemaphoreTeleportNear(true);
1682 //lets save teleport destination for player
1683 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1684 m_teleport_options = options;
1685 return true;
1688 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1690 //same map, only remove pet if out of range for new position
1691 if(pet && !pet->IsWithinDist3d(x, y, z, GetMap()->GetVisibilityDistance()))
1692 UnsummonPetTemporaryIfAny();
1695 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1696 CombatStop();
1698 // this will be used instead of the current location in SaveToDB
1699 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1700 SetFallInformation(0, z);
1702 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1703 // at client packet MSG_MOVE_TELEPORT_ACK
1704 SetSemaphoreTeleportNear(true);
1705 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1706 if(!GetSession()->PlayerLogout())
1708 WorldPacket data;
1709 BuildTeleportAckMsg(&data, x, y, z, orientation);
1710 GetSession()->SendPacket(&data);
1713 else
1715 // far teleport to another map
1716 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1717 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1719 // Check enter rights before map getting to avoid creating instance copy for player
1720 // this check not dependent from map instance copy and same for all instance copies of selected map
1721 if (!sMapMgr.CanPlayerEnter(mapid, this))
1722 return false;
1724 // If the map is not created, assume it is possible to enter it.
1725 // It will be created in the WorldPortAck.
1726 Map *map = sMapMgr.FindMap(mapid);
1727 if (!map || map->CanEnter(this))
1729 //lets reset near teleport flag if it wasn't reset during chained teleports
1730 SetSemaphoreTeleportNear(false);
1731 //setup delayed teleport flag
1732 SetDelayedTeleportFlag(IsCanDelayTeleport());
1733 //if teleport spell is casted in Unit::Update() func
1734 //then we need to delay it until update process will be finished
1735 if(IsHasDelayedTeleport())
1737 SetSemaphoreTeleportFar(true);
1738 //lets save teleport destination for player
1739 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1740 m_teleport_options = options;
1741 return true;
1744 SetSelection(0);
1746 CombatStop();
1748 ResetContestedPvP();
1750 // remove player from battleground on far teleport (when changing maps)
1751 if(BattleGround const* bg = GetBattleGround())
1753 // Note: at battleground join battleground id set before teleport
1754 // and we already will found "current" battleground
1755 // just need check that this is targeted map or leave
1756 if(bg->GetMapId() != mapid)
1757 LeaveBattleground(false); // don't teleport to entry point
1760 // remove pet on map change
1761 if (pet)
1762 UnsummonPetTemporaryIfAny();
1764 // remove all dyn objects
1765 RemoveAllDynObjects();
1767 // stop spellcasting
1768 // not attempt interrupt teleportation spell at caster teleport
1769 if(!(options & TELE_TO_SPELL))
1770 if(IsNonMeleeSpellCasted(true))
1771 InterruptNonMeleeSpells(true);
1773 //remove auras before removing from map...
1774 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1776 if(!GetSession()->PlayerLogout())
1778 // send transfer packets
1779 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1780 data << uint32(mapid);
1781 if (m_transport)
1783 data << uint32(m_transport->GetEntry());
1784 data << uint32(GetMapId());
1786 GetSession()->SendPacket(&data);
1788 data.Initialize(SMSG_NEW_WORLD, (20));
1789 if (m_transport)
1791 data << uint32(mapid);
1792 data << float(m_movementInfo.GetTransportPos()->x);
1793 data << float(m_movementInfo.GetTransportPos()->y);
1794 data << float(m_movementInfo.GetTransportPos()->z);
1795 data << float(m_movementInfo.GetTransportPos()->o);
1797 else
1799 data << uint32(mapid);
1800 data << float(x);
1801 data << float(y);
1802 data << float(z);
1803 data << float(orientation);
1805 GetSession()->SendPacket( &data );
1806 SendSavedInstances();
1809 // remove from old map now
1810 if(oldmap)
1811 oldmap->Remove(this, false);
1813 // new final coordinates
1814 float final_x = x;
1815 float final_y = y;
1816 float final_z = z;
1817 float final_o = orientation;
1819 if(m_transport)
1821 final_x += m_movementInfo.GetTransportPos()->x;
1822 final_y += m_movementInfo.GetTransportPos()->y;
1823 final_z += m_movementInfo.GetTransportPos()->z;
1824 final_o += m_movementInfo.GetTransportPos()->o;
1827 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1828 SetFallInformation(0, final_z);
1829 // if the player is saved before worldport ack (at logout for example)
1830 // this will be used instead of the current location in SaveToDB
1832 // move packet sent by client always after far teleport
1833 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1834 SetSemaphoreTeleportFar(true);
1836 else
1837 return false;
1839 return true;
1842 bool Player::TeleportToBGEntryPoint()
1844 ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
1845 ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
1846 return TeleportTo(m_bgData.joinPos);
1849 void Player::ProcessDelayedOperations()
1851 if(m_DelayedOperations == 0)
1852 return;
1854 if(m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
1856 ResurrectPlayer(0.0f, false);
1858 if(GetMaxHealth() > m_resurrectHealth)
1859 SetHealth( m_resurrectHealth );
1860 else
1861 SetHealth( GetMaxHealth() );
1863 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
1864 SetPower(POWER_MANA, m_resurrectMana );
1865 else
1866 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
1868 SetPower(POWER_RAGE, 0 );
1869 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
1871 SpawnCorpseBones();
1874 if(m_DelayedOperations & DELAYED_SAVE_PLAYER)
1876 SaveToDB();
1879 if(m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
1881 CastSpell(this, 26013, true); // Deserter
1884 if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
1886 if (m_bgData.mountSpell)
1888 CastSpell(this, m_bgData.mountSpell, true);
1889 m_bgData.mountSpell = 0;
1893 if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
1895 if (m_bgData.HasTaxiPath())
1897 m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
1898 m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
1899 m_bgData.ClearTaxiPath();
1901 ContinueTaxiFlight();
1905 //we have executed ALL delayed ops, so clear the flag
1906 m_DelayedOperations = 0;
1909 void Player::AddToWorld()
1911 ///- Do not add/remove the player from the object storage
1912 ///- It will crash when updating the ObjectAccessor
1913 ///- The player should only be added when logging in
1914 Unit::AddToWorld();
1916 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1918 if(m_items[i])
1919 m_items[i]->AddToWorld();
1923 void Player::RemoveFromWorld()
1925 // cleanup
1926 if(IsInWorld())
1928 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1929 UnsummonAllTotems();
1930 RemoveMiniPet();
1933 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1935 if(m_items[i])
1936 m_items[i]->RemoveFromWorld();
1939 ///- Do not add/remove the player from the object storage
1940 ///- It will crash when updating the ObjectAccessor
1941 ///- The player should only be removed when logging out
1942 Unit::RemoveFromWorld();
1945 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1947 float addRage;
1949 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1951 if(attacker)
1953 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1955 // talent who gave more rage on attack
1956 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1958 else
1960 addRage = damage/rageconversion*2.5;
1962 // Berserker Rage effect
1963 if(HasAura(18499,0))
1964 addRage *= 1.3f;
1967 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1969 ModifyPower(POWER_RAGE, uint32(addRage*10));
1972 void Player::RegenerateAll(uint32 diff)
1974 // Not in combat or they have regeneration
1975 if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1976 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1978 RegenerateHealth(diff);
1979 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1981 Regenerate(POWER_RAGE, diff);
1982 if(getClass() == CLASS_DEATH_KNIGHT)
1983 Regenerate(POWER_RUNIC_POWER, diff);
1987 Regenerate(POWER_ENERGY, diff);
1989 Regenerate(POWER_MANA, diff);
1991 if (getClass() == CLASS_DEATH_KNIGHT)
1992 Regenerate(POWER_RUNE, diff);
1994 m_regenTimer = REGEN_TIME_FULL;
1997 // diff contains the time in milliseconds since last regen.
1998 void Player::Regenerate(Powers power, uint32 diff)
2000 uint32 curValue = GetPower(power);
2001 uint32 maxValue = GetMaxPower(power);
2003 float addvalue = 0.0f;
2005 switch (power)
2007 case POWER_MANA:
2009 bool recentCast = IsUnderLastManaUseEffect();
2010 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
2011 if (recentCast)
2013 // Mangos Updates Mana in intervals of 2s, which is correct
2014 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
2016 else
2018 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
2020 } break;
2021 case POWER_RAGE: // Regenerate rage
2023 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
2024 addvalue = 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
2025 } break;
2026 case POWER_ENERGY: // Regenerate energy (rogue)
2027 addvalue = 20;
2028 break;
2029 case POWER_RUNIC_POWER:
2031 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
2032 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
2033 } break;
2034 case POWER_RUNE:
2036 if (getClass() != CLASS_DEATH_KNIGHT)
2037 break;
2039 for(uint32 i = 0; i < MAX_RUNES; ++i)
2041 if(uint16 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
2042 SetRuneCooldown(i, (cd < diff) ? 0 : cd - diff);
2044 } break;
2045 case POWER_FOCUS:
2046 case POWER_HAPPINESS:
2047 case POWER_HEALTH:
2048 break;
2051 // Mana regen calculated in Player::UpdateManaRegen()
2052 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
2053 if(power != POWER_MANA)
2055 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
2056 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
2057 if ((*i)->GetModifier()->m_miscvalue == power)
2058 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
2061 // addvalue computed on a 2sec basis. => update to diff time
2062 addvalue *= float(diff) / REGEN_TIME_FULL;
2064 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
2066 curValue += uint32(addvalue);
2067 if (curValue > maxValue)
2068 curValue = maxValue;
2070 else
2072 if(curValue <= uint32(addvalue))
2073 curValue = 0;
2074 else
2075 curValue -= uint32(addvalue);
2077 SetPower(power, curValue);
2080 void Player::RegenerateHealth(uint32 diff)
2082 uint32 curValue = GetHealth();
2083 uint32 maxValue = GetMaxHealth();
2085 if (curValue >= maxValue) return;
2087 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
2089 float addvalue = 0.0f;
2091 // polymorphed case
2092 if ( IsPolymorphed() )
2093 addvalue = (float)GetMaxHealth()/3;
2094 // normal regen case (maybe partly in combat case)
2095 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
2097 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
2098 if (!isInCombat())
2100 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
2101 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
2102 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
2104 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
2105 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
2107 if(!IsStandState())
2108 addvalue *= 1.5;
2111 // always regeneration bonus (including combat)
2112 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
2114 if(addvalue < 0)
2115 addvalue = 0;
2117 addvalue *= (float)diff / REGEN_TIME_FULL;
2119 ModifyHealth(int32(addvalue));
2122 Creature* Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
2124 // unit checks
2125 if (!guid || !IsInWorld() || isInFlight())
2126 return NULL;
2128 // exist (we need look pets also for some interaction (quest/etc)
2129 Creature *unit = GetMap()->GetCreatureOrPetOrVehicle(guid);
2130 if (!unit)
2131 return NULL;
2133 // appropriate npc type
2134 if (npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
2135 return NULL;
2137 if (npcflagmask == UNIT_NPC_FLAG_STABLEMASTER)
2139 if (getClass() != CLASS_HUNTER)
2140 return NULL;
2143 // if a dead unit should be able to talk - the creature must be alive and have special flags
2144 if (!unit->isAlive())
2145 return NULL;
2147 if (isAlive() && unit->isInvisibleForAlive())
2148 return NULL;
2150 // not allow interaction under control, but allow with own pets
2151 if (unit->GetCharmerGUID())
2152 return NULL;
2154 // not enemy
2155 if (unit->IsHostileTo(this))
2156 return NULL;
2158 // not unfriendly
2159 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
2160 if(factionTemplate->faction)
2161 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
2162 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
2163 return NULL;
2165 // not too far
2166 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
2167 return NULL;
2169 return unit;
2172 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, uint32 gameobject_type) const
2174 if (GameObject *go = GetMap()->GetGameObject(guid))
2176 if (uint32(go->GetGoType()) == gameobject_type || gameobject_type == MAX_GAMEOBJECT_TYPE)
2178 float maxdist;
2179 switch(go->GetGoType())
2181 // TODO: find out how the client calculates the maximal usage distance to spellless working
2182 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2183 case GAMEOBJECT_TYPE_GUILD_BANK:
2184 case GAMEOBJECT_TYPE_MAILBOX:
2185 maxdist = 10.0f;
2186 break;
2187 case GAMEOBJECT_TYPE_FISHINGHOLE:
2188 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2189 break;
2190 default:
2191 maxdist = INTERACTION_DISTANCE;
2192 break;
2195 if (go->IsWithinDistInMap(this, maxdist) && go->isSpawned())
2196 return go;
2198 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,
2199 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2202 return NULL;
2205 bool Player::IsUnderWater() const
2207 return IsInWater() &&
2208 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2211 void Player::SetInWater(bool apply)
2213 if(m_isInWater==apply)
2214 return;
2216 //define player in water by opcodes
2217 //move player's guid into HateOfflineList of those mobs
2218 //which can't swim and move guid back into ThreatList when
2219 //on surface.
2220 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2221 m_isInWater = apply;
2223 // remove auras that need water/land
2224 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2226 getHostileRefManager().updateThreatTables();
2229 struct SetGameMasterOnHelper
2231 explicit SetGameMasterOnHelper() {}
2232 void operator()(Unit* unit) const
2234 unit->setFaction(35);
2235 unit->getHostileRefManager().setOnlineOfflineState(false);
2239 struct SetGameMasterOffHelper
2241 explicit SetGameMasterOffHelper(uint32 _faction) : faction(_faction) {}
2242 void operator()(Unit* unit) const
2244 unit->setFaction(faction);
2245 unit->getHostileRefManager().setOnlineOfflineState(true);
2247 uint32 faction;
2250 void Player::SetGameMaster(bool on)
2252 if(on)
2254 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2255 setFaction(35);
2256 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2258 CallForAllControlledUnits(SetGameMasterOnHelper(),true,true,true,false);
2260 SetFFAPvP(false);
2261 ResetContestedPvP();
2263 getHostileRefManager().setOnlineOfflineState(false);
2264 CombatStopWithPets();
2266 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2268 else
2270 // restore phase
2271 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2272 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2274 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2275 setFactionForRace(getRace());
2276 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2278 CallForAllControlledUnits(SetGameMasterOffHelper(getFaction()),true,true,true,false);
2280 // restore FFA PvP Server state
2281 if(sWorld.IsFFAPvPRealm())
2282 SetFFAPvP(true);
2284 // restore FFA PvP area state, remove not allowed for GM mounts
2285 UpdateArea(m_areaUpdateId);
2287 getHostileRefManager().setOnlineOfflineState(true);
2290 UpdateVisibilityForPlayer();
2293 void Player::SetGMVisible(bool on)
2295 if(on)
2297 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2299 // Reapply stealth/invisibility if active or show if not any
2300 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2301 SetVisibility(VISIBILITY_GROUP_STEALTH);
2302 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2303 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2304 else
2305 SetVisibility(VISIBILITY_ON);
2307 else
2309 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2311 SetAcceptWhispers(false);
2312 SetGameMaster(true);
2314 SetVisibility(VISIBILITY_OFF);
2318 bool Player::IsGroupVisibleFor(Player* p) const
2320 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2322 default: return IsInSameGroupWith(p);
2323 case 1: return IsInSameRaidWith(p);
2324 case 2: return GetTeam()==p->GetTeam();
2328 bool Player::IsInSameGroupWith(Player const* p) const
2330 return (p==this || (GetGroup() != NULL &&
2331 GetGroup()->SameSubGroup((Player*)this, (Player*)p)));
2334 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2335 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2336 void Player::UninviteFromGroup()
2338 Group* group = GetGroupInvite();
2339 if(!group)
2340 return;
2342 group->RemoveInvite(this);
2344 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2346 if(group->IsCreated())
2348 group->Disband(true);
2349 sObjectMgr.RemoveGroup(group);
2351 else
2352 group->RemoveAllInvites();
2354 delete group;
2358 void Player::RemoveFromGroup(Group* group, uint64 guid)
2360 if(group)
2362 if (group->RemoveMember(guid, 0) <= 1)
2364 // group->Disband(); already disbanded in RemoveMember
2365 sObjectMgr.RemoveGroup(group);
2366 delete group;
2367 // removemember sets the player's group pointer to NULL
2372 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2374 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2375 data << uint64(victim ? victim->GetGUID() : 0); // guid
2376 data << uint32(GivenXP+RestXP); // given experience
2377 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2378 if(victim)
2380 data << uint32(GivenXP); // experience without rested bonus
2381 data << float(1); // 1 - none 0 - 100% group bonus output
2383 data << uint8(0); // new 2.4.0
2384 GetSession()->SendPacket(&data);
2387 void Player::GiveXP(uint32 xp, Unit* victim)
2389 if ( xp < 1 )
2390 return;
2392 if(!isAlive())
2393 return;
2395 uint32 level = getLevel();
2397 // XP to money conversion processed in Player::RewardQuest
2398 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2399 return;
2401 if(victim)
2403 // handle SPELL_AURA_MOD_KILL_XP_PCT auras
2404 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT);
2405 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2406 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2408 else
2410 // handle SPELL_AURA_MOD_QUEST_XP_PCT auras
2411 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT);
2412 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2413 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2416 // XP resting bonus for kill
2417 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2419 SendLogXPGain(xp,victim,rested_bonus_xp);
2421 uint32 curXP = GetUInt32Value(PLAYER_XP);
2422 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2423 uint32 newXP = curXP + xp + rested_bonus_xp;
2425 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2427 newXP -= nextLvlXP;
2429 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2430 GiveLevel(level + 1);
2432 level = getLevel();
2433 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2436 SetUInt32Value(PLAYER_XP, newXP);
2439 // Update player to next level
2440 // Current player experience not update (must be update by caller)
2441 void Player::GiveLevel(uint32 level)
2443 if ( level == getLevel() )
2444 return;
2446 PlayerLevelInfo info;
2447 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2449 PlayerClassLevelInfo classInfo;
2450 sObjectMgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2452 // send levelup info to client
2453 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2454 data << uint32(level);
2455 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2456 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2457 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2458 data << uint32(0);
2459 data << uint32(0);
2460 data << uint32(0);
2461 data << uint32(0);
2462 data << uint32(0);
2463 data << uint32(0);
2464 // end for
2465 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2466 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2468 GetSession()->SendPacket(&data);
2470 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(level));
2472 //update level, max level of skills
2473 m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
2475 _ApplyAllLevelScaleItemMods(false);
2477 SetLevel(level);
2479 UpdateSkillsForLevel ();
2481 // save base values (bonuses already included in stored stats
2482 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2483 SetCreateStat(Stats(i), info.stats[i]);
2485 SetCreateHealth(classInfo.basehealth);
2486 SetCreateMana(classInfo.basemana);
2488 InitTalentForLevel();
2489 InitTaxiNodesForLevel();
2490 InitGlyphsForLevel();
2492 UpdateAllStats();
2494 // set current level health and mana/energy to maximum after applying all mods.
2495 SetHealth(GetMaxHealth());
2496 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2497 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2498 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2499 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2500 SetPower(POWER_FOCUS, 0);
2501 SetPower(POWER_HAPPINESS, 0);
2503 _ApplyAllLevelScaleItemMods(true);
2505 // update level to hunter/summon pet
2506 if (Pet* pet = GetPet())
2507 pet->SynchronizeLevelWithOwner();
2509 if (MailLevelReward const* mailReward = sObjectMgr.GetMailLevelReward(level,getRaceMask()))
2510 MailDraft(mailReward->mailTemplateId).SendMailTo(this,MailSender(MAIL_CREATURE,mailReward->senderEntry));
2512 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2515 void Player::InitTalentForLevel()
2517 uint32 level = getLevel();
2518 // talents base at level diff ( talents = level - 9 but some can be used already)
2519 if(level < 10)
2521 // Remove all talent points
2522 if(m_usedTalentCount > 0) // Free any used talents
2524 resetTalents(true);
2525 SetFreeTalentPoints(0);
2528 else
2530 uint32 talentPointsForLevel = CalculateTalentsPoints();
2532 // if used more that have then reset
2533 if(m_usedTalentCount > talentPointsForLevel)
2535 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2536 resetTalents(true);
2537 else
2538 SetFreeTalentPoints(0);
2540 // else update amount of free points
2541 else
2542 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2545 if(!GetSession()->PlayerLoading())
2546 SendTalentsInfoData(false); // update at client
2549 void Player::InitStatsForLevel(bool reapplyMods)
2551 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2552 _RemoveAllStatBonuses();
2554 PlayerClassLevelInfo classInfo;
2555 sObjectMgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2557 PlayerLevelInfo info;
2558 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2560 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2561 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(getLevel()));
2563 // reset before any aura state sources (health set/aura apply)
2564 SetUInt32Value(UNIT_FIELD_AURASTATE, 0);
2566 UpdateSkillsForLevel ();
2568 // set default cast time multiplier
2569 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2571 // reset size before reapply auras
2572 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2574 // save base values (bonuses already included in stored stats
2575 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2576 SetCreateStat(Stats(i), info.stats[i]);
2578 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2579 SetStat(Stats(i), info.stats[i]);
2581 SetCreateHealth(classInfo.basehealth);
2583 //set create powers
2584 SetCreateMana(classInfo.basemana);
2586 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2588 InitStatBuffMods();
2590 //reset rating fields values
2591 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2592 SetUInt32Value(index, 0);
2594 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2595 for (int i = 0; i < 7; ++i)
2597 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2598 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2599 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2602 //reset attack power, damage and attack speed fields
2603 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2604 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2605 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2607 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2608 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2609 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2610 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2611 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2612 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2614 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2615 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2616 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2617 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2618 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2619 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2621 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2622 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2623 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2624 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2626 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2627 for (uint8 i = 0; i < 7; ++i)
2628 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2630 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2631 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2632 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2634 // Dodge percentage
2635 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2637 // set armor (resistance 0) to original value (create_agility*2)
2638 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2639 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2640 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2641 // set other resistance to original value (0)
2642 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2644 SetResistance(SpellSchools(i), 0);
2645 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2646 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2649 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2650 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2651 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2653 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2654 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2656 // Reset no reagent cost field
2657 for(int i = 0; i < 3; ++i)
2658 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2659 // Init data for form but skip reapply item mods for form
2660 InitDataForForm(reapplyMods);
2662 // save new stats
2663 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2664 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2666 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2668 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2669 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2671 // cleanup unit flags (will be re-applied if need at aura load).
2672 RemoveFlag( UNIT_FIELD_FLAGS,
2673 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2674 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2675 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2676 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2677 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2678 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2680 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2682 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2683 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2685 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2686 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2688 // restore if need some important flags
2689 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2691 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2692 _ApplyAllStatBonuses();
2694 // set current level health and mana/energy to maximum after applying all mods.
2695 SetHealth(GetMaxHealth());
2696 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2697 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2698 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2699 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2700 SetPower(POWER_FOCUS, 0);
2701 SetPower(POWER_HAPPINESS, 0);
2702 SetPower(POWER_RUNIC_POWER, 0);
2704 // update level to hunter/summon pet
2705 if (Pet* pet = GetPet())
2706 pet->SynchronizeLevelWithOwner();
2709 void Player::SendInitialSpells()
2711 time_t curTime = time(NULL);
2712 time_t infTime = curTime + infinityCooldownDelayCheck;
2714 uint16 spellCount = 0;
2716 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2717 data << uint8(0);
2719 size_t countPos = data.wpos();
2720 data << uint16(spellCount); // spell count placeholder
2722 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2724 if(itr->second->state == PLAYERSPELL_REMOVED)
2725 continue;
2727 if(!itr->second->active || itr->second->disabled)
2728 continue;
2730 data << uint32(itr->first);
2731 data << uint16(0); // it's not slot id
2733 spellCount +=1;
2736 data.put<uint16>(countPos,spellCount); // write real count value
2738 uint16 spellCooldowns = m_spellCooldowns.size();
2739 data << uint16(spellCooldowns);
2740 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2742 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2743 if(!sEntry)
2744 continue;
2746 data << uint32(itr->first);
2748 data << uint16(itr->second.itemid); // cast item id
2749 data << uint16(sEntry->Category); // spell category
2751 // send infinity cooldown in special format
2752 if(itr->second.end >= infTime)
2754 data << uint32(1); // cooldown
2755 data << uint32(0x80000000); // category cooldown
2756 continue;
2759 time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILISECONDS : 0;
2761 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2763 data << uint32(0); // cooldown
2764 data << uint32(cooldown); // category cooldown
2766 else
2768 data << uint32(cooldown); // cooldown
2769 data << uint32(0); // category cooldown
2773 GetSession()->SendPacket(&data);
2775 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2778 void Player::RemoveMail(uint32 id)
2780 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2782 if ((*itr)->messageID == id)
2784 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2785 m_mail.erase(itr);
2786 return;
2791 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2793 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2794 data << (uint32) mailId;
2795 data << (uint32) mailAction;
2796 data << (uint32) mailError;
2797 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2798 data << (uint32) equipError;
2799 else if( mailAction == MAIL_ITEM_TAKEN )
2801 data << (uint32) item_guid; // item guid low?
2802 data << (uint32) item_count; // item count?
2804 GetSession()->SendPacket(&data);
2807 void Player::SendNewMail()
2809 // deliver undelivered mail
2810 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2811 data << (uint32) 0;
2812 GetSession()->SendPacket(&data);
2815 void Player::UpdateNextMailTimeAndUnreads()
2817 // calculate next delivery time (min. from non-delivered mails
2818 // and recalculate unReadMail
2819 time_t cTime = time(NULL);
2820 m_nextMailDelivereTime = 0;
2821 unReadMails = 0;
2822 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2824 if((*itr)->deliver_time > cTime)
2826 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2827 m_nextMailDelivereTime = (*itr)->deliver_time;
2829 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2830 ++unReadMails;
2834 void Player::AddNewMailDeliverTime(time_t deliver_time)
2836 if(deliver_time <= time(NULL)) // ready now
2838 ++unReadMails;
2839 SendNewMail();
2841 else // not ready and no have ready mails
2843 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2844 m_nextMailDelivereTime = deliver_time;
2848 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2850 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2851 if (!spellInfo)
2853 // do character spell book cleanup (all characters)
2854 if(!IsInWorld() && !learning) // spell load case
2856 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2857 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2859 else
2860 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2862 return false;
2865 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2867 // do character spell book cleanup (all characters)
2868 if(!IsInWorld() && !learning) // spell load case
2870 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2871 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2873 else
2874 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2876 return false;
2879 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2881 bool dependent_set = false;
2882 bool disabled_case = false;
2883 bool superceded_old = false;
2885 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2886 if (itr != m_spells.end())
2888 uint32 next_active_spell_id = 0;
2889 // fix activate state for non-stackable low rank (and find next spell for !active case)
2890 if(!SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
2892 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
2893 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2895 if(HasSpell(next_itr->second))
2897 // high rank already known so this must !active
2898 active = false;
2899 next_active_spell_id = next_itr->second;
2900 break;
2905 // not do anything if already known in expected state
2906 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2907 itr->second->dependent == dependent && itr->second->disabled == disabled)
2909 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2910 itr->second->state = PLAYERSPELL_UNCHANGED;
2912 return false;
2915 // dependent spell known as not dependent, overwrite state
2916 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2918 itr->second->dependent = dependent;
2919 if (itr->second->state != PLAYERSPELL_NEW)
2920 itr->second->state = PLAYERSPELL_CHANGED;
2921 dependent_set = true;
2924 // update active state for known spell
2925 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2927 itr->second->active = active;
2929 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2930 itr->second->state = PLAYERSPELL_UNCHANGED;
2931 else if(itr->second->state != PLAYERSPELL_NEW)
2932 itr->second->state = PLAYERSPELL_CHANGED;
2934 if(active)
2936 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2937 CastSpell (this,spell_id,true);
2939 else if(IsInWorld())
2941 if(next_active_spell_id)
2943 // update spell ranks in spellbook and action bar
2944 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2945 data << uint32(spell_id);
2946 data << uint32(next_active_spell_id);
2947 GetSession()->SendPacket( &data );
2949 else
2951 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2952 data << uint32(spell_id);
2953 GetSession()->SendPacket(&data);
2957 return active; // learn (show in spell book if active now)
2960 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2962 if(itr->second->state != PLAYERSPELL_NEW)
2963 itr->second->state = PLAYERSPELL_CHANGED;
2964 itr->second->disabled = disabled;
2966 if(disabled)
2967 return false;
2969 disabled_case = true;
2971 else switch(itr->second->state)
2973 case PLAYERSPELL_UNCHANGED: // known saved spell
2974 return false;
2975 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2977 delete itr->second;
2978 m_spells.erase(itr);
2979 state = PLAYERSPELL_CHANGED;
2980 break; // need re-add
2982 default: // known not saved yet spell (new or modified)
2984 // can be in case spell loading but learned at some previous spell loading
2985 if(!IsInWorld() && !learning && !dependent_set)
2986 itr->second->state = PLAYERSPELL_UNCHANGED;
2988 return false;
2993 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2995 // talent: unlearn all other talent ranks (high and low)
2996 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2998 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
3000 for(int i=0; i < MAX_TALENT_RANK; ++i)
3002 // skip learning spell and no rank spell case
3003 uint32 rankSpellId = talentInfo->RankID[i];
3004 if(!rankSpellId || rankSpellId==spell_id)
3005 continue;
3007 removeSpell(rankSpellId,false,false);
3011 // non talent spell: learn low ranks (recursive call)
3012 else if(uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id))
3014 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
3015 addSpell(prev_spell,active,true,true,disabled);
3016 else // at normal learning
3017 learnSpell(prev_spell,true);
3020 PlayerSpell *newspell = new PlayerSpell;
3021 newspell->state = state;
3022 newspell->active = active;
3023 newspell->dependent = dependent;
3024 newspell->disabled = disabled;
3026 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
3027 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
3029 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
3031 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
3032 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
3033 if(!i_spellInfo) continue;
3035 if( sSpellMgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
3037 if(itr2->second->active)
3039 if(sSpellMgr.IsHighRankOfSpell(spell_id,itr2->first))
3041 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3043 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3044 data << uint32(itr2->first);
3045 data << uint32(spell_id);
3046 GetSession()->SendPacket( &data );
3049 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
3050 itr2->second->active = false;
3051 if(itr2->second->state != PLAYERSPELL_NEW)
3052 itr2->second->state = PLAYERSPELL_CHANGED;
3053 superceded_old = true; // new spell replace old in action bars and spell book.
3055 else if(sSpellMgr.IsHighRankOfSpell(itr2->first,spell_id))
3057 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3059 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3060 data << uint32(spell_id);
3061 data << uint32(itr2->first);
3062 GetSession()->SendPacket( &data );
3065 // mark new spell as disable (not learned yet for client and will not learned)
3066 newspell->active = false;
3067 if(newspell->state != PLAYERSPELL_NEW)
3068 newspell->state = PLAYERSPELL_CHANGED;
3075 m_spells[spell_id] = newspell;
3077 // return false if spell disabled
3078 if (newspell->disabled)
3079 return false;
3082 uint32 talentCost = GetTalentSpellCost(spell_id);
3084 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3085 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3086 if (talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
3088 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3089 CastSpell(this, spell_id, true);
3091 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3092 else if (IsPassiveSpell(spell_id))
3094 if (IsNeedCastPassiveSpellAtLearn(spellInfo))
3095 CastSpell(this, spell_id, true);
3097 else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
3099 CastSpell(this, spell_id, true);
3100 return false;
3103 // update used talent points count
3104 m_usedTalentCount += talentCost;
3106 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3107 if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
3109 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3110 SetFreePrimaryProfessions(freeProfs-1);
3113 // add dependent skills
3114 uint16 maxskill = GetMaxSkillValueForLevel();
3116 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3118 SkillLineAbilityMapBounds skill_bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3120 if (spellLearnSkill)
3122 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
3123 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
3125 if (skill_value < spellLearnSkill->value)
3126 skill_value = spellLearnSkill->value;
3128 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
3130 if (skill_max_value < new_skill_max_value)
3131 skill_max_value = new_skill_max_value;
3133 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
3135 else
3137 // not ranked skills
3138 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3140 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3141 if (!pSkill)
3142 continue;
3144 if (HasSkill(pSkill->id))
3145 continue;
3147 if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3148 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3149 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3151 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
3153 case SKILL_RANGE_LANGUAGE:
3154 SetSkill(pSkill->id, 300, 300 );
3155 break;
3156 case SKILL_RANGE_LEVEL:
3157 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
3158 break;
3159 case SKILL_RANGE_MONO:
3160 SetSkill(pSkill->id, 1, 1 );
3161 break;
3162 default:
3163 break;
3169 // learn dependent spells
3170 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3172 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3174 if (!itr2->second.autoLearned)
3176 if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
3177 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
3178 else // at normal learning
3179 learnSpell(itr2->second.spell,true);
3183 if (!GetSession()->PlayerLoading())
3185 // not ranked skills
3186 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3188 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3189 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3192 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3195 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3196 return active && !disabled && !superceded_old;
3199 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3201 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3202 // talent dependent passives activated at form apply have proper stance data
3203 bool need_cast = (!spellInfo->Stances || (m_form != 0 && (spellInfo->Stances & (1<<(m_form-1)))));
3205 //Check CasterAuraStates
3206 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3209 void Player::learnSpell(uint32 spell_id, bool dependent)
3211 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3213 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3214 bool active = disabled ? itr->second->active : true;
3216 bool learning = addSpell(spell_id,active,true,dependent,false);
3218 // learn all disabled higher ranks (recursive)
3219 if(disabled)
3221 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3222 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3224 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3225 if (iter != m_spells.end() && iter->second->disabled)
3226 learnSpell(i->second,false);
3230 // prevent duplicated entires in spell book, also not send if not in world (loading)
3231 if(!learning || !IsInWorld ())
3232 return;
3234 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3235 data << uint32(spell_id);
3236 GetSession()->SendPacket(&data);
3239 void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bool sendUpdate)
3241 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3242 if (itr == m_spells.end())
3243 return;
3245 if (itr->second->state == PLAYERSPELL_REMOVED || (disabled && itr->second->disabled))
3246 return;
3248 // unlearn non talent higher ranks (recursive)
3249 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3250 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3251 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3252 removeSpell(itr2->second,disabled,false);
3254 // re-search, it can be corrupted in prev loop
3255 itr = m_spells.find(spell_id);
3256 if (itr == m_spells.end())
3257 return; // already unleared
3259 bool cur_active = itr->second->active;
3260 bool cur_dependent = itr->second->dependent;
3262 if (disabled)
3264 itr->second->disabled = disabled;
3265 if(itr->second->state != PLAYERSPELL_NEW)
3266 itr->second->state = PLAYERSPELL_CHANGED;
3268 else
3270 if(itr->second->state == PLAYERSPELL_NEW)
3272 delete itr->second;
3273 m_spells.erase(itr);
3275 else
3276 itr->second->state = PLAYERSPELL_REMOVED;
3279 RemoveAurasDueToSpell(spell_id);
3281 // remove pet auras
3282 for(int i = 0; i < 3; ++i)
3283 if(PetAura const* petSpell = sSpellMgr.GetPetAura(spell_id, i))
3284 RemovePetAura(petSpell);
3286 // free talent points
3287 uint32 talentCosts = GetTalentSpellCost(spell_id);
3288 if(talentCosts > 0)
3290 if(talentCosts < m_usedTalentCount)
3291 m_usedTalentCount -= talentCosts;
3292 else
3293 m_usedTalentCount = 0;
3296 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3297 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3299 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3300 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3301 SetFreePrimaryProfessions(freeProfs);
3304 // remove dependent skill
3305 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3306 if(spellLearnSkill)
3308 uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id);
3309 if(!prev_spell) // first rank, remove skill
3310 SetSkill(spellLearnSkill->skill,0,0);
3311 else
3313 // search prev. skill setting by spell ranks chain
3314 SpellLearnSkillNode const* prevSkill = sSpellMgr.GetSpellLearnSkill(prev_spell);
3315 while(!prevSkill && prev_spell)
3317 prev_spell = sSpellMgr.GetPrevSpellInChain(prev_spell);
3318 prevSkill = sSpellMgr.GetSpellLearnSkill(sSpellMgr.GetFirstSpellInChain(prev_spell));
3321 if (!prevSkill) // not found prev skill setting, remove skill
3322 SetSkill(spellLearnSkill->skill,0,0);
3323 else // set to prev. skill setting values
3325 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3326 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3328 if (skill_value > prevSkill->value)
3329 skill_value = prevSkill->value;
3331 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3333 if (skill_max_value > new_skill_max_value)
3334 skill_max_value = new_skill_max_value;
3336 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3341 else
3343 // not ranked skills
3344 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3346 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
3348 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3349 if (!pSkill)
3350 continue;
3352 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
3353 pSkill->categoryId != SKILL_CATEGORY_CLASS ||// not unlearn class skills (spellbook/talent pages)
3354 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3355 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3357 // not reset skills for professions and racial abilities
3358 if ((pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3359 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0))
3360 continue;
3362 SetSkill(pSkill->id, 0, 0 );
3367 // remove dependent spells
3368 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3370 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3371 removeSpell(itr2->second.spell, disabled);
3373 // activate lesser rank in spellbook/action bar, and cast it if need
3374 bool prev_activate = false;
3376 if (uint32 prev_id = sSpellMgr.GetPrevSpellInChain (spell_id))
3378 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3380 // if talent then lesser rank also talent and need learn
3381 if (talentCosts)
3383 if(learn_low_rank)
3384 learnSpell (prev_id,false);
3386 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3387 else if (cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
3389 // need manually update dependence state (learn spell ignore like attempts)
3390 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3391 if (prev_itr != m_spells.end())
3393 if (prev_itr->second->dependent != cur_dependent)
3395 prev_itr->second->dependent = cur_dependent;
3396 if (prev_itr->second->state != PLAYERSPELL_NEW)
3397 prev_itr->second->state = PLAYERSPELL_CHANGED;
3400 // now re-learn if need re-activate
3401 if (cur_active && !prev_itr->second->active && learn_low_rank)
3403 if (addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3405 // downgrade spell ranks in spellbook and action bar
3406 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3407 data << uint32(spell_id);
3408 data << uint32(prev_id);
3409 GetSession()->SendPacket( &data );
3410 prev_activate = true;
3417 // remove from spell book if not replaced by lesser rank
3418 if (!prev_activate && sendUpdate)
3420 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3421 data << uint32(spell_id);
3422 GetSession()->SendPacket(&data);
3426 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3428 m_spellCooldowns.erase(spell_id);
3430 if(update)
3431 SendClearCooldown(spell_id, this);
3434 void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
3436 SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
3437 if (ct == sSpellCategoryStore.end())
3438 return;
3440 const SpellCategorySet& ct_set = ct->second;
3441 for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
3443 if (ct_set.find(i->first) != ct_set.end())
3444 RemoveSpellCooldown((i++)->first, update);
3445 else
3446 ++i;
3450 void Player::RemoveArenaSpellCooldowns()
3452 // remove cooldowns on spells that has < 15 min CD
3453 SpellCooldowns::iterator itr, next;
3454 // iterate spell cooldowns
3455 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3457 next = itr;
3458 ++next;
3459 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3460 // check if spellentry is present and if the cooldown is less than 15 mins
3461 if( entry &&
3462 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3463 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3465 // remove & notify
3466 RemoveSpellCooldown(itr->first, true);
3471 void Player::RemoveAllSpellCooldown()
3473 if(!m_spellCooldowns.empty())
3475 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3476 SendClearCooldown(itr->first, this);
3478 m_spellCooldowns.clear();
3482 void Player::_LoadSpellCooldowns(QueryResult *result)
3484 // some cooldowns can be already set at aura loading...
3486 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3488 if(result)
3490 time_t curTime = time(NULL);
3494 Field *fields = result->Fetch();
3496 uint32 spell_id = fields[0].GetUInt32();
3497 uint32 item_id = fields[1].GetUInt32();
3498 time_t db_time = (time_t)fields[2].GetUInt64();
3500 if(!sSpellStore.LookupEntry(spell_id))
3502 sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3503 continue;
3506 // skip outdated cooldown
3507 if(db_time <= curTime)
3508 continue;
3510 AddSpellCooldown(spell_id, item_id, db_time);
3512 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3514 while( result->NextRow() );
3516 delete result;
3520 void Player::_SaveSpellCooldowns()
3522 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3524 time_t curTime = time(NULL);
3525 time_t infTime = curTime + infinityCooldownDelayCheck;
3527 /* copied following sql-code partly from achievementmgr */
3528 bool first_round = true;
3529 std::ostringstream ss;
3531 // remove outdated and save active
3532 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3534 if(itr->second.end <= curTime)
3535 m_spellCooldowns.erase(itr++);
3536 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3538 if (first_round)
3540 ss << "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ";
3541 first_round = false;
3543 // next new/changed record prefix
3544 else
3545 ss << ", ";
3546 ss << "(" << GetGUIDLow() << "," << itr->first << "," << itr->second.itemid << "," << uint64(itr->second.end) << ")";
3547 ++itr;
3549 else
3550 ++itr;
3553 // if something changed execute
3554 if (!first_round)
3555 CharacterDatabase.Execute( ss.str().c_str() );
3558 uint32 Player::resetTalentsCost() const
3560 // The first time reset costs 1 gold
3561 if(m_resetTalentsCost < 1*GOLD)
3562 return 1*GOLD;
3563 // then 5 gold
3564 else if(m_resetTalentsCost < 5*GOLD)
3565 return 5*GOLD;
3566 // After that it increases in increments of 5 gold
3567 else if(m_resetTalentsCost < 10*GOLD)
3568 return 10*GOLD;
3569 else
3571 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3572 if(months > 0)
3574 // This cost will be reduced by a rate of 5 gold per month
3575 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3576 // to a minimum of 10 gold.
3577 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3579 else
3581 // After that it increases in increments of 5 gold
3582 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3583 // until it hits a cap of 50 gold.
3584 if(new_cost > 50*GOLD)
3585 new_cost = 50*GOLD;
3586 return new_cost;
3591 bool Player::resetTalents(bool no_cost)
3593 // not need after this call
3594 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3595 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
3597 uint32 talentPointsForLevel = CalculateTalentsPoints();
3599 if (m_usedTalentCount == 0)
3601 SetFreeTalentPoints(talentPointsForLevel);
3602 return false;
3605 uint32 cost = 0;
3607 if(!no_cost)
3609 cost = resetTalentsCost();
3611 if (GetMoney() < cost)
3613 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3614 return false;
3618 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3620 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3622 if (!talentInfo) continue;
3624 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3626 if(!talentTabInfo)
3627 continue;
3629 // unlearn only talents for character class
3630 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3631 // to prevent unexpected lost normal learned spell skip another class talents
3632 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3633 continue;
3635 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3637 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3639 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3641 ++itr;
3642 continue;
3645 // remove learned spells (all ranks)
3646 uint32 itrFirstId = sSpellMgr.GetFirstSpellInChain(itr->first);
3648 // unlearn if first rank is talent or learned by talent
3649 if (itrFirstId == talentInfo->RankID[j])
3651 removeSpell(itr->first,!IsPassiveSpell(itr->first),false);
3652 itr = GetSpellMap().begin();
3653 continue;
3655 else if (sSpellMgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3657 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3658 itr = GetSpellMap().begin();
3659 continue;
3661 else
3662 ++itr;
3667 SetFreeTalentPoints(talentPointsForLevel);
3669 if(!no_cost)
3671 ModifyMoney(-(int32)cost);
3672 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3673 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3675 m_resetTalentsCost = cost;
3676 m_resetTalentsTime = time(NULL);
3679 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3680 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3681 /* when prev line will dropped use next line
3682 if(Pet* pet = GetPet())
3684 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3685 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3690 if(m_canTitanGrip)
3692 m_canTitanGrip = false;
3693 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3694 AutoUnequipOffhandIfNeed();
3697 return true;
3700 Mail* Player::GetMail(uint32 id)
3702 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3704 if ((*itr)->messageID == id)
3706 return (*itr);
3709 return NULL;
3712 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3714 if(target == this)
3716 Object::_SetCreateBits(updateMask, target);
3718 else
3720 for(uint16 index = 0; index < m_valuesCount; index++)
3722 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3723 updateMask->SetBit(index);
3728 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3730 if(target == this)
3732 Object::_SetUpdateBits(updateMask, target);
3734 else
3736 Object::_SetUpdateBits(updateMask, target);
3737 *updateMask &= updateVisualBits;
3741 void Player::InitVisibleBits()
3743 updateVisualBits.SetCount(PLAYER_END);
3745 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3746 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3747 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3748 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3749 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3750 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3751 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3752 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3753 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3754 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3755 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3756 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3757 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3758 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3759 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3760 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3761 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3762 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3763 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3764 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3765 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3766 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3767 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3768 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3769 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3770 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3771 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3772 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3773 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3774 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3775 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3776 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3777 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3778 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3779 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3780 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3781 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3782 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3783 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3784 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3785 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3786 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3787 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3788 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3789 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3790 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3791 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3792 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3793 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3794 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3795 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3796 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3797 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3798 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3799 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3801 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3802 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3803 updateVisualBits.SetBit(PLAYER_FLAGS);
3804 updateVisualBits.SetBit(PLAYER_GUILDID);
3805 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3806 updateVisualBits.SetBit(PLAYER_BYTES);
3807 updateVisualBits.SetBit(PLAYER_BYTES_2);
3808 updateVisualBits.SetBit(PLAYER_BYTES_3);
3809 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3810 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3812 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3813 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += MAX_QUEST_OFFSET)
3814 updateVisualBits.SetBit(i);
3816 // Players visible items are not inventory stuff
3817 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3819 uint32 offset = i * 2;
3821 // item entry
3822 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3823 // enchant
3824 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3827 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3830 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3832 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3834 if(m_items[i] == NULL)
3835 continue;
3837 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3840 if(target == this)
3842 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3844 if(m_items[i] == NULL)
3845 continue;
3847 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3849 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3851 if(m_items[i] == NULL)
3852 continue;
3854 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3858 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3861 void Player::DestroyForPlayer( Player *target, bool anim ) const
3863 Unit::DestroyForPlayer( target, anim );
3865 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3867 if(m_items[i] == NULL)
3868 continue;
3870 m_items[i]->DestroyForPlayer( target );
3873 if(target == this)
3875 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3877 if(m_items[i] == NULL)
3878 continue;
3880 m_items[i]->DestroyForPlayer( target );
3882 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3884 if(m_items[i] == NULL)
3885 continue;
3887 m_items[i]->DestroyForPlayer( target );
3892 bool Player::HasSpell(uint32 spell) const
3894 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3895 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3896 !itr->second->disabled);
3899 bool Player::HasActiveSpell(uint32 spell) const
3901 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3902 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3903 itr->second->active && !itr->second->disabled);
3906 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3908 if (!trainer_spell)
3909 return TRAINER_SPELL_RED;
3911 if (!trainer_spell->learnedSpell)
3912 return TRAINER_SPELL_RED;
3914 // known spell
3915 if(HasSpell(trainer_spell->learnedSpell))
3916 return TRAINER_SPELL_GRAY;
3918 // check race/class requirement
3919 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3920 return TRAINER_SPELL_RED;
3922 // check level requirement
3923 if(getLevel() < trainer_spell->reqLevel)
3924 return TRAINER_SPELL_RED;
3926 if(SpellChainNode const* spell_chain = sSpellMgr.GetSpellChainNode(trainer_spell->learnedSpell))
3928 // check prev.rank requirement
3929 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3930 return TRAINER_SPELL_RED;
3932 // check additional spell requirement
3933 if(spell_chain->req && !HasSpell(spell_chain->req))
3934 return TRAINER_SPELL_RED;
3937 // check skill requirement
3938 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3939 return TRAINER_SPELL_RED;
3941 // exist, already checked at loading
3942 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3944 // secondary prof. or not prof. spell
3945 uint32 skill = spell->EffectMiscValue[1];
3947 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3948 return TRAINER_SPELL_GREEN;
3950 // check primary prof. limit
3951 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
3952 return TRAINER_SPELL_GREEN_DISABLED;
3954 return TRAINER_SPELL_GREEN;
3957 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3959 uint32 guid = GUID_LOPART(playerguid);
3961 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3962 // bones will be deleted by corpse/bones deleting thread shortly
3963 sObjectAccessor.ConvertCorpseForPlayer(playerguid);
3965 // remove from guild
3966 uint32 guildId = GetGuildIdFromDB(playerguid);
3967 if(guildId != 0)
3969 Guild* guild = sObjectMgr.GetGuildById(guildId);
3970 if(guild)
3971 guild->DelMember(guid);
3974 // remove from arena teams
3975 LeaveAllArenaTeams(playerguid);
3977 // the player was uninvited already on logout so just remove from group
3978 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", guid);
3979 if(resultGroup)
3981 uint32 groupId = (*resultGroup)[0].GetUInt32();
3982 delete resultGroup;
3983 if (Group* group = sObjectMgr.GetGroupById(groupId))
3984 RemoveFromGroup(group, playerguid);
3987 // remove signs from petitions (also remove petitions if owner);
3988 RemovePetitionsAndSigns(playerguid, 10);
3990 // return back all mails with COD and Item 0 1 2 3 4 5 6 7
3991 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);
3992 if(resultMail)
3996 Field *fields = resultMail->Fetch();
3998 uint32 mail_id = fields[0].GetUInt32();
3999 uint16 mailType = fields[1].GetUInt16();
4000 uint16 mailTemplateId= fields[2].GetUInt16();
4001 uint32 sender = fields[3].GetUInt32();
4002 std::string subject = fields[4].GetCppString();
4003 uint32 itemTextId = fields[5].GetUInt32();
4004 uint32 money = fields[6].GetUInt32();
4005 bool has_items = fields[7].GetBool();
4007 //we can return mail now
4008 //so firstly delete the old one
4009 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
4011 // mail not from player
4012 if (mailType != MAIL_NORMAL)
4014 if(has_items)
4015 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
4016 continue;
4019 MailDraft draft(subject, itemTextId);
4020 if (mailTemplateId)
4021 draft = MailDraft(mailTemplateId,false); // itesm already included
4023 if(has_items)
4025 // data needs to be at first place for Item::LoadFromDB
4026 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);
4027 if(resultItems)
4031 Field *fields2 = resultItems->Fetch();
4033 uint32 item_guidlow = fields2[1].GetUInt32();
4034 uint32 item_template = fields2[2].GetUInt32();
4036 ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_template);
4037 if(!itemProto)
4039 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
4040 continue;
4043 Item *pItem = NewItemOrBag(itemProto);
4044 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
4046 pItem->FSetState(ITEM_REMOVED);
4047 pItem->SaveToDB(); // it also deletes item object !
4048 continue;
4051 draft.AddItem(pItem);
4053 while (resultItems->NextRow());
4055 delete resultItems;
4059 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
4061 uint32 pl_account = sObjectMgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
4063 draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender);
4065 while (resultMail->NextRow());
4067 delete resultMail;
4070 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
4071 // Get guids of character's pets, will deleted in transaction
4072 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
4074 // NOW we can finally clear other DB data related to character
4075 CharacterDatabase.BeginTransaction();
4076 if (resultPets)
4080 Field *fields3 = resultPets->Fetch();
4081 uint32 petguidlow = fields3[0].GetUInt32();
4082 Pet::DeleteFromDB(petguidlow);
4083 } while (resultPets->NextRow());
4084 delete resultPets;
4087 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
4088 CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid);
4089 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
4090 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
4091 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
4092 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
4093 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
4094 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
4095 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
4096 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
4097 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
4098 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",guid);
4099 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
4100 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u'",guid);
4101 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
4102 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
4103 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
4104 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
4105 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
4106 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
4107 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
4108 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
4109 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
4110 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
4111 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
4112 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
4113 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u'",guid);
4114 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid);
4115 CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid);
4116 CharacterDatabase.CommitTransaction();
4118 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4119 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
4122 void Player::SetMovement(PlayerMovementType pType)
4124 WorldPacket data;
4125 switch(pType)
4127 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
4128 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
4129 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
4130 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
4131 default:
4132 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
4133 return;
4135 data.append(GetPackGUID());
4136 data << uint32(0);
4137 GetSession()->SendPacket( &data );
4140 /* Preconditions:
4141 - a resurrectable corpse must not be loaded for the player (only bones)
4142 - the player must be in world
4144 void Player::BuildPlayerRepop()
4146 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
4147 data.append(GetPackGUID());
4148 GetSession()->SendPacket(&data);
4150 if(getRace() == RACE_NIGHTELF)
4151 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)
4152 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4154 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4155 // there must be SMSG.STOP_MIRROR_TIMER
4156 // there we must send 888 opcode
4158 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4159 if(GetCorpse())
4161 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4162 assert(false);
4165 // create a corpse and place it at the player's location
4166 CreateCorpse();
4167 Corpse *corpse = GetCorpse();
4168 if(!corpse)
4170 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4171 return;
4173 GetMap()->Add(corpse);
4175 // convert player body to ghost
4176 SetHealth( 1 );
4178 SetMovement(MOVE_WATER_WALK);
4179 if(!GetSession()->isLogingOut())
4180 SetMovement(MOVE_UNROOT);
4182 // BG - remove insignia related
4183 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
4185 SendCorpseReclaimDelay();
4187 // to prevent cheating
4188 corpse->ResetGhostTime();
4190 StopMirrorTimers(); //disable timers(bars)
4192 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
4194 // set and clear other
4195 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
4198 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
4200 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
4201 data << uint32(-1);
4202 data << float(0);
4203 data << float(0);
4204 data << float(0);
4205 GetSession()->SendPacket(&data);
4207 // speed change, land walk
4209 // remove death flag + set aura
4210 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4211 if(getRace() == RACE_NIGHTELF)
4212 RemoveAurasDueToSpell(20584); // speed bonuses
4213 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4215 setDeathState(ALIVE);
4217 SetMovement(MOVE_LAND_WALK);
4218 SetMovement(MOVE_UNROOT);
4220 m_deathTimer = 0;
4222 // set health/powers (0- will be set in caller)
4223 if(restore_percent>0.0f)
4225 SetHealth(uint32(GetMaxHealth()*restore_percent));
4226 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4227 SetPower(POWER_RAGE, 0);
4228 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4231 // trigger update zone for alive state zone updates
4232 uint32 newzone, newarea;
4233 GetZoneAndAreaId(newzone,newarea);
4234 UpdateZone(newzone,newarea);
4236 // update visibility
4237 UpdateVisibilityForPlayer();
4239 if(!applySickness)
4240 return;
4242 //Characters from level 1-10 are not affected by resurrection sickness.
4243 //Characters from level 11-19 will suffer from one minute of sickness
4244 //for each level they are above 10.
4245 //Characters level 20 and up suffer from ten minutes of sickness.
4246 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
4248 if(int32(getLevel()) >= startLevel)
4250 // set resurrection sickness
4251 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4253 // not full duration
4254 if(int32(getLevel()) < startLevel+9)
4256 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4258 for(int i =0; i < 3; ++i)
4260 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4262 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4263 Aur->SendAuraUpdate(false);
4270 void Player::KillPlayer()
4272 SetMovement(MOVE_ROOT);
4274 StopMirrorTimers(); //disable timers(bars)
4276 setDeathState(CORPSE);
4277 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4279 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4280 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4282 // 6 minutes until repop at graveyard
4283 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4285 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4287 // don't create corpse at this moment, player might be falling
4289 // update visibility
4290 UpdateObjectVisibility();
4293 void Player::CreateCorpse()
4295 // prevent existence 2 corpse for player
4296 SpawnCorpseBones();
4298 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4300 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4301 SetPvPDeath(false);
4303 if(!corpse->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4305 delete corpse;
4306 return;
4309 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4310 _pb = GetUInt32Value(PLAYER_BYTES);
4311 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4313 uint8 race = (uint8)(_uf);
4314 uint8 skin = (uint8)(_pb);
4315 uint8 face = (uint8)(_pb >> 8);
4316 uint8 hairstyle = (uint8)(_pb >> 16);
4317 uint8 haircolor = (uint8)(_pb >> 24);
4318 uint8 facialhair = (uint8)(_pb2);
4320 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4321 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4323 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4324 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4326 uint32 flags = CORPSE_FLAG_UNK2;
4327 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4328 flags |= CORPSE_FLAG_HIDE_HELM;
4329 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4330 flags |= CORPSE_FLAG_HIDE_CLOAK;
4331 if(InBattleGround() && !InArena())
4332 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4333 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4335 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4337 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4339 uint32 iDisplayID;
4340 uint32 iIventoryType;
4341 uint32 _cfi;
4342 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4344 if(m_items[i])
4346 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4347 iIventoryType = m_items[i]->GetProto()->InventoryType;
4349 _cfi = iDisplayID | (iIventoryType << 24);
4350 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi);
4354 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4355 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4356 assert(entry);
4357 if(entry->map_type != MAP_BATTLEGROUND)
4358 corpse->SaveToDB();
4360 // register for player, but not show
4361 sObjectAccessor.AddCorpse(corpse);
4364 void Player::SpawnCorpseBones()
4366 if(sObjectAccessor.ConvertCorpseForPlayer(GetGUID()))
4367 if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
4368 SaveToDB(); // prevent loading as ghost without corpse
4371 Corpse* Player::GetCorpse() const
4373 return sObjectAccessor.GetCorpseForPlayerGUID(GetGUID());
4376 void Player::DurabilityLossAll(double percent, bool inventory)
4378 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4379 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4380 DurabilityLoss(pItem,percent);
4382 if(inventory)
4384 // bags not have durability
4385 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4387 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4388 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4389 DurabilityLoss(pItem,percent);
4391 // keys not have durability
4392 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4394 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4395 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4396 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4397 if(Item* pItem = GetItemByPos( i, j ))
4398 DurabilityLoss(pItem,percent);
4402 void Player::DurabilityLoss(Item* item, double percent)
4404 if(!item )
4405 return;
4407 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4409 if(!pMaxDurability)
4410 return;
4412 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4414 if(pDurabilityLoss < 1 )
4415 pDurabilityLoss = 1;
4417 DurabilityPointsLoss(item,pDurabilityLoss);
4420 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4422 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4423 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4424 DurabilityPointsLoss(pItem,points);
4426 if(inventory)
4428 // bags not have durability
4429 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4431 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4432 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4433 DurabilityPointsLoss(pItem,points);
4435 // keys not have durability
4436 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4438 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4439 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4440 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4441 if(Item* pItem = GetItemByPos( i, j ))
4442 DurabilityPointsLoss(pItem,points);
4446 void Player::DurabilityPointsLoss(Item* item, int32 points)
4448 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4449 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4450 int32 pNewDurability = pOldDurability - points;
4452 if (pNewDurability < 0)
4453 pNewDurability = 0;
4454 else if (pNewDurability > pMaxDurability)
4455 pNewDurability = pMaxDurability;
4457 if (pOldDurability != pNewDurability)
4459 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4460 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4461 _ApplyItemMods(item,item->GetSlot(), false);
4463 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4465 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4466 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4467 _ApplyItemMods(item,item->GetSlot(), true);
4469 item->SetState(ITEM_CHANGED, this);
4473 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4475 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4476 DurabilityPointsLoss(pItem,1);
4479 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4481 uint32 TotalCost = 0;
4482 // equipped, backpack, bags itself
4483 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4484 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4486 // bank, buyback and keys not repaired
4488 // items in inventory bags
4489 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4490 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4491 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4492 return TotalCost;
4495 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4497 Item* item = GetItemByPos(pos);
4499 uint32 TotalCost = 0;
4500 if(!item)
4501 return TotalCost;
4503 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4504 if(!maxDurability)
4505 return TotalCost;
4507 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4509 if(cost)
4511 uint32 LostDurability = maxDurability - curDurability;
4512 if(LostDurability>0)
4514 ItemPrototype const *ditemProto = item->GetProto();
4516 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4517 if(!dcost)
4519 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4520 return TotalCost;
4523 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4524 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4525 if(!dQualitymodEntry)
4527 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4528 return TotalCost;
4531 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4532 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4534 costs = uint32(costs * discountMod);
4536 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4537 costs = 1;
4539 if (guildBank)
4541 if (GetGuildId()==0)
4543 DEBUG_LOG("You are not member of a guild");
4544 return TotalCost;
4547 Guild *pGuild = sObjectMgr.GetGuildById(GetGuildId());
4548 if (!pGuild)
4549 return TotalCost;
4551 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4553 DEBUG_LOG("You do not have rights to withdraw for repairs");
4554 return TotalCost;
4557 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4559 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4560 return TotalCost;
4563 if (pGuild->GetGuildBankMoney() < costs)
4565 DEBUG_LOG("There is not enough money in bank");
4566 return TotalCost;
4569 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4570 TotalCost = costs;
4572 else if (GetMoney() < costs)
4574 DEBUG_LOG("You do not have enough money");
4575 return TotalCost;
4577 else
4578 ModifyMoney( -int32(costs) );
4582 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4583 item->SetState(ITEM_CHANGED, this);
4585 // reapply mods for total broken and repaired item if equipped
4586 if(IsEquipmentPos(pos) && !curDurability)
4587 _ApplyItemMods(item,pos & 255, true);
4588 return TotalCost;
4591 void Player::RepopAtGraveyard()
4593 // note: this can be called also when the player is alive
4594 // for example from WorldSession::HandleMovementOpcodes
4596 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4598 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4599 if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport())
4601 ResurrectPlayer(0.5f);
4602 SpawnCorpseBones();
4605 WorldSafeLocsEntry const *ClosestGrave = NULL;
4607 // Special handle for battleground maps
4608 if( BattleGround *bg = GetBattleGround() )
4609 ClosestGrave = bg->GetClosestGraveYard(this);
4610 else
4611 ClosestGrave = sObjectMgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4613 // stop countdown until repop
4614 m_deathTimer = 0;
4616 // if no grave found, stay at the current location
4617 // and don't show spirit healer location
4618 if(ClosestGrave)
4620 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4621 if(isDead()) // not send if alive, because it used in TeleportTo()
4623 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4624 data << ClosestGrave->map_id;
4625 data << ClosestGrave->x;
4626 data << ClosestGrave->y;
4627 data << ClosestGrave->z;
4628 GetSession()->SendPacket(&data);
4633 void Player::JoinedChannel(Channel *c)
4635 m_channels.push_back(c);
4638 void Player::LeftChannel(Channel *c)
4640 m_channels.remove(c);
4643 void Player::CleanupChannels()
4645 while(!m_channels.empty())
4647 Channel* ch = *m_channels.begin();
4648 m_channels.erase(m_channels.begin()); // remove from player's channel list
4649 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4650 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4651 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4654 sLog.outDebug("Player: channels cleaned up!");
4657 void Player::UpdateLocalChannels(uint32 newZone )
4659 if(m_channels.empty())
4660 return;
4662 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4663 if(!current_zone)
4664 return;
4666 ChannelMgr* cMgr = channelMgr(GetTeam());
4667 if(!cMgr)
4668 return;
4670 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4672 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4674 next = i; ++next;
4676 // skip non built-in channels
4677 if(!(*i)->IsConstant())
4678 continue;
4680 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4681 if(!ch)
4682 continue;
4684 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4685 continue;
4687 // new channel
4688 char new_channel_name_buf[100];
4689 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4690 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4692 if((*i)!=new_channel)
4694 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4696 // leave old channel
4697 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4698 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4699 LeftChannel(*i); // remove from player's channel list
4700 cMgr->LeftChannel(name); // delete if empty
4703 sLog.outDebug("Player: channels cleaned up!");
4706 void Player::LeaveLFGChannel()
4708 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4710 if((*i)->IsLFG())
4712 (*i)->Leave(GetGUID());
4713 break;
4718 void Player::UpdateDefense()
4720 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4722 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4724 // update dependent from defense skill part
4725 UpdateDefenseBonusesMod();
4729 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4731 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4733 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4734 return;
4737 float val = 1.0f;
4739 switch(modType)
4741 case FLAT_MOD:
4742 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4743 break;
4744 case PCT_MOD:
4745 if(amount <= -100.0f)
4746 amount = -200.0f;
4748 val = (100.0f + amount) / 100.0f;
4749 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4750 break;
4753 if(!CanModifyStats())
4754 return;
4756 switch(modGroup)
4758 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4759 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4760 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4761 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4762 default: break;
4766 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4768 if(modGroup >= BASEMOD_END || modType > MOD_END)
4770 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4771 return 0.0f;
4774 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4775 return 0.0f;
4777 return m_auraBaseMod[modGroup][modType];
4780 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4782 if(modGroup >= BASEMOD_END)
4784 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4785 return 0.0f;
4788 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4789 return 0.0f;
4791 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4794 uint32 Player::GetShieldBlockValue() const
4796 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4798 value = (value < 0) ? 0 : value;
4800 return uint32(value);
4803 float Player::GetMeleeCritFromAgility()
4805 uint32 level = getLevel();
4806 uint32 pclass = getClass();
4808 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4810 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4811 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4812 if (critBase==NULL || critRatio==NULL)
4813 return 0.0f;
4815 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4816 return crit*100.0f;
4819 float Player::GetDodgeFromAgility()
4821 // Table for base dodge values
4822 float dodge_base[MAX_CLASSES] = {
4823 0.0075f, // Warrior
4824 0.00652f, // Paladin
4825 -0.0545f, // Hunter
4826 -0.0059f, // Rogue
4827 0.03183f, // Priest
4828 0.0114f, // DK
4829 0.0167f, // Shaman
4830 0.034575f, // Mage
4831 0.02011f, // Warlock
4832 0.0f, // ??
4833 -0.0187f // Druid
4835 // Crit/agility to dodge/agility coefficient multipliers
4836 float crit_to_dodge[MAX_CLASSES] = {
4837 1.1f, // Warrior
4838 1.0f, // Paladin
4839 1.6f, // Hunter
4840 2.0f, // Rogue
4841 1.0f, // Priest
4842 1.0f, // DK?
4843 1.0f, // Shaman
4844 1.0f, // Mage
4845 1.0f, // Warlock
4846 0.0f, // ??
4847 1.7f // Druid
4850 uint32 level = getLevel();
4851 uint32 pclass = getClass();
4853 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4855 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4856 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4857 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4858 return 0.0f;
4860 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4861 return dodge*100.0f;
4864 float Player::GetSpellCritFromIntellect()
4866 uint32 level = getLevel();
4867 uint32 pclass = getClass();
4869 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4871 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4872 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4873 if (critBase==NULL || critRatio==NULL)
4874 return 0.0f;
4876 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4877 return crit*100.0f;
4880 float Player::GetRatingCoefficient(CombatRating cr) const
4882 uint32 level = getLevel();
4884 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4886 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4887 if (Rating == NULL)
4888 return 1.0f; // By default use minimum coefficient (not must be called)
4890 return Rating->ratio;
4893 float Player::GetRatingBonusValue(CombatRating cr) const
4895 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4898 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4900 switch (attType)
4902 case BASE_ATTACK:
4903 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4904 case OFF_ATTACK:
4905 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4906 default:
4907 break;
4909 return 0.0f;
4912 float Player::OCTRegenHPPerSpirit()
4914 uint32 level = getLevel();
4915 uint32 pclass = getClass();
4917 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4919 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4920 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4921 if (baseRatio==NULL || moreRatio==NULL)
4922 return 0.0f;
4924 // Formula from PaperDollFrame script
4925 float spirit = GetStat(STAT_SPIRIT);
4926 float baseSpirit = spirit;
4927 if (baseSpirit>50) baseSpirit = 50;
4928 float moreSpirit = spirit - baseSpirit;
4929 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4930 return regen;
4933 float Player::OCTRegenMPPerSpirit()
4935 uint32 level = getLevel();
4936 uint32 pclass = getClass();
4938 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4940 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4941 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4942 if (moreRatio==NULL)
4943 return 0.0f;
4945 // Formula get from PaperDollFrame script
4946 float spirit = GetStat(STAT_SPIRIT);
4947 float regen = spirit * moreRatio->ratio;
4948 return regen;
4951 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4953 m_baseRatingValue[cr]+=(apply ? value : -value);
4955 // explicit affected values
4956 switch (cr)
4958 case CR_HASTE_MELEE:
4960 float RatingChange = value / GetRatingCoefficient(cr);
4961 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4962 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4963 break;
4965 case CR_HASTE_RANGED:
4967 float RatingChange = value / GetRatingCoefficient(cr);
4968 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4969 break;
4971 case CR_HASTE_SPELL:
4973 float RatingChange = value / GetRatingCoefficient(cr);
4974 ApplyCastTimePercentMod(RatingChange,apply);
4975 break;
4979 UpdateRating(cr);
4982 void Player::UpdateRating(CombatRating cr)
4984 int32 amount = m_baseRatingValue[cr];
4985 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4986 // stat used stored in miscValueB for this aura
4987 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4988 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4989 if ((*i)->GetMiscValue() & (1<<cr))
4990 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4991 if (amount < 0)
4992 amount = 0;
4993 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4995 bool affectStats = CanModifyStats();
4997 switch (cr)
4999 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
5000 case CR_DEFENSE_SKILL:
5001 UpdateDefenseBonusesMod();
5002 break;
5003 case CR_DODGE:
5004 UpdateDodgePercentage();
5005 break;
5006 case CR_PARRY:
5007 UpdateParryPercentage();
5008 break;
5009 case CR_BLOCK:
5010 UpdateBlockPercentage();
5011 break;
5012 case CR_HIT_MELEE:
5013 UpdateMeleeHitChances();
5014 break;
5015 case CR_HIT_RANGED:
5016 UpdateRangedHitChances();
5017 break;
5018 case CR_HIT_SPELL:
5019 UpdateSpellHitChances();
5020 break;
5021 case CR_CRIT_MELEE:
5022 if(affectStats)
5024 UpdateCritPercentage(BASE_ATTACK);
5025 UpdateCritPercentage(OFF_ATTACK);
5027 break;
5028 case CR_CRIT_RANGED:
5029 if(affectStats)
5030 UpdateCritPercentage(RANGED_ATTACK);
5031 break;
5032 case CR_CRIT_SPELL:
5033 if(affectStats)
5034 UpdateAllSpellCritChances();
5035 break;
5036 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
5037 case CR_HIT_TAKEN_RANGED:
5038 break;
5039 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
5040 break;
5041 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
5042 case CR_CRIT_TAKEN_RANGED:
5043 break;
5044 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
5045 break;
5046 case CR_HASTE_MELEE: // Implemented in Player::ApplyRatingMod
5047 case CR_HASTE_RANGED:
5048 case CR_HASTE_SPELL:
5049 break;
5050 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
5051 case CR_WEAPON_SKILL_OFFHAND:
5052 case CR_WEAPON_SKILL_RANGED:
5053 break;
5054 case CR_EXPERTISE:
5055 if(affectStats)
5057 UpdateExpertise(BASE_ATTACK);
5058 UpdateExpertise(OFF_ATTACK);
5060 break;
5061 case CR_ARMOR_PENETRATION:
5062 if(affectStats)
5063 UpdateArmorPenetration();
5064 break;
5068 void Player::UpdateAllRatings()
5070 for(int cr = 0; cr < MAX_COMBAT_RATING; ++cr)
5071 UpdateRating(CombatRating(cr));
5074 void Player::SetRegularAttackTime()
5076 for(int i = 0; i < MAX_ATTACK; ++i)
5078 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i),true,false);
5079 if (tmpitem)
5081 ItemPrototype const *proto = tmpitem->GetProto();
5082 if(proto->Delay)
5083 SetAttackTime(WeaponAttackType(i), proto->Delay);
5084 else
5085 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
5090 //skill+step, checking for max value
5091 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
5093 if(!skill_id)
5094 return false;
5096 SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
5097 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5098 return false;
5100 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5101 uint32 data = GetUInt32Value(valueIndex);
5102 uint32 value = SKILL_VALUE(data);
5103 uint32 max = SKILL_MAX(data);
5105 if ((!max) || (!value) || (value >= max))
5106 return false;
5108 if (value*512 < max*urand(0,512))
5110 uint32 new_value = value+step;
5111 if(new_value > max)
5112 new_value = max;
5114 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,max));
5115 if(itr->second.uState != SKILL_NEW)
5116 itr->second.uState = SKILL_CHANGED;
5117 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
5118 return true;
5121 return false;
5124 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
5126 if ( SkillValue >= GrayLevel )
5127 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
5128 if ( SkillValue >= GreenLevel )
5129 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
5130 if ( SkillValue >= YellowLevel )
5131 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
5132 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
5135 bool Player::UpdateCraftSkill(uint32 spellid)
5137 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
5139 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spellid);
5141 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
5143 if (_spell_idx->second->skillId)
5145 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
5147 // Alchemy Discoveries here
5148 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
5149 if (spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
5151 if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
5152 learnSpell(discoveredSpell,false);
5155 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
5157 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
5158 _spell_idx->second->max_value,
5159 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
5160 _spell_idx->second->min_value),
5161 craft_skill_gain);
5164 return false;
5167 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
5169 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
5171 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5173 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5174 switch (SkillId)
5176 case SKILL_HERBALISM:
5177 case SKILL_LOCKPICKING:
5178 case SKILL_JEWELCRAFTING:
5179 case SKILL_INSCRIPTION:
5180 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5181 case SKILL_SKINNING:
5182 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
5183 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5184 else
5185 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
5186 case SKILL_MINING:
5187 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
5188 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5189 else
5190 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
5192 return false;
5195 bool Player::UpdateFishingSkill()
5197 sLog.outDebug("UpdateFishingSkill");
5199 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5201 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5203 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5205 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5208 // levels sync. with spell requirement for skill levels to learn
5209 // bonus abilities in sSkillLineAbilityStore
5210 // Used only to avoid scan DBC at each skill grow
5211 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5213 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5215 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5216 if ( !SkillId )
5217 return false;
5219 if(Chance <= 0) // speedup in 0 chance case
5221 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5222 return false;
5225 SkillStatusMap::iterator itr = mSkillStatus.find(SkillId);
5226 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5227 return false;
5229 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5231 uint32 data = GetUInt32Value(valueIndex);
5232 uint16 SkillValue = SKILL_VALUE(data);
5233 uint16 MaxValue = SKILL_MAX(data);
5235 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5236 return false;
5238 int32 Roll = irand(1,1000);
5240 if ( Roll <= Chance )
5242 uint32 new_value = SkillValue+step;
5243 if(new_value > MaxValue)
5244 new_value = MaxValue;
5246 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,MaxValue));
5247 if(itr->second.uState != SKILL_NEW)
5248 itr->second.uState = SKILL_CHANGED;
5249 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5251 if((SkillValue < *bsl && new_value >= *bsl))
5253 learnSkillRewardedSpells( SkillId, new_value);
5254 break;
5257 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5258 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5259 return true;
5262 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5263 return false;
5266 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5268 // no skill gain in pvp
5269 Unit *pVictim = getVictim();
5270 if(pVictim && pVictim->IsCharmerOrOwnerPlayerOrPlayerItself())
5271 return;
5273 if(IsInFeralForm())
5274 return; // always maximized SKILL_FERAL_COMBAT in fact
5276 if(m_form == FORM_TREE)
5277 return; // use weapon but not skill up
5279 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5281 switch(attType)
5283 case BASE_ATTACK:
5285 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5287 if (!tmpitem)
5288 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5289 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5290 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5291 break;
5293 case OFF_ATTACK:
5294 case RANGED_ATTACK:
5296 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5297 if (tmpitem)
5298 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5299 break;
5302 UpdateAllCritPercentages();
5305 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5307 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5308 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5309 uint32 moblevel = pVictim->getLevelForTarget(this);
5310 if(moblevel < greylevel)
5311 return;
5313 if (moblevel > plevel + 5)
5314 moblevel = plevel + 5;
5316 uint32 lvldif = moblevel - greylevel;
5317 if(lvldif < 3)
5318 lvldif = 3;
5320 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5321 if(skilldif <= 0)
5322 return;
5324 float chance = float(3 * lvldif * skilldif) / plevel;
5325 if(!defence)
5327 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5328 chance *= 0.1f * GetStat(STAT_INTELLECT);
5331 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5333 if(roll_chance_f(chance))
5335 if(defence)
5336 UpdateDefense();
5337 else
5338 UpdateWeaponSkill(attType);
5340 else
5341 return;
5344 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5346 SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid);
5347 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5348 return;
5350 uint32 bonusIndex = PLAYER_SKILL_BONUS_INDEX(itr->second.pos);
5352 uint32 bonus_val = GetUInt32Value(bonusIndex);
5353 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5354 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5356 if(talent) // permanent bonus stored in high part
5357 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5358 else // temporary/item bonus stored in low part
5359 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5362 void Player::UpdateSkillsForLevel()
5364 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5365 uint32 maxSkill = GetMaxSkillValueForLevel();
5367 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5369 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5371 if(itr->second.uState == SKILL_DELETED)
5372 continue;
5374 uint32 pskill = itr->first;
5376 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5377 if(!pSkill)
5378 continue;
5380 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5381 continue;
5383 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5384 uint32 data = GetUInt32Value(valueIndex);
5385 uint32 max = SKILL_MAX(data);
5386 uint32 val = SKILL_VALUE(data);
5388 /// update only level dependent max skill values
5389 if(max!=1)
5391 /// maximize skill always
5392 if(alwaysMaxSkill)
5394 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(maxSkill,maxSkill));
5395 if(itr->second.uState != SKILL_NEW)
5396 itr->second.uState = SKILL_CHANGED;
5398 else if(max != maxconfskill) /// update max skill value if current max skill not maximized
5400 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(val,maxSkill));
5401 if(itr->second.uState != SKILL_NEW)
5402 itr->second.uState = SKILL_CHANGED;
5408 void Player::UpdateSkillsToMaxSkillsForLevel()
5410 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5412 if(itr->second.uState == SKILL_DELETED)
5413 continue;
5415 uint32 pskill = itr->first;
5416 if( IsProfessionOrRidingSkill(pskill))
5417 continue;
5418 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5419 uint32 data = GetUInt32Value(valueIndex);
5421 uint32 max = SKILL_MAX(data);
5423 if(max > 1)
5425 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(max,max));
5426 if(itr->second.uState != SKILL_NEW)
5427 itr->second.uState = SKILL_CHANGED;
5430 if(pskill == SKILL_DEFENSE)
5431 UpdateDefenseBonusesMod();
5435 // This functions sets a skill line value (and adds if doesn't exist yet)
5436 // To "remove" a skill line, set it's values to zero
5437 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5439 if(!id)
5440 return;
5442 SkillStatusMap::iterator itr = mSkillStatus.find(id);
5444 //has skill
5445 if(itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED)
5447 if(currVal)
5449 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),MAKE_SKILL_VALUE(currVal,maxVal));
5450 if(itr->second.uState != SKILL_NEW)
5451 itr->second.uState = SKILL_CHANGED;
5452 learnSkillRewardedSpells(id, currVal);
5453 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5454 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5456 else //remove
5458 // clear skill fields
5459 SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos),0);
5460 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),0);
5461 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos),0);
5463 // mark as deleted or simply remove from map if not saved yet
5464 if(itr->second.uState != SKILL_NEW)
5465 itr->second.uState = SKILL_DELETED;
5466 else
5467 mSkillStatus.erase(itr);
5469 // remove all spells that related to this skill
5470 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5471 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5472 if (pAbility->skillId==id)
5473 removeSpell(sSpellMgr.GetFirstSpellInChain(pAbility->spellId));
5476 else if(currVal) //add
5478 for (int i=0; i < PLAYER_MAX_SKILLS; ++i)
5479 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5481 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5482 if(!pSkill)
5484 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5485 return;
5487 // enable unlearn button for primary professions only
5488 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5489 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5490 else
5491 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5492 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5493 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5494 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5496 // insert new entry or update if not deleted old entry yet
5497 if(itr != mSkillStatus.end())
5499 itr->second.pos = i;
5500 itr->second.uState = SKILL_CHANGED;
5502 else
5503 mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW)));
5505 // apply skill bonuses
5506 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5508 // temporary bonuses
5509 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5510 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5511 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5512 (*j)->ApplyModifier(true);
5514 // permanent bonuses
5515 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5516 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5517 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5518 (*j)->ApplyModifier(true);
5520 // Learn all spells for skill
5521 learnSkillRewardedSpells(id, currVal);
5522 return;
5527 bool Player::HasSkill(uint32 skill) const
5529 if(!skill)
5530 return false;
5532 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5533 return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED);
5536 uint16 Player::GetSkillValue(uint32 skill) const
5538 if(!skill)
5539 return 0;
5541 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5542 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5543 return 0;
5545 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5547 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5548 result += SKILL_TEMP_BONUS(bonus);
5549 result += SKILL_PERM_BONUS(bonus);
5550 return result < 0 ? 0 : result;
5553 uint16 Player::GetMaxSkillValue(uint32 skill) const
5555 if(!skill)
5556 return 0;
5558 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5559 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5560 return 0;
5562 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5564 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5565 result += SKILL_TEMP_BONUS(bonus);
5566 result += SKILL_PERM_BONUS(bonus);
5567 return result < 0 ? 0 : result;
5570 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5572 if(!skill)
5573 return 0;
5575 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5576 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5577 return 0;
5579 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5582 uint16 Player::GetBaseSkillValue(uint32 skill) const
5584 if(!skill)
5585 return 0;
5587 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5588 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5589 return 0;
5591 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5592 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5593 return result < 0 ? 0 : result;
5596 uint16 Player::GetPureSkillValue(uint32 skill) const
5598 if(!skill)
5599 return 0;
5601 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5602 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5603 return 0;
5605 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5608 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5610 if(!skill)
5611 return 0;
5613 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5614 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5615 return 0;
5617 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5620 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5622 if(!skill)
5623 return 0;
5625 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5626 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5627 return 0;
5629 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5632 void Player::SendInitialActionButtons() const
5634 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5636 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5637 data << uint8(1); // can be 0, 1, 2 (talent spec)
5638 ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
5639 for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button)
5641 ActionButtonList::const_iterator itr = currentActionButtonList.find(button);
5642 if(itr != currentActionButtonList.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5643 data << uint32(itr->second.packedData);
5644 else
5645 data << uint32(0);
5648 GetSession()->SendPacket( &data );
5649 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5652 bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Player* player)
5654 if(button >= MAX_ACTION_BUTTONS)
5656 if (player)
5657 sLog.outError( "Action %u not added into button %u for player %s: button must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTONS );
5658 else
5659 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action, button, MAX_ACTION_BUTTONS );
5660 return false;
5663 if(action >= MAX_ACTION_BUTTON_ACTION_VALUE)
5665 if (player)
5666 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 );
5667 else
5668 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action, button, MAX_ACTION_BUTTON_ACTION_VALUE );
5669 return false;
5672 switch(type)
5674 case ACTION_BUTTON_SPELL:
5675 if(!sSpellStore.LookupEntry(action))
5677 if (player)
5678 sLog.outError( "Spell action %u not added into button %u for player %s: spell not exist", action, button, player->GetName() );
5679 else
5680 sLog.outError( "Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action, button );
5681 return false;
5684 if(player && !player->HasSpell(action))
5686 sLog.outError( "Spell action %u not added into button %u for player %s: player don't known this spell", action, button, player->GetName() );
5687 return false;
5689 break;
5690 case ACTION_BUTTON_ITEM:
5691 if(!ObjectMgr::GetItemPrototype(action))
5693 if (player)
5694 sLog.outError( "Item action %u not added into button %u for player %s: item not exist", action, button, player->GetName() );
5695 else
5696 sLog.outError( "Table `playercreateinfo_action` have item action %u into button %u: item not exist", action, button );
5697 return false;
5699 break;
5700 default:
5701 break; // other cases not checked at this moment
5704 return true;
5707 ActionButton* Player::addActionButton(uint8 spec, uint8 button, uint32 action, uint8 type)
5709 // check action only for active spec (so not check at copy/load passive spec)
5710 if (spec == GetActiveSpec() && !IsActionButtonDataValid(button,action,type,this))
5711 return NULL;
5713 // it create new button (NEW state) if need or return existed
5714 ActionButton& ab = m_actionButtons[spec][button];
5716 // set data and update to CHANGED if not NEW
5717 ab.SetActionAndType(action,ActionButtonType(type));
5719 sLog.outDetail("Player '%u' Added Action '%u' (type %u) to Button '%u' for spec %u", GetGUIDLow(), action, uint32(type), button, spec);
5720 return &ab;
5723 void Player::removeActionButton(uint8 spec, uint8 button)
5725 ActionButtonList& currentActionButtonList = m_actionButtons[spec];
5726 ActionButtonList::iterator buttonItr = currentActionButtonList.find(button);
5727 if (buttonItr == currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
5728 return;
5730 if (buttonItr->second.uState == ACTIONBUTTON_NEW)
5731 currentActionButtonList.erase(buttonItr); // new and not saved
5732 else
5733 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5735 sLog.outDetail("Action Button '%u' Removed from Player '%u' for spec %u", button, GetGUIDLow(), spec);
5738 ActionButton const* Player::GetActionButton(uint8 button)
5740 ActionButtonList& currentActionButtonList = m_actionButtons[m_activeSpec];
5741 ActionButtonList::iterator buttonItr = currentActionButtonList.find(button);
5742 if (buttonItr==currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
5743 return NULL;
5745 return &buttonItr->second;
5748 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5750 // prevent crash when a bad coord is sent by the client
5751 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5753 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5754 return false;
5757 Map *m = GetMap();
5759 const float old_x = GetPositionX();
5760 const float old_y = GetPositionY();
5761 const float old_z = GetPositionZ();
5762 const float old_r = GetOrientation();
5764 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5766 if (teleport || old_x != x || old_y != y || old_z != z)
5767 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5768 else
5769 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5771 // move and update visible state if need
5772 m->PlayerRelocation(this, x, y, z, orientation);
5774 // reread after Map::Relocation
5775 m = GetMap();
5776 x = GetPositionX();
5777 y = GetPositionY();
5778 z = GetPositionZ();
5780 // group update
5781 if(GetGroup() && (old_x != x || old_y != y))
5782 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5785 // code block for underwater state update
5786 UpdateUnderwaterState(m, x, y, z);
5788 CheckExploreSystem();
5790 return true;
5793 void Player::SaveRecallPosition()
5795 m_recallMap = GetMapId();
5796 m_recallX = GetPositionX();
5797 m_recallY = GetPositionY();
5798 m_recallZ = GetPositionZ();
5799 m_recallO = GetOrientation();
5802 void Player::SendMessageToSet(WorldPacket *data, bool self)
5804 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5805 if(_map)
5807 _map->MessageBroadcast(this, data, self);
5808 return;
5811 //if player is not in world and map in not created/already destroyed
5812 //no need to create one, just send packet for itself!
5813 if(self)
5814 GetSession()->SendPacket(data);
5817 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5819 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5820 if(_map)
5822 _map->MessageDistBroadcast(this, data, dist, self);
5823 return;
5826 if(self)
5827 GetSession()->SendPacket(data);
5830 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5832 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5833 if(_map)
5835 _map->MessageDistBroadcast(this, data, dist, self, own_team_only);
5836 return;
5839 if(self)
5840 GetSession()->SendPacket(data);
5843 void Player::SendDirectMessage(WorldPacket *data)
5845 GetSession()->SendPacket(data);
5848 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5850 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5851 data << uint32(CinematicSequenceId);
5852 SendDirectMessage(&data);
5855 void Player::SendMovieStart(uint32 MovieId)
5857 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5858 data << uint32(MovieId);
5859 SendDirectMessage(&data);
5862 void Player::CheckExploreSystem()
5864 if (!isAlive())
5865 return;
5867 if (isInFlight())
5868 return;
5870 uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5871 if(areaFlag==0xffff)
5872 return;
5873 int offset = areaFlag / 32;
5875 if(offset >= 128)
5877 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);
5878 return;
5881 uint32 val = (uint32)(1 << (areaFlag % 32));
5882 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5884 if( !(currFields & val) )
5886 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5888 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5890 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5891 if(!p)
5893 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5895 else if(p->area_level > 0)
5897 uint32 area = p->ID;
5898 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5900 SendExplorationExperience(area,0);
5902 else
5904 int32 diff = int32(getLevel()) - p->area_level;
5905 uint32 XP = 0;
5906 if (diff < -5)
5908 XP = uint32(sObjectMgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5910 else if (diff > 5)
5912 int32 exploration_percent = (100-((diff-5)*5));
5913 if (exploration_percent > 100)
5914 exploration_percent = 100;
5915 else if (exploration_percent < 0)
5916 exploration_percent = 0;
5918 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5920 else
5922 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5925 GiveXP( XP, NULL );
5926 SendExplorationExperience(area,XP);
5928 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5933 uint32 Player::TeamForRace(uint8 race)
5935 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5936 if(!rEntry)
5938 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5939 return ALLIANCE;
5942 switch(rEntry->TeamID)
5944 case 7: return ALLIANCE;
5945 case 1: return HORDE;
5948 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5949 return ALLIANCE;
5952 uint32 Player::getFactionForRace(uint8 race)
5954 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5955 if(!rEntry)
5957 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5958 return 0;
5961 return rEntry->FactionID;
5964 void Player::setFactionForRace(uint8 race)
5966 m_team = TeamForRace(race);
5967 setFaction( getFactionForRace(race) );
5970 ReputationRank Player::GetReputationRank(uint32 faction) const
5972 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5973 return GetReputationMgr().GetRank(factionEntry);
5976 //Calculate total reputation percent player gain with quest/creature level
5977 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5979 float percent = 100.0f;
5981 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5983 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5984 percent *= rate;
5986 float repMod = (float)GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5988 if (!for_quest)
5989 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
5991 percent += rep > 0 ? repMod : -repMod;
5993 if (percent <= 0.0f)
5994 return 0;
5996 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100.0f);
5999 //Calculates how many reputation points player gains in victim's enemy factions
6000 void Player::RewardReputation(Unit *pVictim, float rate)
6002 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
6003 return;
6005 ReputationOnKillEntry const* Rep = sObjectMgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
6007 if(!Rep)
6008 return;
6010 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
6012 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
6013 donerep1 = int32(donerep1*rate);
6014 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
6015 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
6016 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
6017 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
6019 // Wiki: Team factions value divided by 2
6020 if (factionEntry1 && Rep->is_teamaward1)
6022 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
6023 if(team1_factionEntry)
6024 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
6028 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
6030 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
6031 donerep2 = int32(donerep2*rate);
6032 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
6033 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
6034 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
6035 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
6037 // Wiki: Team factions value divided by 2
6038 if (factionEntry2 && Rep->is_teamaward2)
6040 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
6041 if(team2_factionEntry)
6042 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
6047 //Calculate how many reputation points player gain with the quest
6048 void Player::RewardReputation(Quest const *pQuest)
6050 // quest reputation reward/loss
6051 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
6053 if (!pQuest->RewRepFaction[i])
6054 continue;
6056 // For future, this row should be used as "override". Example quests are 10298 and 10870.
6057 // Typically, no diplomacy mod must apply to the final value (flat). Note the formula must be (finalValue = DBvalue/100)
6058 if (pQuest->RewRepValue[i])
6060 int32 rep = CalculateReputationGain(GetQuestLevelForPlayer(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
6062 if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
6063 GetReputationMgr().ModifyReputation(factionEntry, rep);
6065 else
6067 uint32 row = ((pQuest->RewRepValueId[i] < 0) ? 1 : 0) + 1;
6068 uint32 field = abs(pQuest->RewRepValueId[i]);
6070 if (const QuestFactionRewardEntry *pRow = sQuestFactionRewardStore.LookupEntry(row))
6072 int32 repPoints = pRow->rewardValue[field];
6074 if (!repPoints)
6075 continue;
6077 repPoints = CalculateReputationGain(GetQuestLevelForPlayer(pQuest), repPoints, pQuest->RewRepFaction[i], true);
6079 if (const FactionEntry* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
6080 GetReputationMgr().ModifyReputation(factionEntry, repPoints);
6085 // TODO: implement reputation spillover
6088 void Player::UpdateArenaFields(void)
6090 /* arena calcs go here */
6093 void Player::UpdateHonorFields()
6095 /// called when rewarding honor and at each save
6096 time_t now = time(NULL);
6097 time_t today = (time(NULL) / DAY) * DAY;
6099 if(m_lastHonorUpdateTime < today)
6101 time_t yesterday = today - DAY;
6103 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
6105 // update yesterday's contribution
6106 if(m_lastHonorUpdateTime >= yesterday )
6108 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
6110 // this is the first update today, reset today's contribution
6111 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
6112 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
6114 else
6116 // no honor/kills yesterday or today, reset
6117 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
6118 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
6122 m_lastHonorUpdateTime = now;
6125 ///Calculate the amount of honor gained based on the victim
6126 ///and the size of the group for which the honor is divided
6127 ///An exact honor value can also be given (overriding the calcs)
6128 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
6130 // do not reward honor in arenas, but enable onkill spellproc
6131 if(InArena())
6133 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
6134 return false;
6136 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
6137 return false;
6139 return true;
6142 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6143 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
6144 return false;
6146 uint64 victim_guid = 0;
6147 uint32 victim_rank = 0;
6149 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6150 UpdateHonorFields();
6152 if(honor <= 0)
6154 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
6155 return false;
6157 victim_guid = uVictim->GetGUID();
6159 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6161 Player *pVictim = (Player *)uVictim;
6163 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6164 return false;
6166 float f = 1; //need for total kills (?? need more info)
6167 uint32 k_grey = 0;
6168 uint32 k_level = getLevel();
6169 uint32 v_level = pVictim->getLevel();
6172 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6173 // [0] Just name
6174 // [1..14] Alliance honor titles and player name
6175 // [15..28] Horde honor titles and player name
6176 // [29..38] Other title and player name
6177 // [39+] Nothing
6178 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6179 // Get Killer titles, CharTitlesEntry::bit_index
6180 // Ranks:
6181 // title[1..14] -> rank[5..18]
6182 // title[15..28] -> rank[5..18]
6183 // title[other] -> 0
6184 if (victim_title == 0)
6185 victim_guid = 0; // Don't show HK: <rank> message, only log.
6186 else if (victim_title < 15)
6187 victim_rank = victim_title + 4;
6188 else if (victim_title < 29)
6189 victim_rank = victim_title - 14 + 4;
6190 else
6191 victim_guid = 0; // Don't show HK: <rank> message, only log.
6194 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6196 if(v_level<=k_grey)
6197 return false;
6199 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6201 int32 v_rank =1; //need more info
6203 honor = ((f * diff_level * (190 + v_rank*10))/6);
6204 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6206 // count the number of playerkills in one day
6207 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6208 // and those in a lifetime
6209 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6210 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
6211 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
6212 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
6214 else
6216 Creature *cVictim = (Creature *)uVictim;
6218 if (!cVictim->isRacialLeader())
6219 return false;
6221 honor = 100; // ??? need more info
6222 victim_rank = 19; // HK: Leader
6226 if (uVictim != NULL)
6228 honor *= sWorld.getRate(RATE_HONOR);
6229 honor *= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN) + 100.0f)/100.0f;
6231 if(groupsize > 1)
6232 honor /= groupsize;
6234 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6237 // honor - for show honor points in log
6238 // victim_guid - for show victim name in log
6239 // victim_rank [1..4] HK: <dishonored rank>
6240 // victim_rank [5..19] HK: <alliance\horde rank>
6241 // victim_rank [0,20+] HK: <>
6242 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6243 data << (uint32) honor;
6244 data << (uint64) victim_guid;
6245 data << (uint32) victim_rank;
6247 GetSession()->SendPacket(&data);
6249 // add honor points
6250 ModifyHonorPoints(int32(honor));
6252 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6253 return true;
6256 void Player::ModifyHonorPoints( int32 value )
6258 if(value < 0)
6260 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6261 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6262 else
6263 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6265 else
6266 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6269 void Player::ModifyArenaPoints( int32 value )
6271 if(value < 0)
6273 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6274 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6275 else
6276 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6278 else
6279 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6282 uint32 Player::GetGuildIdFromDB(uint64 guid)
6284 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6285 if(!result)
6286 return 0;
6288 uint32 id = result->Fetch()[0].GetUInt32();
6289 delete result;
6290 return id;
6293 uint32 Player::GetRankFromDB(uint64 guid)
6295 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6296 if( result )
6298 uint32 v = result->Fetch()[0].GetUInt32();
6299 delete result;
6300 return v;
6302 else
6303 return 0;
6306 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6308 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);
6309 if(!result)
6310 return 0;
6312 uint32 id = (*result)[0].GetUInt32();
6313 delete result;
6314 return id;
6317 uint32 Player::GetZoneIdFromDB(uint64 guid)
6319 uint32 guidLow = GUID_LOPART(guid);
6320 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6321 if (!result)
6322 return 0;
6323 Field* fields = result->Fetch();
6324 uint32 zone = fields[0].GetUInt32();
6325 delete result;
6327 if (!zone)
6329 // stored zone is zero, use generic and slow zone detection
6330 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6331 if( !result )
6332 return 0;
6333 fields = result->Fetch();
6334 uint32 map = fields[0].GetUInt32();
6335 float posx = fields[1].GetFloat();
6336 float posy = fields[2].GetFloat();
6337 float posz = fields[3].GetFloat();
6338 delete result;
6340 zone = sMapMgr.GetZoneId(map,posx,posy,posz);
6342 if (zone > 0)
6343 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6346 return zone;
6349 uint32 Player::GetLevelFromDB(uint64 guid)
6351 QueryResult *result = CharacterDatabase.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid) );
6352 if (!result)
6353 return 0;
6355 Field* fields = result->Fetch();
6356 uint32 level = fields[0].GetUInt32();
6357 delete result;
6359 return level;
6362 void Player::UpdateArea(uint32 newArea)
6364 // FFA_PVP flags are area and not zone id dependent
6365 // so apply them accordingly
6366 m_areaUpdateId = newArea;
6368 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6370 if(area && (area->flags & AREA_FLAG_ARENA))
6372 if(!isGameMaster())
6373 SetFFAPvP(true);
6375 else
6377 // remove ffa flag only if not ffapvp realm
6378 // removal in sanctuaries and capitals is handled in zone update
6379 if(IsFFAPvP() && !sWorld.IsFFAPvPRealm())
6380 SetFFAPvP(false);
6383 UpdateAreaDependentAuras(newArea);
6386 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6388 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6389 if(!zone)
6390 return;
6392 if(m_zoneUpdateId != newZone)
6394 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6396 if (sWorld.getConfig(CONFIG_WEATHER))
6398 if(Weather *wth = sWorld.FindWeather(zone->ID))
6399 wth->SendWeatherUpdateToPlayer(this);
6400 else if(!sWorld.AddWeather(zone->ID))
6402 // send fine weather packet to remove old zone's weather
6403 Weather::SendFineWeatherUpdateToPlayer(this);
6408 m_zoneUpdateId = newZone;
6409 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6411 // zone changed, so area changed as well, update it
6412 UpdateArea(newArea);
6414 // in PvP, any not controlled zone (except zone->team == 6, default case)
6415 // in PvE, only opposition team capital
6416 switch(zone->team)
6418 case AREATEAM_ALLY:
6419 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6420 break;
6421 case AREATEAM_HORDE:
6422 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6423 break;
6424 case AREATEAM_NONE:
6425 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6426 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6427 break;
6428 default: // 6 in fact
6429 pvpInfo.inHostileArea = false;
6430 break;
6433 if(pvpInfo.inHostileArea) // in hostile area
6435 if(!IsPvP() || pvpInfo.endTimer != 0)
6436 UpdatePvP(true, true);
6438 else // in friendly area
6440 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6441 pvpInfo.endTimer = time(0); // start toggle-off
6444 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6446 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6447 if(sWorld.IsFFAPvPRealm())
6448 SetFFAPvP(false);
6450 else
6452 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6455 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6457 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6458 SetRestType(REST_TYPE_IN_CITY);
6459 InnEnter(time(0),GetMapId(),0,0,0);
6461 if(sWorld.IsFFAPvPRealm())
6462 SetFFAPvP(false);
6464 else // anywhere else
6466 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6468 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6470 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6472 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6473 SetRestType(REST_TYPE_NO);
6475 if(sWorld.IsFFAPvPRealm())
6476 SetFFAPvP(true);
6479 else // not in tavern (leave city then)
6481 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6482 SetRestType(REST_TYPE_NO);
6484 // Set player to FFA PVP when not in rested environment.
6485 if(sWorld.IsFFAPvPRealm())
6486 SetFFAPvP(true);
6491 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6492 // if player resurrected at teleport this will be applied in resurrect code
6493 if(isAlive())
6494 DestroyZoneLimitedItem( true, newZone );
6496 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6497 AutoUnequipOffhandIfNeed();
6499 // recent client version not send leave/join channel packets for built-in local channels
6500 UpdateLocalChannels( newZone );
6502 // group update
6503 if(GetGroup())
6504 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6506 UpdateZoneDependentAuras(newZone);
6509 //If players are too far way of duel flag... then player loose the duel
6510 void Player::CheckDuelDistance(time_t currTime)
6512 if(!duel)
6513 return;
6515 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6516 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6517 if(!obj)
6518 return;
6520 if(duel->outOfBound == 0)
6522 if(!IsWithinDistInMap(obj, 50))
6524 duel->outOfBound = currTime;
6526 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6527 GetSession()->SendPacket(&data);
6530 else
6532 if(IsWithinDistInMap(obj, 40))
6534 duel->outOfBound = 0;
6536 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6537 GetSession()->SendPacket(&data);
6539 else if(currTime >= (duel->outOfBound+10))
6541 DuelComplete(DUEL_FLED);
6546 void Player::DuelComplete(DuelCompleteType type)
6548 // duel not requested
6549 if(!duel)
6550 return;
6552 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6553 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6554 GetSession()->SendPacket(&data);
6555 duel->opponent->GetSession()->SendPacket(&data);
6557 if(type != DUEL_INTERUPTED)
6559 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6560 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6561 data << duel->opponent->GetName();
6562 data << GetName();
6563 SendMessageToSet(&data,true);
6566 if (type == DUEL_WON)
6568 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6569 if (duel->opponent)
6570 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6573 //Remove Duel Flag object
6574 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6575 if(obj)
6576 duel->initiator->RemoveGameObject(obj,true);
6578 /* remove auras */
6579 std::vector<uint32> auras2remove;
6580 AuraMap const& vAuras = duel->opponent->GetAuras();
6581 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6583 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6584 auras2remove.push_back(i->second->GetId());
6587 for(size_t i=0; i<auras2remove.size(); ++i)
6588 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6590 auras2remove.clear();
6591 AuraMap const& auras = GetAuras();
6592 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6594 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6595 auras2remove.push_back(i->second->GetId());
6597 for(size_t i=0; i<auras2remove.size(); ++i)
6598 RemoveAurasDueToSpell(auras2remove[i]);
6600 // cleanup combo points
6601 if(GetComboTarget()==duel->opponent->GetGUID())
6602 ClearComboPoints();
6603 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6604 ClearComboPoints();
6606 if(duel->opponent->GetComboTarget()==GetGUID())
6607 duel->opponent->ClearComboPoints();
6608 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6609 duel->opponent->ClearComboPoints();
6611 //cleanups
6612 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6613 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6614 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6615 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6617 delete duel->opponent->duel;
6618 duel->opponent->duel = NULL;
6619 delete duel;
6620 duel = NULL;
6623 //---------------------------------------------------------//
6625 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6627 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6628 return;
6630 // not apply/remove mods for broken item
6631 if(item->IsBroken())
6632 return;
6634 ItemPrototype const *proto = item->GetProto();
6636 if(!proto)
6637 return;
6639 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6641 uint32 attacktype = Player::GetAttackBySlot(slot);
6642 if(attacktype < MAX_ATTACK)
6643 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6645 _ApplyItemBonuses(proto,slot,apply);
6647 if( slot==EQUIPMENT_SLOT_RANGED )
6648 _ApplyAmmoBonuses();
6650 ApplyItemEquipSpell(item,apply);
6651 ApplyEnchantment(item, apply);
6653 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6654 CorrectMetaGemEnchants(slot, apply);
6656 sLog.outDebug("_ApplyItemMods complete.");
6659 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
6661 if (slot >= INVENTORY_SLOT_BAG_END || !proto)
6662 return;
6664 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
6665 if (only_level_scale && !ssd)
6666 return;
6668 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6669 uint32 ssd_level = getLevel();
6670 if (ssd && ssd_level > ssd->MaxLevel)
6671 ssd_level = ssd->MaxLevel;
6673 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
6674 if (only_level_scale && !ssv)
6675 return;
6677 for (uint32 i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6679 uint32 statType = 0;
6680 int32 val = 0;
6681 // If set ScalingStatDistribution need get stats and values from it
6682 if (ssd && ssv)
6684 if (ssd->StatMod[i] < 0)
6685 continue;
6686 statType = ssd->StatMod[i];
6687 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6689 else
6691 if (i >= proto->StatsCount)
6692 continue;
6693 statType = proto->ItemStat[i].ItemStatType;
6694 val = proto->ItemStat[i].ItemStatValue;
6697 if(val == 0)
6698 continue;
6700 switch (statType)
6702 case ITEM_MOD_MANA:
6703 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6704 break;
6705 case ITEM_MOD_HEALTH: // modify HP
6706 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6707 break;
6708 case ITEM_MOD_AGILITY: // modify agility
6709 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6710 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6711 break;
6712 case ITEM_MOD_STRENGTH: //modify strength
6713 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6714 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6715 break;
6716 case ITEM_MOD_INTELLECT: //modify intellect
6717 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6718 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6719 break;
6720 case ITEM_MOD_SPIRIT: //modify spirit
6721 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6722 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6723 break;
6724 case ITEM_MOD_STAMINA: //modify stamina
6725 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6726 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6727 break;
6728 case ITEM_MOD_DEFENSE_SKILL_RATING:
6729 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6730 break;
6731 case ITEM_MOD_DODGE_RATING:
6732 ApplyRatingMod(CR_DODGE, int32(val), apply);
6733 break;
6734 case ITEM_MOD_PARRY_RATING:
6735 ApplyRatingMod(CR_PARRY, int32(val), apply);
6736 break;
6737 case ITEM_MOD_BLOCK_RATING:
6738 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6739 break;
6740 case ITEM_MOD_HIT_MELEE_RATING:
6741 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6742 break;
6743 case ITEM_MOD_HIT_RANGED_RATING:
6744 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6745 break;
6746 case ITEM_MOD_HIT_SPELL_RATING:
6747 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6748 break;
6749 case ITEM_MOD_CRIT_MELEE_RATING:
6750 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6751 break;
6752 case ITEM_MOD_CRIT_RANGED_RATING:
6753 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6754 break;
6755 case ITEM_MOD_CRIT_SPELL_RATING:
6756 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6757 break;
6758 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6759 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6760 break;
6761 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6762 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6763 break;
6764 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6765 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6766 break;
6767 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6768 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6769 break;
6770 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6771 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6772 break;
6773 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6774 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6775 break;
6776 case ITEM_MOD_HASTE_MELEE_RATING:
6777 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6778 break;
6779 case ITEM_MOD_HASTE_RANGED_RATING:
6780 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6781 break;
6782 case ITEM_MOD_HASTE_SPELL_RATING:
6783 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6784 break;
6785 case ITEM_MOD_HIT_RATING:
6786 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6787 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6788 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6789 break;
6790 case ITEM_MOD_CRIT_RATING:
6791 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6792 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6793 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6794 break;
6795 case ITEM_MOD_HIT_TAKEN_RATING:
6796 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6797 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6798 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6799 break;
6800 case ITEM_MOD_CRIT_TAKEN_RATING:
6801 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6802 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6803 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6804 break;
6805 case ITEM_MOD_RESILIENCE_RATING:
6806 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6807 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6808 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6809 break;
6810 case ITEM_MOD_HASTE_RATING:
6811 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6812 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6813 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6814 break;
6815 case ITEM_MOD_EXPERTISE_RATING:
6816 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6817 break;
6818 case ITEM_MOD_ATTACK_POWER:
6819 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6820 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6821 break;
6822 case ITEM_MOD_RANGED_ATTACK_POWER:
6823 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6824 break;
6825 case ITEM_MOD_MANA_REGENERATION:
6826 ApplyManaRegenBonus(int32(val), apply);
6827 break;
6828 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6829 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6830 break;
6831 case ITEM_MOD_SPELL_POWER:
6832 ApplySpellPowerBonus(int32(val), apply);
6833 break;
6834 // depricated item mods
6835 case ITEM_MOD_FERAL_ATTACK_POWER:
6836 case ITEM_MOD_SPELL_HEALING_DONE:
6837 case ITEM_MOD_SPELL_DAMAGE_DONE:
6838 break;
6842 // Apply Spell Power from ScalingStatValue if set
6843 if(ssv)
6845 if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
6846 ApplySpellPowerBonus(spellbonus, apply);
6849 // If set ScalingStatValue armor get it or use item armor
6850 uint32 armor = proto->Armor;
6851 if (ssv)
6853 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6854 armor = ssvarmor;
6856 // Add armor bonus from ArmorDamageModifier if > 0
6857 if (proto->ArmorDamageModifier > 0)
6858 armor += uint32(proto->ArmorDamageModifier);
6860 if (armor)
6861 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6863 if (proto->Block)
6864 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6866 if (proto->HolyRes)
6867 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6869 if (proto->FireRes)
6870 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6872 if (proto->NatureRes)
6873 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6875 if (proto->FrostRes)
6876 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6878 if (proto->ShadowRes)
6879 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6881 if (proto->ArcaneRes)
6882 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6884 WeaponAttackType attType = BASE_ATTACK;
6885 float damage = 0.0f;
6887 if( slot == EQUIPMENT_SLOT_RANGED && (
6888 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6889 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6891 attType = RANGED_ATTACK;
6893 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6895 attType = OFF_ATTACK;
6898 float minDamage = proto->Damage[0].DamageMin;
6899 float maxDamage = proto->Damage[0].DamageMax;
6900 int32 extraDPS = 0;
6901 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6902 if (ssv)
6904 if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue)))
6906 float average = extraDPS * proto->Delay / 1000.0f;
6907 minDamage = 0.7f * average;
6908 maxDamage = 1.3f * average;
6911 if (minDamage > 0 )
6913 damage = apply ? minDamage : BASE_MINDAMAGE;
6914 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6915 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6918 if (maxDamage > 0 )
6920 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6921 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6924 // Apply feral bonus from ScalingStatValue if set
6925 if (ssv)
6927 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6928 ApplyFeralAPBonus(feral_bonus, apply);
6930 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6931 if(getClass() == CLASS_DRUID)
6933 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6934 if (feral_bonus > 0)
6935 ApplyFeralAPBonus(feral_bonus, apply);
6938 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6939 return;
6941 if (proto->Delay)
6943 if(slot == EQUIPMENT_SLOT_RANGED)
6944 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6945 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6946 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6947 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6948 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6951 if(CanModifyStats() && (damage || proto->Delay))
6952 UpdateDamagePhysical(attType);
6955 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6957 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6958 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6959 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6961 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6962 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6963 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6965 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6966 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6967 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6970 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6972 // generic not weapon specific case processes in aura code
6973 if(aura->GetSpellProto()->EquippedItemClass == -1)
6974 return;
6976 BaseModGroup mod = BASEMOD_END;
6977 switch(attackType)
6979 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6980 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6981 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6982 default: return;
6985 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6987 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6991 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6993 // ignore spell mods for not wands
6994 Modifier const* modifier = aura->GetModifier();
6995 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6996 return;
6998 // generic not weapon specific case processes in aura code
6999 if(aura->GetSpellProto()->EquippedItemClass == -1)
7000 return;
7002 UnitMods unitMod = UNIT_MOD_END;
7003 switch(attackType)
7005 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
7006 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
7007 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
7008 default: return;
7011 UnitModifierType unitModType = TOTAL_VALUE;
7012 switch(modifier->m_auraname)
7014 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
7015 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
7016 default: return;
7019 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
7021 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
7025 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
7027 if(!item)
7028 return;
7030 ItemPrototype const *proto = item->GetProto();
7031 if(!proto)
7032 return;
7034 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7036 _Spell const& spellData = proto->Spells[i];
7038 // no spell
7039 if(!spellData.SpellId )
7040 continue;
7042 // wrong triggering type
7043 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
7044 continue;
7046 // check if it is valid spell
7047 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
7048 if(!spellproto)
7049 continue;
7051 ApplyEquipSpell(spellproto,item,apply,form_change);
7055 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
7057 if(apply)
7059 // Cannot be used in this stance/form
7060 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
7061 return;
7063 if(form_change) // check aura active state from other form
7065 bool found = false;
7066 for (int k=0; k < 3; ++k)
7068 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
7069 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
7071 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
7073 found = true;
7074 break;
7077 if(found)
7078 break;
7081 if(found) // and skip re-cast already active aura at form change
7082 return;
7085 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
7087 CastSpell(this,spellInfo,true,item);
7089 else
7091 if(form_change) // check aura compatibility
7093 // Cannot be used in this stance/form
7094 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
7095 return; // and remove only not compatible at form change
7098 if(item)
7099 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
7100 else
7101 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
7105 void Player::UpdateEquipSpellsAtFormChange()
7107 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7109 if(m_items[i] && !m_items[i]->IsBroken())
7111 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
7112 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
7116 // item set bonuses not dependent from item broken state
7117 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
7119 ItemSetEffect* eff = ItemSetEff[setindex];
7120 if(!eff)
7121 continue;
7123 for(uint32 y=0;y<8; ++y)
7125 SpellEntry const* spellInfo = eff->spells[y];
7126 if(!spellInfo)
7127 continue;
7129 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
7130 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
7135 void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
7137 Item *item = GetWeaponForAttack(attType, true, false);
7138 if(!item)
7139 return;
7141 ItemPrototype const *proto = item->GetProto();
7142 if(!proto)
7143 return;
7145 if (!Target || Target == this )
7146 return;
7148 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7150 _Spell const& spellData = proto->Spells[i];
7152 // no spell
7153 if(!spellData.SpellId )
7154 continue;
7156 // wrong triggering type
7157 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7158 continue;
7160 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7161 if(!spellInfo)
7163 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7164 continue;
7167 // not allow proc extra attack spell at extra attack
7168 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7169 return;
7171 float chance = (float)spellInfo->procChance;
7173 if(spellData.SpellPPMRate)
7175 uint32 WeaponSpeed = proto->Delay;
7176 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7178 else if(chance > 100.0f)
7180 chance = GetWeaponProcChance();
7183 if (roll_chance_f(chance))
7184 CastSpell(Target, spellInfo->Id, true, item);
7187 // item combat enchantments
7188 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7190 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7191 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7192 if(!pEnchant) continue;
7193 for (int s=0;s<3;s++)
7195 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7196 continue;
7198 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7199 if (!spellInfo)
7201 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7202 continue;
7205 // Use first rank to access spell item enchant procs
7206 float ppmRate = sSpellMgr.GetItemEnchantProcChance(spellInfo->Id);
7208 float chance = ppmRate
7209 ? GetPPMProcChance(proto->Delay, ppmRate)
7210 : pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7213 ApplySpellMod(spellInfo->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
7214 ApplySpellMod(spellInfo->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
7216 if (roll_chance_f(chance))
7218 if(IsPositiveSpell(pEnchant->spellid[s]))
7219 CastSpell(this, pEnchant->spellid[s], true, item);
7220 else
7221 CastSpell(Target, pEnchant->spellid[s], true, item);
7227 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7229 ItemPrototype const* proto = item->GetProto();
7230 // special learning case
7231 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7233 uint32 learn_spell_id = proto->Spells[0].SpellId;
7234 uint32 learning_spell_id = proto->Spells[1].SpellId;
7236 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7237 if(!spellInfo)
7239 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7240 SendEquipError(EQUIP_ERR_NONE,item,NULL);
7241 return;
7244 Spell *spell = new Spell(this, spellInfo, false);
7245 spell->m_CastItem = item;
7246 spell->m_cast_count = cast_count; //set count of casts
7247 spell->m_currentBasePoints[0] = learning_spell_id;
7248 spell->prepare(&targets);
7249 return;
7252 // use triggered flag only for items with many spell casts and for not first cast
7253 int count = 0;
7255 // item spells casted at use
7256 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7258 _Spell const& spellData = proto->Spells[i];
7260 // no spell
7261 if(!spellData.SpellId)
7262 continue;
7264 // wrong triggering type
7265 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7266 continue;
7268 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7269 if(!spellInfo)
7271 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7272 continue;
7275 Spell *spell = new Spell(this, spellInfo, (count > 0));
7276 spell->m_CastItem = item;
7277 spell->m_cast_count = cast_count; // set count of casts
7278 spell->m_glyphIndex = glyphIndex; // glyph index
7279 spell->prepare(&targets);
7281 ++count;
7284 // Item enchantments spells casted at use
7285 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7287 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7288 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7289 if(!pEnchant) continue;
7290 for (int s=0;s<3;s++)
7292 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7293 continue;
7295 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7296 if (!spellInfo)
7298 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7299 continue;
7302 Spell *spell = new Spell(this, spellInfo, (count > 0));
7303 spell->m_CastItem = item;
7304 spell->m_cast_count = cast_count; // set count of casts
7305 spell->m_glyphIndex = glyphIndex; // glyph index
7306 spell->prepare(&targets);
7308 ++count;
7313 void Player::_RemoveAllItemMods()
7315 sLog.outDebug("_RemoveAllItemMods start.");
7317 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7319 if(m_items[i])
7321 ItemPrototype const *proto = m_items[i]->GetProto();
7322 if(!proto)
7323 continue;
7325 // item set bonuses not dependent from item broken state
7326 if(proto->ItemSet)
7327 RemoveItemsSetItem(this,proto);
7329 if(m_items[i]->IsBroken())
7330 continue;
7332 ApplyItemEquipSpell(m_items[i],false);
7333 ApplyEnchantment(m_items[i], false);
7337 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7339 if(m_items[i])
7341 if(m_items[i]->IsBroken())
7342 continue;
7343 ItemPrototype const *proto = m_items[i]->GetProto();
7344 if(!proto)
7345 continue;
7347 uint32 attacktype = Player::GetAttackBySlot(i);
7348 if(attacktype < MAX_ATTACK)
7349 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7351 _ApplyItemBonuses(proto,i, false);
7353 if( i == EQUIPMENT_SLOT_RANGED )
7354 _ApplyAmmoBonuses();
7358 sLog.outDebug("_RemoveAllItemMods complete.");
7361 void Player::_ApplyAllItemMods()
7363 sLog.outDebug("_ApplyAllItemMods start.");
7365 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7367 if(m_items[i])
7369 if(m_items[i]->IsBroken())
7370 continue;
7372 ItemPrototype const *proto = m_items[i]->GetProto();
7373 if(!proto)
7374 continue;
7376 uint32 attacktype = Player::GetAttackBySlot(i);
7377 if(attacktype < MAX_ATTACK)
7378 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7380 _ApplyItemBonuses(proto,i, true);
7382 if( i == EQUIPMENT_SLOT_RANGED )
7383 _ApplyAmmoBonuses();
7387 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7389 if(m_items[i])
7391 ItemPrototype const *proto = m_items[i]->GetProto();
7392 if(!proto)
7393 continue;
7395 // item set bonuses not dependent from item broken state
7396 if(proto->ItemSet)
7397 AddItemsSetItem(this,m_items[i]);
7399 if(m_items[i]->IsBroken())
7400 continue;
7402 ApplyItemEquipSpell(m_items[i],true);
7403 ApplyEnchantment(m_items[i], true);
7407 sLog.outDebug("_ApplyAllItemMods complete.");
7410 void Player::_ApplyAllLevelScaleItemMods(bool apply)
7412 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7414 if(m_items[i])
7416 if(m_items[i]->IsBroken())
7417 continue;
7419 ItemPrototype const *proto = m_items[i]->GetProto();
7420 if(!proto)
7421 continue;
7423 _ApplyItemBonuses(proto,i, apply, true);
7428 void Player::_ApplyAmmoBonuses()
7430 // check ammo
7431 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7432 if(!ammo_id)
7433 return;
7435 float currentAmmoDPS;
7437 ItemPrototype const *ammo_proto = ObjectMgr::GetItemPrototype( ammo_id );
7438 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7439 currentAmmoDPS = 0.0f;
7440 else
7441 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7443 if(currentAmmoDPS == GetAmmoDPS())
7444 return;
7446 m_ammoDPS = currentAmmoDPS;
7448 if(CanModifyStats())
7449 UpdateDamagePhysical(RANGED_ATTACK);
7452 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7454 if(!ammo_proto)
7455 return false;
7457 // check ranged weapon
7458 Item *weapon = GetWeaponForAttack( RANGED_ATTACK, true, false );
7459 if (!weapon)
7460 return false;
7462 ItemPrototype const* weapon_proto = weapon->GetProto();
7463 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7464 return false;
7466 // check ammo ws. weapon compatibility
7467 switch(weapon_proto->SubClass)
7469 case ITEM_SUBCLASS_WEAPON_BOW:
7470 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7471 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7472 return false;
7473 break;
7474 case ITEM_SUBCLASS_WEAPON_GUN:
7475 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7476 return false;
7477 break;
7478 default:
7479 return false;
7482 return true;
7485 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7486 Called by remove insignia spell effect */
7487 void Player::RemovedInsignia(Player* looterPlr)
7489 if (!GetBattleGroundId())
7490 return;
7492 // If not released spirit, do it !
7493 if(m_deathTimer > 0)
7495 m_deathTimer = 0;
7496 BuildPlayerRepop();
7497 RepopAtGraveyard();
7500 Corpse *corpse = GetCorpse();
7501 if (!corpse)
7502 return;
7504 // We have to convert player corpse to bones, not to be able to resurrect there
7505 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7506 Corpse *bones = sObjectAccessor.ConvertCorpseForPlayer(GetGUID(),true);
7507 if (!bones)
7508 return;
7510 // Now we must make bones lootable, and send player loot
7511 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7513 // We store the level of our player in the gold field
7514 // We retrieve this information at Player::SendLoot()
7515 bones->loot.gold = getLevel();
7516 bones->lootRecipient = looterPlr;
7517 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7520 void Player::SendLootRelease( uint64 guid )
7522 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7523 data << uint64(guid) << uint8(1);
7524 SendDirectMessage( &data );
7527 void Player::SendLoot(uint64 guid, LootType loot_type)
7529 if (uint64 lguid = GetLootGUID())
7530 m_session->DoLootRelease(lguid);
7532 Loot *loot = 0;
7533 PermissionTypes permission = ALL_PERMISSION;
7535 sLog.outDebug("Player::SendLoot");
7536 if (IS_GAMEOBJECT_GUID(guid))
7538 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7539 GameObject *go = GetMap()->GetGameObject(guid);
7541 // not check distance for GO in case owned GO (fishing bobber case, for example)
7542 // And permit out of range GO with no owner in case fishing hole
7543 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7545 SendLootRelease(guid);
7546 return;
7549 loot = &go->loot;
7551 if (go->getLootState() == GO_READY)
7553 uint32 lootid = go->GetGOInfo()->GetLootId();
7554 if ((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S))
7555 if (BattleGround *bg = GetBattleGround())
7556 if (bg->GetTypeID() == BATTLEGROUND_AV)
7557 if (!(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(go->GetEntry(), GetTeam())))
7559 SendLootRelease(guid);
7560 return;
7563 if (lootid)
7565 sLog.outDebug(" if(lootid)");
7566 loot->clear();
7567 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7570 if (loot_type == LOOT_FISHING)
7571 go->getFishLoot(loot,this);
7573 go->SetLootState(GO_ACTIVATED);
7576 else if (IS_ITEM_GUID(guid))
7578 Item *item = GetItemByGuid( guid );
7580 if (!item)
7582 SendLootRelease(guid);
7583 return;
7586 loot = &item->loot;
7588 if (!item->m_lootGenerated)
7590 item->m_lootGenerated = true;
7591 loot->clear();
7593 switch(loot_type)
7595 case LOOT_DISENCHANTING:
7596 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7597 break;
7598 case LOOT_PROSPECTING:
7599 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7600 break;
7601 case LOOT_MILLING:
7602 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7603 break;
7604 default:
7605 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7606 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7607 break;
7611 else if (IS_CORPSE_GUID(guid)) // remove insignia
7613 Corpse *bones = GetMap()->GetCorpse(guid);
7615 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7617 SendLootRelease(guid);
7618 return;
7621 loot = &bones->loot;
7623 if (!bones->lootForBody)
7625 bones->lootForBody = true;
7626 uint32 pLevel = bones->loot.gold;
7627 bones->loot.clear();
7628 if (GetBattleGround()->GetTypeID() == BATTLEGROUND_AV)
7629 loot->FillLoot(0, LootTemplates_Creature, this, false);
7630 // It may need a better formula
7631 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7632 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7635 if (bones->lootRecipient != this)
7636 permission = NONE_PERMISSION;
7638 else
7640 Creature *creature = GetMap()->GetCreature(guid);
7642 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7643 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7645 SendLootRelease(guid);
7646 return;
7649 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7651 SendLootRelease(guid);
7652 return;
7655 loot = &creature->loot;
7657 if (loot_type == LOOT_PICKPOCKETING)
7659 if (!creature->lootForPickPocketed)
7661 creature->lootForPickPocketed = true;
7662 loot->clear();
7664 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7665 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7667 // Generate extra money for pick pocket loot
7668 const uint32 a = urand(0, creature->getLevel()/2);
7669 const uint32 b = urand(0, getLevel()/2);
7670 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7673 else
7675 // the player whose group may loot the corpse
7676 Player *recipient = creature->GetLootRecipient();
7677 if (!recipient)
7679 creature->SetLootRecipient(this);
7680 recipient = this;
7683 if (creature->lootForPickPocketed)
7685 creature->lootForPickPocketed = false;
7686 loot->clear();
7689 if (!creature->lootForBody)
7691 creature->lootForBody = true;
7692 loot->clear();
7694 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7695 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7697 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7699 if (Group* group = recipient->GetGroup())
7701 group->UpdateLooterGuid(creature,true);
7703 switch (group->GetLootMethod())
7705 case GROUP_LOOT:
7706 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7707 group->GroupLoot(recipient->GetGUID(), loot, creature);
7708 break;
7709 case NEED_BEFORE_GREED:
7710 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7711 break;
7712 case MASTER_LOOT:
7713 group->MasterLoot(recipient->GetGUID(), loot, creature);
7714 break;
7715 default:
7716 break;
7721 // possible only if creature->lootForBody && loot->empty() at spell cast check
7722 if (loot_type == LOOT_SKINNING)
7724 loot->clear();
7725 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7727 // set group rights only for loot_type != LOOT_SKINNING
7728 else
7730 if(Group* group = GetGroup())
7732 if (group == recipient->GetGroup())
7734 if (group->GetLootMethod() == FREE_FOR_ALL)
7735 permission = ALL_PERMISSION;
7736 else if (group->GetLooterGuid() == GetGUID())
7738 if (group->GetLootMethod() == MASTER_LOOT)
7739 permission = MASTER_PERMISSION;
7740 else
7741 permission = ALL_PERMISSION;
7743 else
7744 permission = GROUP_PERMISSION;
7746 else
7747 permission = NONE_PERMISSION;
7749 else if (recipient == this)
7750 permission = ALL_PERMISSION;
7751 else
7752 permission = NONE_PERMISSION;
7757 SetLootGUID(guid);
7759 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7760 switch(loot_type)
7762 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7763 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7764 default: break;
7767 // need know merged fishing/corpse loot type for achievements
7768 loot->loot_type = loot_type;
7770 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7772 data << uint64(guid);
7773 data << uint8(loot_type);
7774 data << LootView(*loot, this, permission);
7776 SendDirectMessage(&data);
7778 // add 'this' player as one of the players that are looting 'loot'
7779 if (permission != NONE_PERMISSION)
7780 loot->AddLooter(GetGUID());
7782 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7783 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7786 void Player::SendNotifyLootMoneyRemoved()
7788 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7789 GetSession()->SendPacket( &data );
7792 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7794 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7795 data << uint8(lootSlot);
7796 GetSession()->SendPacket( &data );
7799 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7801 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7802 data << Field;
7803 data << Value;
7804 GetSession()->SendPacket(&data);
7807 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7809 // data depends on zoneid/mapid...
7810 BattleGround* bg = GetBattleGround();
7811 uint16 NumberOfFields = 0;
7812 uint32 mapid = GetMapId();
7814 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7816 // may be exist better way to do this...
7817 switch(zoneid)
7819 case 0:
7820 case 1:
7821 case 4:
7822 case 8:
7823 case 10:
7824 case 11:
7825 case 12:
7826 case 36:
7827 case 38:
7828 case 40:
7829 case 41:
7830 case 51:
7831 case 267:
7832 case 1519:
7833 case 1537:
7834 case 2257:
7835 case 2918:
7836 NumberOfFields = 8;
7837 break;
7838 case 139:
7839 NumberOfFields = 41;
7840 break;
7841 case 1377:
7842 NumberOfFields = 15;
7843 break;
7844 case 2597:
7845 NumberOfFields = 83;
7846 break;
7847 case 3277:
7848 NumberOfFields = 16;
7849 break;
7850 case 3358:
7851 case 3820:
7852 NumberOfFields = 40;
7853 break;
7854 case 3483:
7855 NumberOfFields = 27;
7856 break;
7857 case 3518:
7858 NumberOfFields = 39;
7859 break;
7860 case 3519:
7861 NumberOfFields = 38;
7862 break;
7863 case 3521:
7864 NumberOfFields = 37;
7865 break;
7866 case 3698:
7867 case 3702:
7868 case 3968:
7869 NumberOfFields = 11;
7870 break;
7871 case 3703:
7872 NumberOfFields = 11;
7873 break;
7874 default:
7875 NumberOfFields = 12;
7876 break;
7879 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7880 data << uint32(mapid); // mapid
7881 data << uint32(zoneid); // zone id
7882 data << uint32(areaid); // area id, new 2.1.0
7883 data << uint16(NumberOfFields); // count of uint64 blocks
7884 data << uint32(0x8d8) << uint32(0x0); // 1
7885 data << uint32(0x8d7) << uint32(0x0); // 2
7886 data << uint32(0x8d6) << uint32(0x0); // 3
7887 data << uint32(0x8d5) << uint32(0x0); // 4
7888 data << uint32(0x8d4) << uint32(0x0); // 5
7889 data << uint32(0x8d3) << uint32(0x0); // 6
7890 // 7 1 - Arena season in progress, 0 - end of season
7891 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7892 // 8 Arena season id
7893 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7894 if(mapid == 530) // Outland
7896 data << uint32(0x9bf) << uint32(0x0); // 7
7897 data << uint32(0x9bd) << uint32(0xF); // 8
7898 data << uint32(0x9bb) << uint32(0xF); // 9
7900 switch(zoneid)
7902 case 1:
7903 case 11:
7904 case 12:
7905 case 38:
7906 case 40:
7907 case 51:
7908 case 1519:
7909 case 1537:
7910 case 2257:
7911 break;
7912 case 2597: // AV
7913 if (bg && bg->GetTypeID() == BATTLEGROUND_AV)
7914 bg->FillInitialWorldStates(data);
7915 else
7917 data << uint32(0x7ae) << uint32(0x1); // 7 snowfall n
7918 data << uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
7919 data << uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
7920 data << uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
7921 data << uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
7922 data << uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
7923 data << uint32(0x567) << uint32(0x1); // 13 frostwolfe c
7924 data << uint32(0x566) << uint32(0x1); // 14 frostwolfw c
7925 data << uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
7926 data << uint32(0x544) << uint32(0x0); // 16 ice grave a_a
7927 data << uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
7928 data << uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
7929 data << uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
7930 data << uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
7931 data << uint32(0x574) << uint32(0x0); // 21 1396 unk
7932 data << uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
7933 data << uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
7934 data << uint32(0x56f) << uint32(0x0); // 24 1391 unk
7935 data << uint32(0x56e) << uint32(0x0); // 25 iceblood a
7936 data << uint32(0x56d) << uint32(0x0); // 26 towerp a
7937 data << uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
7938 data << uint32(0x56b) << uint32(0x0); // 28 froswolfw a
7939 data << uint32(0x56a) << uint32(0x1); // 29 1386 unk
7940 data << uint32(0x569) << uint32(0x1); // 30 iceblood c
7941 data << uint32(0x568) << uint32(0x1); // 31 towerp c
7942 data << uint32(0x565) << uint32(0x0); // 32 stoneh tower a
7943 data << uint32(0x564) << uint32(0x0); // 33 icewing tower a
7944 data << uint32(0x563) << uint32(0x0); // 34 dunn a
7945 data << uint32(0x562) << uint32(0x0); // 35 duns a
7946 data << uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
7947 data << uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
7948 data << uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
7949 data << uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
7950 data << uint32(0x55d) << uint32(0x0); // 40 stone tower d
7951 data << uint32(0x3c6) << uint32(0x0); // 41 966 unk
7952 data << uint32(0x3c4) << uint32(0x0); // 42 964 unk
7953 data << uint32(0x3c2) << uint32(0x0); // 43 962 unk
7954 data << uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
7955 data << uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
7956 data << uint32(0x3b6) << uint32(0x0); // 46 950 unk
7957 data << uint32(0x55c) << uint32(0x0); // 47 icewing tower d
7958 data << uint32(0x55b) << uint32(0x0); // 48 dunn d
7959 data << uint32(0x55a) << uint32(0x0); // 49 duns d
7960 data << uint32(0x559) << uint32(0x0); // 50 1369 unk
7961 data << uint32(0x558) << uint32(0x0); // 51 iceblood d
7962 data << uint32(0x557) << uint32(0x0); // 52 towerp d
7963 data << uint32(0x556) << uint32(0x0); // 53 frostwolfe d
7964 data << uint32(0x555) << uint32(0x0); // 54 frostwolfw d
7965 data << uint32(0x554) << uint32(0x1); // 55 stoneh tower c
7966 data << uint32(0x553) << uint32(0x1); // 56 icewing tower c
7967 data << uint32(0x552) << uint32(0x1); // 57 dunn c
7968 data << uint32(0x551) << uint32(0x1); // 58 duns c
7969 data << uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
7970 data << uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
7971 data << uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
7972 data << uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
7973 data << uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
7974 data << uint32(0x545) << uint32(0x0); // 64 iceblood h_a
7975 data << uint32(0x543) << uint32(0x1); // 65 iceblod h_c
7976 data << uint32(0x542) << uint32(0x0); // 66 iceblood a_c
7977 data << uint32(0x540) << uint32(0x0); // 67 snowfall h_a
7978 data << uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
7979 data << uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
7980 data << uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
7981 data << uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
7982 data << uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
7983 data << uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
7984 data << uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
7985 data << uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
7986 data << uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
7987 data << uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
7988 data << uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
7989 data << uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
7990 data << uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
7991 data << uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
7993 break;
7994 case 3277: // WS
7995 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7996 bg->FillInitialWorldStates(data);
7997 else
7999 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
8000 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
8001 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
8002 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
8003 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
8004 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
8005 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8006 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8008 break;
8009 case 3358: // AB
8010 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
8011 bg->FillInitialWorldStates(data);
8012 else
8014 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
8015 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
8016 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
8017 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
8018 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
8019 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
8020 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
8021 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
8022 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
8023 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
8024 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
8025 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
8026 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
8027 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
8028 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
8029 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
8030 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
8031 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
8032 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
8033 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
8034 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
8035 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
8036 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
8037 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
8038 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
8039 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
8040 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
8041 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
8042 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
8043 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
8044 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
8045 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
8047 break;
8048 case 3820: // EY
8049 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
8050 bg->FillInitialWorldStates(data);
8051 else
8053 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
8054 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
8055 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
8056 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
8057 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
8058 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
8059 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
8060 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
8061 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
8062 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
8063 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
8064 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
8065 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
8066 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
8067 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
8068 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
8069 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
8070 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
8071 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
8072 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
8073 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
8074 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
8075 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
8076 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
8077 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
8078 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
8079 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
8080 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
8081 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
8082 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
8083 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
8084 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
8085 // and some more ... unknown
8087 break;
8088 case 3483: // Hellfire Peninsula
8089 data << uint32(0x9ba) << uint32(0x1); // 10
8090 data << uint32(0x9b9) << uint32(0x1); // 11
8091 data << uint32(0x9b5) << uint32(0x0); // 12
8092 data << uint32(0x9b4) << uint32(0x1); // 13
8093 data << uint32(0x9b3) << uint32(0x0); // 14
8094 data << uint32(0x9b2) << uint32(0x0); // 15
8095 data << uint32(0x9b1) << uint32(0x1); // 16
8096 data << uint32(0x9b0) << uint32(0x0); // 17
8097 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
8098 data << uint32(0x9ac) << uint32(0x0); // 19
8099 data << uint32(0x9a8) << uint32(0x0); // 20
8100 data << uint32(0x9a7) << uint32(0x0); // 21
8101 data << uint32(0x9a6) << uint32(0x1); // 22
8102 break;
8103 case 3519: // Terokkar Forest
8104 data << uint32(0xa41) << uint32(0x0); // 10
8105 data << uint32(0xa40) << uint32(0x14); // 11
8106 data << uint32(0xa3f) << uint32(0x0); // 12
8107 data << uint32(0xa3e) << uint32(0x0); // 13
8108 data << uint32(0xa3d) << uint32(0x5); // 14
8109 data << uint32(0xa3c) << uint32(0x0); // 15
8110 data << uint32(0xa87) << uint32(0x0); // 16
8111 data << uint32(0xa86) << uint32(0x0); // 17
8112 data << uint32(0xa85) << uint32(0x0); // 18
8113 data << uint32(0xa84) << uint32(0x0); // 19
8114 data << uint32(0xa83) << uint32(0x0); // 20
8115 data << uint32(0xa82) << uint32(0x0); // 21
8116 data << uint32(0xa81) << uint32(0x0); // 22
8117 data << uint32(0xa80) << uint32(0x0); // 23
8118 data << uint32(0xa7e) << uint32(0x0); // 24
8119 data << uint32(0xa7d) << uint32(0x0); // 25
8120 data << uint32(0xa7c) << uint32(0x0); // 26
8121 data << uint32(0xa7b) << uint32(0x0); // 27
8122 data << uint32(0xa7a) << uint32(0x0); // 28
8123 data << uint32(0xa79) << uint32(0x0); // 29
8124 data << uint32(0x9d0) << uint32(0x5); // 30
8125 data << uint32(0x9ce) << uint32(0x0); // 31
8126 data << uint32(0x9cd) << uint32(0x0); // 32
8127 data << uint32(0x9cc) << uint32(0x0); // 33
8128 data << uint32(0xa88) << uint32(0x0); // 34
8129 data << uint32(0xad0) << uint32(0x0); // 35
8130 data << uint32(0xacf) << uint32(0x1); // 36
8131 break;
8132 case 3521: // Zangarmarsh
8133 data << uint32(0x9e1) << uint32(0x0); // 10
8134 data << uint32(0x9e0) << uint32(0x0); // 11
8135 data << uint32(0x9df) << uint32(0x0); // 12
8136 data << uint32(0xa5d) << uint32(0x1); // 13
8137 data << uint32(0xa5c) << uint32(0x0); // 14
8138 data << uint32(0xa5b) << uint32(0x1); // 15
8139 data << uint32(0xa5a) << uint32(0x0); // 16
8140 data << uint32(0xa59) << uint32(0x1); // 17
8141 data << uint32(0xa58) << uint32(0x0); // 18
8142 data << uint32(0xa57) << uint32(0x0); // 19
8143 data << uint32(0xa56) << uint32(0x0); // 20
8144 data << uint32(0xa55) << uint32(0x1); // 21
8145 data << uint32(0xa54) << uint32(0x0); // 22
8146 data << uint32(0x9e7) << uint32(0x0); // 23
8147 data << uint32(0x9e6) << uint32(0x0); // 24
8148 data << uint32(0x9e5) << uint32(0x0); // 25
8149 data << uint32(0xa00) << uint32(0x0); // 26
8150 data << uint32(0x9ff) << uint32(0x1); // 27
8151 data << uint32(0x9fe) << uint32(0x0); // 28
8152 data << uint32(0x9fd) << uint32(0x0); // 29
8153 data << uint32(0x9fc) << uint32(0x1); // 30
8154 data << uint32(0x9fb) << uint32(0x0); // 31
8155 data << uint32(0xa62) << uint32(0x0); // 32
8156 data << uint32(0xa61) << uint32(0x1); // 33
8157 data << uint32(0xa60) << uint32(0x1); // 34
8158 data << uint32(0xa5f) << uint32(0x0); // 35
8159 break;
8160 case 3698: // Nagrand Arena
8161 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
8162 bg->FillInitialWorldStates(data);
8163 else
8165 data << uint32(0xa0f) << uint32(0x0); // 7
8166 data << uint32(0xa10) << uint32(0x0); // 8
8167 data << uint32(0xa11) << uint32(0x0); // 9 show
8169 break;
8170 case 3702: // Blade's Edge Arena
8171 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8172 bg->FillInitialWorldStates(data);
8173 else
8175 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8176 data << uint32(0x9f1) << uint32(0x0); // 8 green
8177 data << uint32(0x9f3) << uint32(0x0); // 9 show
8179 break;
8180 case 3968: // Ruins of Lordaeron
8181 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8182 bg->FillInitialWorldStates(data);
8183 else
8185 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8186 data << uint32(0xbb9) << uint32(0x0); // 8 green
8187 data << uint32(0xbba) << uint32(0x0); // 9 show
8189 break;
8190 case 3703: // Shattrath City
8191 break;
8192 default:
8193 data << uint32(0x914) << uint32(0x0); // 7
8194 data << uint32(0x913) << uint32(0x0); // 8
8195 data << uint32(0x912) << uint32(0x0); // 9
8196 data << uint32(0x915) << uint32(0x0); // 10
8197 break;
8199 GetSession()->SendPacket(&data);
8202 uint32 Player::GetXPRestBonus(uint32 xp)
8204 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8206 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8207 rested_bonus = xp;
8209 SetRestBonus( GetRestBonus() - rested_bonus);
8211 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8212 return rested_bonus;
8215 void Player::SetBindPoint(uint64 guid)
8217 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8218 data << uint64(guid);
8219 GetSession()->SendPacket( &data );
8222 void Player::SendTalentWipeConfirm(uint64 guid)
8224 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8225 data << uint64(guid);
8226 data << uint32(resetTalentsCost());
8227 GetSession()->SendPacket( &data );
8230 void Player::SendPetSkillWipeConfirm()
8232 Pet* pet = GetPet();
8233 if(!pet)
8234 return;
8235 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8236 data << pet->GetGUID();
8237 data << uint32(pet->resetTalentsCost());
8238 GetSession()->SendPacket( &data );
8241 /*********************************************************/
8242 /*** STORAGE SYSTEM ***/
8243 /*********************************************************/
8245 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8247 assert(i < 3);
8248 if(i < 2 && item)
8250 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8251 return;
8252 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8253 if(charges == 0)
8254 return;
8255 if(charges > 1)
8256 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8257 else if(charges <= 1)
8259 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8260 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8265 void Player::SetSheath( SheathState sheathed )
8267 switch (sheathed)
8269 case SHEATH_STATE_UNARMED: // no prepared weapon
8270 SetVirtualItemSlot(0,NULL);
8271 SetVirtualItemSlot(1,NULL);
8272 SetVirtualItemSlot(2,NULL);
8273 break;
8274 case SHEATH_STATE_MELEE: // prepared melee weapon
8276 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true,true));
8277 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true,true));
8278 SetVirtualItemSlot(2,NULL);
8279 }; break;
8280 case SHEATH_STATE_RANGED: // prepared ranged weapon
8281 SetVirtualItemSlot(0,NULL);
8282 SetVirtualItemSlot(1,NULL);
8283 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true,true));
8284 break;
8285 default:
8286 SetVirtualItemSlot(0,NULL);
8287 SetVirtualItemSlot(1,NULL);
8288 SetVirtualItemSlot(2,NULL);
8289 break;
8291 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
8294 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8296 uint8 pClass = getClass();
8298 uint8 slots[4];
8299 slots[0] = NULL_SLOT;
8300 slots[1] = NULL_SLOT;
8301 slots[2] = NULL_SLOT;
8302 slots[3] = NULL_SLOT;
8303 switch( proto->InventoryType )
8305 case INVTYPE_HEAD:
8306 slots[0] = EQUIPMENT_SLOT_HEAD;
8307 break;
8308 case INVTYPE_NECK:
8309 slots[0] = EQUIPMENT_SLOT_NECK;
8310 break;
8311 case INVTYPE_SHOULDERS:
8312 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8313 break;
8314 case INVTYPE_BODY:
8315 slots[0] = EQUIPMENT_SLOT_BODY;
8316 break;
8317 case INVTYPE_CHEST:
8318 slots[0] = EQUIPMENT_SLOT_CHEST;
8319 break;
8320 case INVTYPE_ROBE:
8321 slots[0] = EQUIPMENT_SLOT_CHEST;
8322 break;
8323 case INVTYPE_WAIST:
8324 slots[0] = EQUIPMENT_SLOT_WAIST;
8325 break;
8326 case INVTYPE_LEGS:
8327 slots[0] = EQUIPMENT_SLOT_LEGS;
8328 break;
8329 case INVTYPE_FEET:
8330 slots[0] = EQUIPMENT_SLOT_FEET;
8331 break;
8332 case INVTYPE_WRISTS:
8333 slots[0] = EQUIPMENT_SLOT_WRISTS;
8334 break;
8335 case INVTYPE_HANDS:
8336 slots[0] = EQUIPMENT_SLOT_HANDS;
8337 break;
8338 case INVTYPE_FINGER:
8339 slots[0] = EQUIPMENT_SLOT_FINGER1;
8340 slots[1] = EQUIPMENT_SLOT_FINGER2;
8341 break;
8342 case INVTYPE_TRINKET:
8343 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8344 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8345 break;
8346 case INVTYPE_CLOAK:
8347 slots[0] = EQUIPMENT_SLOT_BACK;
8348 break;
8349 case INVTYPE_WEAPON:
8351 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8353 // suggest offhand slot only if know dual wielding
8354 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8355 if(CanDualWield())
8356 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8357 break;
8359 case INVTYPE_SHIELD:
8360 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8361 break;
8362 case INVTYPE_RANGED:
8363 slots[0] = EQUIPMENT_SLOT_RANGED;
8364 break;
8365 case INVTYPE_2HWEAPON:
8366 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8367 if (CanDualWield() && CanTitanGrip())
8368 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8369 break;
8370 case INVTYPE_TABARD:
8371 slots[0] = EQUIPMENT_SLOT_TABARD;
8372 break;
8373 case INVTYPE_WEAPONMAINHAND:
8374 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8375 break;
8376 case INVTYPE_WEAPONOFFHAND:
8377 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8378 break;
8379 case INVTYPE_HOLDABLE:
8380 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8381 break;
8382 case INVTYPE_THROWN:
8383 slots[0] = EQUIPMENT_SLOT_RANGED;
8384 break;
8385 case INVTYPE_RANGEDRIGHT:
8386 slots[0] = EQUIPMENT_SLOT_RANGED;
8387 break;
8388 case INVTYPE_BAG:
8389 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8390 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8391 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8392 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8393 break;
8394 case INVTYPE_RELIC:
8396 switch(proto->SubClass)
8398 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8399 if (pClass == CLASS_PALADIN)
8400 slots[0] = EQUIPMENT_SLOT_RANGED;
8401 break;
8402 case ITEM_SUBCLASS_ARMOR_IDOL:
8403 if (pClass == CLASS_DRUID)
8404 slots[0] = EQUIPMENT_SLOT_RANGED;
8405 break;
8406 case ITEM_SUBCLASS_ARMOR_TOTEM:
8407 if (pClass == CLASS_SHAMAN)
8408 slots[0] = EQUIPMENT_SLOT_RANGED;
8409 break;
8410 case ITEM_SUBCLASS_ARMOR_MISC:
8411 if (pClass == CLASS_WARLOCK)
8412 slots[0] = EQUIPMENT_SLOT_RANGED;
8413 break;
8414 case ITEM_SUBCLASS_ARMOR_SIGIL:
8415 if (pClass == CLASS_DEATH_KNIGHT)
8416 slots[0] = EQUIPMENT_SLOT_RANGED;
8417 break;
8419 break;
8421 default :
8422 return NULL_SLOT;
8425 if( slot != NULL_SLOT )
8427 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8429 for (int i = 0; i < 4; ++i)
8431 if ( slots[i] == slot )
8432 return slot;
8436 else
8438 // search free slot at first
8439 for (int i = 0; i < 4; ++i)
8441 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8443 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8444 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8445 return slots[i];
8449 // if not found free and can swap return first appropriate from used
8450 for (int i = 0; i < 4; ++i)
8452 if ( slots[i] != NULL_SLOT && swap )
8453 return slots[i];
8457 // no free position
8458 return NULL_SLOT;
8461 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8463 Item *pItem;
8464 uint32 tempcount = 0;
8466 uint8 res = EQUIP_ERR_OK;
8468 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8470 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8471 if( pItem && pItem->GetEntry() == item )
8473 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8474 if(ires==EQUIP_ERR_OK)
8476 tempcount += pItem->GetCount();
8477 if( tempcount >= count )
8478 return EQUIP_ERR_OK;
8480 else
8481 res = ires;
8484 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8486 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8487 if( pItem && pItem->GetEntry() == item )
8489 tempcount += pItem->GetCount();
8490 if( tempcount >= count )
8491 return EQUIP_ERR_OK;
8494 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8496 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8497 if( pItem && pItem->GetEntry() == item )
8499 tempcount += pItem->GetCount();
8500 if( tempcount >= count )
8501 return EQUIP_ERR_OK;
8504 Bag *pBag;
8505 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8507 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8508 if( pBag )
8510 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8512 pItem = GetItemByPos( i, j );
8513 if( pItem && pItem->GetEntry() == item )
8515 tempcount += pItem->GetCount();
8516 if( tempcount >= count )
8517 return EQUIP_ERR_OK;
8523 // not found req. item count and have unequippable items
8524 return res;
8527 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8529 uint32 count = 0;
8530 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8532 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8533 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8534 count += pItem->GetCount();
8536 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8538 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8539 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8540 count += pItem->GetCount();
8542 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8544 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8545 if( pBag )
8546 count += pBag->GetItemCount(item,skipItem);
8549 if(skipItem && skipItem->GetProto()->GemProperties)
8551 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8553 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8554 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8555 count += pItem->GetGemCountWithID(item);
8559 if(inBankAlso)
8561 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8563 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8564 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8565 count += pItem->GetCount();
8567 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8569 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8570 if( pBag )
8571 count += pBag->GetItemCount(item,skipItem);
8574 if(skipItem && skipItem->GetProto()->GemProperties)
8576 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8578 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8579 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8580 count += pItem->GetGemCountWithID(item);
8585 return count;
8588 Item* Player::GetItemByGuid( uint64 guid ) const
8590 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8592 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8593 if( pItem && pItem->GetGUID() == guid )
8594 return pItem;
8596 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8598 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8599 if( pItem && pItem->GetGUID() == guid )
8600 return pItem;
8603 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8605 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8606 if( pBag )
8608 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8610 Item* pItem = pBag->GetItemByPos( j );
8611 if( pItem && pItem->GetGUID() == guid )
8612 return pItem;
8616 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8618 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8619 if( pBag )
8621 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8623 Item* pItem = pBag->GetItemByPos( j );
8624 if( pItem && pItem->GetGUID() == guid )
8625 return pItem;
8630 return NULL;
8633 Item* Player::GetItemByPos( uint16 pos ) const
8635 uint8 bag = pos >> 8;
8636 uint8 slot = pos & 255;
8637 return GetItemByPos( bag, slot );
8640 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8642 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END )) )
8643 return m_items[slot];
8644 else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8645 || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END) )
8647 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8648 if ( pBag )
8649 return pBag->GetItemByPos(slot);
8651 return NULL;
8654 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool nonbroken, bool useable) const
8656 uint8 slot;
8657 switch (attackType)
8659 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8660 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8661 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8662 default: return NULL;
8665 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8666 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8667 return NULL;
8669 if (useable && !IsUseEquipedWeapon(attackType==BASE_ATTACK))
8670 return NULL;
8672 if (nonbroken && item->IsBroken())
8673 return NULL;
8675 return item;
8678 Item* Player::GetShield(bool useable) const
8680 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8681 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8682 return NULL;
8684 if(!useable)
8685 return item;
8687 if( item->IsBroken())
8688 return NULL;
8690 return item;
8693 uint32 Player::GetAttackBySlot( uint8 slot )
8695 switch(slot)
8697 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8698 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8699 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8700 default: return MAX_ATTACK;
8704 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8706 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8707 return true;
8708 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8709 return true;
8710 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8711 return true;
8712 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8713 return true;
8714 return false;
8717 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8719 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8720 return true;
8721 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8722 return true;
8723 return false;
8726 bool Player::IsBankPos( uint8 bag, uint8 slot )
8728 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8729 return true;
8730 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8731 return true;
8732 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8733 return true;
8734 return false;
8737 bool Player::IsBagPos( uint16 pos )
8739 uint8 bag = pos >> 8;
8740 uint8 slot = pos & 255;
8741 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8742 return true;
8743 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8744 return true;
8745 return false;
8748 bool Player::IsValidPos( uint8 bag, uint8 slot, bool explicit_pos )
8750 // post selected
8751 if(bag == NULL_BAG && !explicit_pos)
8752 return true;
8754 if (bag == INVENTORY_SLOT_BAG_0)
8756 // any post selected
8757 if (slot == NULL_SLOT && !explicit_pos)
8758 return true;
8760 // equipment
8761 if (slot < EQUIPMENT_SLOT_END)
8762 return true;
8764 // bag equip slots
8765 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8766 return true;
8768 // backpack slots
8769 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8770 return true;
8772 // keyring slots
8773 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8774 return true;
8776 // bank main slots
8777 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8778 return true;
8780 // bank bag slots
8781 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8782 return true;
8784 return false;
8787 // bag content slots
8788 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8790 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8791 if(!pBag)
8792 return false;
8794 // any post selected
8795 if (slot == NULL_SLOT && !explicit_pos)
8796 return true;
8798 return slot < pBag->GetBagSize();
8801 // bank bag content slots
8802 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8804 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8805 if(!pBag)
8806 return false;
8808 // any post selected
8809 if (slot == NULL_SLOT && !explicit_pos)
8810 return true;
8812 return slot < pBag->GetBagSize();
8815 // where this?
8816 return false;
8820 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8822 uint32 tempcount = 0;
8823 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8825 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8826 if( pItem && pItem->GetEntry() == item )
8828 tempcount += pItem->GetCount();
8829 if( tempcount >= count )
8830 return true;
8833 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8835 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8836 if( pItem && pItem->GetEntry() == item )
8838 tempcount += pItem->GetCount();
8839 if( tempcount >= count )
8840 return true;
8843 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8845 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8847 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8849 Item* pItem = GetItemByPos( i, j );
8850 if( pItem && pItem->GetEntry() == item )
8852 tempcount += pItem->GetCount();
8853 if( tempcount >= count )
8854 return true;
8860 if(inBankAlso)
8862 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8864 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8865 if( pItem && pItem->GetEntry() == item )
8867 tempcount += pItem->GetCount();
8868 if( tempcount >= count )
8869 return true;
8872 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8874 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8876 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8878 Item* pItem = GetItemByPos( i, j );
8879 if( pItem && pItem->GetEntry() == item )
8881 tempcount += pItem->GetCount();
8882 if( tempcount >= count )
8883 return true;
8890 return false;
8893 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8895 uint32 tempcount = 0;
8896 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8898 if(i==int(except_slot))
8899 continue;
8901 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8902 if( pItem && pItem->GetEntry() == item)
8904 tempcount += pItem->GetCount();
8905 if( tempcount >= count )
8906 return true;
8910 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item);
8911 if (pProto && pProto->GemProperties)
8913 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8915 if(i==int(except_slot))
8916 continue;
8918 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8919 if( pItem && pItem->GetProto()->Socket[0].Color)
8921 tempcount += pItem->GetGemCountWithID(item);
8922 if( tempcount >= count )
8923 return true;
8928 return false;
8931 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8933 uint32 tempcount = 0;
8934 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8936 if(i==int(except_slot))
8937 continue;
8939 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8940 if (!pItem)
8941 continue;
8943 ItemPrototype const *pProto = pItem->GetProto();
8944 if (!pProto)
8945 continue;
8947 if (pProto->ItemLimitCategory == limitCategory)
8949 tempcount += pItem->GetCount();
8950 if( tempcount >= count )
8951 return true;
8954 if( pProto->Socket[0].Color)
8956 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8957 if( tempcount >= count )
8958 return true;
8962 return false;
8965 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8967 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
8968 if( !pProto )
8970 if(no_space_count)
8971 *no_space_count = count;
8972 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8975 // no maximum
8976 if(pProto->MaxCount <= 0)
8977 return EQUIP_ERR_OK;
8979 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8981 if (curcount + count > uint32(pProto->MaxCount))
8983 if(no_space_count)
8984 *no_space_count = count +curcount - pProto->MaxCount;
8985 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8988 return EQUIP_ERR_OK;
8991 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8993 Item *pItem;
8994 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8996 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8997 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8998 return true;
9000 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9002 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9003 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
9004 return true;
9006 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9008 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9010 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9012 pItem = GetItemByPos( i, j );
9013 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
9014 return true;
9018 return false;
9021 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
9023 Item* pItem2 = GetItemByPos( bag, slot );
9025 // ignore move item (this slot will be empty at move)
9026 if (pItem2==pSrcItem)
9027 pItem2 = NULL;
9029 uint32 need_space;
9031 // empty specific slot - check item fit to slot
9032 if (!pItem2 || swap)
9034 if (bag == INVENTORY_SLOT_BAG_0)
9036 // keyring case
9037 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
9038 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9040 // currencytoken case
9041 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
9042 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9044 // prevent cheating
9045 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
9046 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9048 else
9050 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9051 if (!pBag)
9052 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9054 ItemPrototype const* pBagProto = pBag->GetProto();
9055 if (!pBagProto)
9056 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9058 if (slot >= pBagProto->ContainerSlots)
9059 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9061 if (!ItemCanGoIntoBag(pProto,pBagProto))
9062 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9065 // non empty stack with space
9066 need_space = pProto->GetMaxStackSize();
9068 // non empty slot, check item type
9069 else
9071 // can be merged at least partly
9072 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9073 if (res != EQUIP_ERR_OK)
9074 return res;
9076 // free stack space or infinity
9077 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9080 if (need_space > count)
9081 need_space = count;
9083 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
9084 if (!newPosition.isContainedIn(dest))
9086 dest.push_back(newPosition);
9087 count -= need_space;
9089 return EQUIP_ERR_OK;
9092 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
9094 // skip specific bag already processed in first called _CanStoreItem_InBag
9095 if (bag==skip_bag)
9096 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9098 // skip not existed bag or self targeted bag
9099 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9100 if (!pBag || pBag==pSrcItem)
9101 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9103 ItemPrototype const* pBagProto = pBag->GetProto();
9104 if (!pBagProto)
9105 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9107 // specialized bag mode or non-specilized
9108 if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
9109 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9111 if (!ItemCanGoIntoBag(pProto,pBagProto))
9112 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9114 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9116 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9117 if (j==skip_slot)
9118 continue;
9120 Item* pItem2 = GetItemByPos( bag, j );
9122 // ignore move item (this slot will be empty at move)
9123 if (pItem2 == pSrcItem)
9124 pItem2 = NULL;
9126 // if merge skip empty, if !merge skip non-empty
9127 if ((pItem2 != NULL) != merge)
9128 continue;
9130 uint32 need_space = pProto->GetMaxStackSize();
9132 if (pItem2)
9134 // can be merged at least partly
9135 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9136 if (res != EQUIP_ERR_OK)
9137 continue;
9139 // descrease at current stacksize
9140 need_space -= pItem2->GetCount();
9143 if (need_space > count)
9144 need_space = count;
9146 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9147 if (!newPosition.isContainedIn(dest))
9149 dest.push_back(newPosition);
9150 count -= need_space;
9152 if (count==0)
9153 return EQUIP_ERR_OK;
9156 return EQUIP_ERR_OK;
9159 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
9161 for(uint32 j = slot_begin; j < slot_end; ++j)
9163 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9164 if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
9165 continue;
9167 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
9169 // ignore move item (this slot will be empty at move)
9170 if (pItem2==pSrcItem)
9171 pItem2 = NULL;
9173 // if merge skip empty, if !merge skip non-empty
9174 if ((pItem2 != NULL) != merge)
9175 continue;
9177 uint32 need_space = pProto->GetMaxStackSize();
9179 if (pItem2)
9181 // can be merged at least partly
9182 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9183 if (res != EQUIP_ERR_OK)
9184 continue;
9186 // descrease at current stacksize
9187 need_space -= pItem2->GetCount();
9190 if (need_space > count)
9191 need_space = count;
9193 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9194 if (!newPosition.isContainedIn(dest))
9196 dest.push_back(newPosition);
9197 count -= need_space;
9199 if (count==0)
9200 return EQUIP_ERR_OK;
9203 return EQUIP_ERR_OK;
9206 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9208 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9210 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
9211 if (!pProto)
9213 if (no_space_count)
9214 *no_space_count = count;
9215 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9218 if (pItem)
9220 // item used
9221 if(pItem->m_lootGenerated)
9223 if (no_space_count)
9224 *no_space_count = count;
9225 return EQUIP_ERR_ALREADY_LOOTED;
9228 if (pItem->IsBindedNotWith(this))
9230 if (no_space_count)
9231 *no_space_count = count;
9232 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9236 // check count of items (skip for auto move for same player from bank)
9237 uint32 no_similar_count = 0; // can't store this amount similar items
9238 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9239 if (res!=EQUIP_ERR_OK)
9241 if (count==no_similar_count)
9243 if (no_space_count)
9244 *no_space_count = no_similar_count;
9245 return res;
9247 count -= no_similar_count;
9250 // in specific slot
9251 if (bag != NULL_BAG && slot != NULL_SLOT)
9253 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9254 if (res!=EQUIP_ERR_OK)
9256 if (no_space_count)
9257 *no_space_count = count + no_similar_count;
9258 return res;
9261 if (count==0)
9263 if (no_similar_count==0)
9264 return EQUIP_ERR_OK;
9266 if (no_space_count)
9267 *no_space_count = count + no_similar_count;
9268 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9272 // not specific slot or have space for partly store only in specific slot
9274 // in specific bag
9275 if (bag != NULL_BAG)
9277 // search stack in bag for merge to
9278 if (pProto->Stackable != 1)
9280 if (bag == INVENTORY_SLOT_BAG_0) // inventory
9282 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9283 if (res!=EQUIP_ERR_OK)
9285 if (no_space_count)
9286 *no_space_count = count + no_similar_count;
9287 return res;
9290 if (count==0)
9292 if (no_similar_count==0)
9293 return EQUIP_ERR_OK;
9295 if (no_space_count)
9296 *no_space_count = count + no_similar_count;
9297 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9300 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9301 if (res!=EQUIP_ERR_OK)
9303 if (no_space_count)
9304 *no_space_count = count + no_similar_count;
9305 return res;
9308 if (count==0)
9310 if (no_similar_count==0)
9311 return EQUIP_ERR_OK;
9313 if (no_space_count)
9314 *no_space_count = count + no_similar_count;
9315 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9318 else // equipped bag
9320 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9321 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9322 if (res!=EQUIP_ERR_OK)
9323 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9325 if (res!=EQUIP_ERR_OK)
9327 if (no_space_count)
9328 *no_space_count = count + no_similar_count;
9329 return res;
9332 if (count==0)
9334 if (no_similar_count==0)
9335 return EQUIP_ERR_OK;
9337 if (no_space_count)
9338 *no_space_count = count + no_similar_count;
9339 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9344 // search free slot in bag for place to
9345 if(bag == INVENTORY_SLOT_BAG_0) // inventory
9347 // search free slot - keyring case
9348 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9350 uint32 keyringSize = GetMaxKeyringSize();
9351 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9352 if (res!=EQUIP_ERR_OK)
9354 if (no_space_count)
9355 *no_space_count = count + no_similar_count;
9356 return res;
9359 if (count==0)
9361 if (no_similar_count==0)
9362 return EQUIP_ERR_OK;
9364 if (no_space_count)
9365 *no_space_count = count + no_similar_count;
9366 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9369 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9370 if (res!=EQUIP_ERR_OK)
9372 if (no_space_count)
9373 *no_space_count = count + no_similar_count;
9374 return res;
9377 if (count==0)
9379 if (no_similar_count==0)
9380 return EQUIP_ERR_OK;
9382 if (no_space_count)
9383 *no_space_count = count + no_similar_count;
9384 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9387 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9389 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9390 if (res!=EQUIP_ERR_OK)
9392 if (no_space_count)
9393 *no_space_count = count + no_similar_count;
9394 return res;
9397 if (count==0)
9399 if (no_similar_count==0)
9400 return EQUIP_ERR_OK;
9402 if (no_space_count)
9403 *no_space_count = count + no_similar_count;
9404 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9408 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,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 else // equipped bag
9428 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9429 if (res!=EQUIP_ERR_OK)
9430 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9432 if (res!=EQUIP_ERR_OK)
9434 if (no_space_count)
9435 *no_space_count = count + no_similar_count;
9436 return res;
9439 if (count==0)
9441 if (no_similar_count==0)
9442 return EQUIP_ERR_OK;
9444 if (no_space_count)
9445 *no_space_count = count + no_similar_count;
9446 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9451 // not specific bag or have space for partly store only in specific bag
9453 // search stack for merge to
9454 if (pProto->Stackable != 1)
9456 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9457 if (res!=EQUIP_ERR_OK)
9459 if (no_space_count)
9460 *no_space_count = count + no_similar_count;
9461 return res;
9464 if (count==0)
9466 if (no_similar_count==0)
9467 return EQUIP_ERR_OK;
9469 if (no_space_count)
9470 *no_space_count = count + no_similar_count;
9471 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9474 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9475 if (res!=EQUIP_ERR_OK)
9477 if (no_space_count)
9478 *no_space_count = count + no_similar_count;
9479 return res;
9482 if (count==0)
9484 if (no_similar_count==0)
9485 return EQUIP_ERR_OK;
9487 if (no_space_count)
9488 *no_space_count = count + no_similar_count;
9489 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9492 if (pProto->BagFamily)
9494 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9496 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9497 if (res!=EQUIP_ERR_OK)
9498 continue;
9500 if (count==0)
9502 if (no_similar_count==0)
9503 return EQUIP_ERR_OK;
9505 if (no_space_count)
9506 *no_space_count = count + no_similar_count;
9507 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9512 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9514 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9515 if (res!=EQUIP_ERR_OK)
9516 continue;
9518 if (count==0)
9520 if (no_similar_count==0)
9521 return EQUIP_ERR_OK;
9523 if (no_space_count)
9524 *no_space_count = count + no_similar_count;
9525 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9530 // search free slot - special bag case
9531 if (pProto->BagFamily)
9533 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9535 uint32 keyringSize = GetMaxKeyringSize();
9536 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9537 if (res!=EQUIP_ERR_OK)
9539 if (no_space_count)
9540 *no_space_count = count + no_similar_count;
9541 return res;
9544 if (count==0)
9546 if (no_similar_count==0)
9547 return EQUIP_ERR_OK;
9549 if (no_space_count)
9550 *no_space_count = count + no_similar_count;
9551 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9554 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9556 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9557 if (res!=EQUIP_ERR_OK)
9559 if (no_space_count)
9560 *no_space_count = count + no_similar_count;
9561 return res;
9564 if (count==0)
9566 if (no_similar_count==0)
9567 return EQUIP_ERR_OK;
9569 if (no_space_count)
9570 *no_space_count = count + no_similar_count;
9571 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9575 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9577 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9578 if (res!=EQUIP_ERR_OK)
9579 continue;
9581 if (count==0)
9583 if (no_similar_count==0)
9584 return EQUIP_ERR_OK;
9586 if (no_space_count)
9587 *no_space_count = count + no_similar_count;
9588 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9593 // search free slot
9594 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9595 if (res!=EQUIP_ERR_OK)
9597 if (no_space_count)
9598 *no_space_count = count + no_similar_count;
9599 return res;
9602 if (count==0)
9604 if (no_similar_count==0)
9605 return EQUIP_ERR_OK;
9607 if (no_space_count)
9608 *no_space_count = count + no_similar_count;
9609 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9612 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9614 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9615 if (res!=EQUIP_ERR_OK)
9616 continue;
9618 if (count==0)
9620 if (no_similar_count==0)
9621 return EQUIP_ERR_OK;
9623 if (no_space_count)
9624 *no_space_count = count + no_similar_count;
9625 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9629 if (no_space_count)
9630 *no_space_count = count + no_similar_count;
9632 return EQUIP_ERR_INVENTORY_FULL;
9635 //////////////////////////////////////////////////////////////////////////
9636 uint8 Player::CanStoreItems( Item **pItems,int count) const
9638 Item *pItem2;
9640 // fill space table
9641 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9642 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9643 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9644 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9646 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9647 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9648 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9649 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9651 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9653 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9655 if (pItem2 && !pItem2->IsInTrade())
9657 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9661 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9663 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9665 if (pItem2 && !pItem2->IsInTrade())
9667 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9671 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9673 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9675 if (pItem2 && !pItem2->IsInTrade())
9677 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9681 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9683 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9685 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9687 pItem2 = GetItemByPos( i, j );
9688 if (pItem2 && !pItem2->IsInTrade())
9690 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9696 // check free space for all items
9697 for (int k = 0; k < count; ++k)
9699 Item *pItem = pItems[k];
9701 // no item
9702 if (!pItem) continue;
9704 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9705 ItemPrototype const *pProto = pItem->GetProto();
9707 // strange item
9708 if( !pProto )
9709 return EQUIP_ERR_ITEM_NOT_FOUND;
9711 // item used
9712 if(pItem->m_lootGenerated)
9713 return EQUIP_ERR_ALREADY_LOOTED;
9715 // item it 'bind'
9716 if(pItem->IsBindedNotWith(this))
9717 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9719 Bag *pBag;
9720 ItemPrototype const *pBagProto;
9722 // item is 'one item only'
9723 uint8 res = CanTakeMoreSimilarItems(pItem);
9724 if(res != EQUIP_ERR_OK)
9725 return res;
9727 // search stack for merge to
9728 if( pProto->Stackable != 1 )
9730 bool b_found = false;
9732 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9734 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9735 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9737 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9738 b_found = true;
9739 break;
9742 if (b_found) continue;
9744 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9746 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9747 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9749 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9750 b_found = true;
9751 break;
9754 if (b_found) continue;
9756 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9758 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9759 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9761 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9762 b_found = true;
9763 break;
9766 if (b_found) continue;
9768 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9770 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9771 if( pBag )
9773 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9775 pItem2 = GetItemByPos( t, j );
9776 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9778 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9779 b_found = true;
9780 break;
9785 if (b_found) continue;
9788 // special bag case
9789 if( pProto->BagFamily )
9791 bool b_found = false;
9792 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9794 uint32 keyringSize = GetMaxKeyringSize();
9795 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9797 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9799 inv_keys[t-KEYRING_SLOT_START] = 1;
9800 b_found = true;
9801 break;
9806 if (b_found) continue;
9808 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9810 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9812 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9814 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9815 b_found = true;
9816 break;
9821 if (b_found) continue;
9823 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9825 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9826 if( pBag )
9828 pBagProto = pBag->GetProto();
9830 // not plain container check
9831 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9832 ItemCanGoIntoBag(pProto,pBagProto) )
9834 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9836 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9838 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9839 b_found = true;
9840 break;
9846 if (b_found) continue;
9849 // search free slot
9850 bool b_found = false;
9851 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9853 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9855 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9856 b_found = true;
9857 break;
9860 if (b_found) continue;
9862 // search free slot in bags
9863 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9865 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9866 if( pBag )
9868 pBagProto = pBag->GetProto();
9870 // special bag already checked
9871 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9872 continue;
9874 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9876 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9878 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9879 b_found = true;
9880 break;
9886 // no free slot found?
9887 if (!b_found)
9888 return EQUIP_ERR_INVENTORY_FULL;
9891 return EQUIP_ERR_OK;
9894 //////////////////////////////////////////////////////////////////////////
9895 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9897 dest = 0;
9898 Item *pItem = Item::CreateItem( item, 1, this );
9899 if( pItem )
9901 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9902 delete pItem;
9903 return result;
9906 return EQUIP_ERR_ITEM_NOT_FOUND;
9909 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9911 dest = 0;
9912 if( pItem )
9914 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9915 ItemPrototype const *pProto = pItem->GetProto();
9916 if( pProto )
9918 // item used
9919 if(pItem->m_lootGenerated)
9920 return EQUIP_ERR_ALREADY_LOOTED;
9922 if(pItem->IsBindedNotWith(this))
9923 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9925 // check count of items (skip for auto move for same player from bank)
9926 uint8 res = CanTakeMoreSimilarItems(pItem);
9927 if(res != EQUIP_ERR_OK)
9928 return res;
9930 // check this only in game
9931 if(not_loading)
9933 // May be here should be more stronger checks; STUNNED checked
9934 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9935 if (hasUnitState(UNIT_STAT_STUNNED))
9936 return EQUIP_ERR_YOU_ARE_STUNNED;
9938 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9939 // - combat
9940 // - in-progress arenas
9941 if( !pProto->CanChangeEquipStateInCombat() )
9943 if( isInCombat() )
9944 return EQUIP_ERR_NOT_IN_COMBAT;
9946 if(BattleGround* bg = GetBattleGround())
9947 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9948 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9951 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9952 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9954 if(IsNonMeleeSpellCasted(false))
9955 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9958 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
9959 // 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)
9960 if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
9961 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9963 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9964 if (eslot == NULL_SLOT)
9965 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9967 uint8 msg = CanUseItem(pItem , not_loading);
9968 if (msg != EQUIP_ERR_OK)
9969 return msg;
9970 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
9971 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9973 // if swap ignore item (equipped also)
9974 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9975 return res2;
9977 // check unique-equipped special item classes
9978 if (pProto->Class == ITEM_CLASS_QUIVER)
9980 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9982 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
9984 if (pBag != pItem)
9986 if (ItemPrototype const* pBagProto = pBag->GetProto())
9988 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
9989 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9990 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
9991 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9998 uint32 type = pProto->InventoryType;
10000 if (eslot == EQUIPMENT_SLOT_OFFHAND)
10002 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
10004 if (!CanDualWield())
10005 return EQUIP_ERR_CANT_DUAL_WIELD;
10007 else if (type == INVTYPE_2HWEAPON)
10009 if (!CanDualWield() || !CanTitanGrip())
10010 return EQUIP_ERR_CANT_DUAL_WIELD;
10013 if (IsTwoHandUsed())
10014 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
10017 // equip two-hand weapon case (with possible unequip 2 items)
10018 if (type == INVTYPE_2HWEAPON)
10020 if (eslot == EQUIPMENT_SLOT_OFFHAND)
10022 if (!CanTitanGrip())
10023 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10025 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
10026 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10028 if (!CanTitanGrip())
10030 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
10031 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
10032 ItemPosCountVec off_dest;
10033 if (offItem && (!not_loading ||
10034 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
10035 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
10036 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
10039 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
10040 return EQUIP_ERR_OK;
10044 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
10047 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
10049 // Applied only to equipped items and bank bags
10050 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
10051 return EQUIP_ERR_OK;
10053 Item* pItem = GetItemByPos(pos);
10055 // Applied only to existed equipped item
10056 if( !pItem )
10057 return EQUIP_ERR_OK;
10059 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
10061 ItemPrototype const *pProto = pItem->GetProto();
10062 if( !pProto )
10063 return EQUIP_ERR_ITEM_NOT_FOUND;
10065 // item used
10066 if(pItem->m_lootGenerated)
10067 return EQUIP_ERR_ALREADY_LOOTED;
10069 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10070 // - combat
10071 // - in-progress arenas
10072 if( !pProto->CanChangeEquipStateInCombat() )
10074 if( isInCombat() )
10075 return EQUIP_ERR_NOT_IN_COMBAT;
10077 if(BattleGround* bg = GetBattleGround())
10078 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
10079 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
10082 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
10083 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
10085 return EQUIP_ERR_OK;
10088 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
10090 if (!pItem)
10091 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10093 uint32 count = pItem->GetCount();
10095 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
10096 ItemPrototype const *pProto = pItem->GetProto();
10097 if (!pProto)
10098 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10100 // item used
10101 if(pItem->m_lootGenerated)
10102 return EQUIP_ERR_ALREADY_LOOTED;
10104 if (pItem->IsBindedNotWith(this))
10105 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10107 // check count of items (skip for auto move for same player from bank)
10108 uint8 res = CanTakeMoreSimilarItems(pItem);
10109 if (res != EQUIP_ERR_OK)
10110 return res;
10112 // in specific slot
10113 if (bag != NULL_BAG && slot != NULL_SLOT)
10115 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
10117 if (!pItem->IsBag())
10118 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
10120 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
10121 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
10123 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
10124 return cantuse;
10127 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
10128 if (res!=EQUIP_ERR_OK)
10129 return res;
10131 if (count==0)
10132 return EQUIP_ERR_OK;
10135 // not specific slot or have space for partly store only in specific slot
10137 // in specific bag
10138 if( bag != NULL_BAG )
10140 if( pProto->InventoryType == INVTYPE_BAG )
10142 Bag *pBag = (Bag*)pItem;
10143 if( pBag && !pBag->IsEmpty() )
10144 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
10147 // search stack in bag for merge to
10148 if( pProto->Stackable != 1 )
10150 if( bag == INVENTORY_SLOT_BAG_0 )
10152 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10153 if(res!=EQUIP_ERR_OK)
10154 return res;
10156 if(count==0)
10157 return EQUIP_ERR_OK;
10159 else
10161 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
10162 if(res!=EQUIP_ERR_OK)
10163 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
10165 if(res!=EQUIP_ERR_OK)
10166 return res;
10168 if(count==0)
10169 return EQUIP_ERR_OK;
10173 // search free slot in bag
10174 if( bag == INVENTORY_SLOT_BAG_0 )
10176 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10177 if(res!=EQUIP_ERR_OK)
10178 return res;
10180 if(count==0)
10181 return EQUIP_ERR_OK;
10183 else
10185 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
10186 if(res != EQUIP_ERR_OK)
10187 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
10189 if(res != EQUIP_ERR_OK)
10190 return res;
10192 if(count == 0)
10193 return EQUIP_ERR_OK;
10197 // not specific bag or have space for partly store only in specific bag
10199 // search stack for merge to
10200 if( pProto->Stackable != 1 )
10202 // in slots
10203 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10204 if(res != EQUIP_ERR_OK)
10205 return res;
10207 if(count == 0)
10208 return EQUIP_ERR_OK;
10210 // in special bags
10211 if( pProto->BagFamily )
10213 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10215 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10216 if(res!=EQUIP_ERR_OK)
10217 continue;
10219 if(count==0)
10220 return EQUIP_ERR_OK;
10224 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10226 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10227 if(res!=EQUIP_ERR_OK)
10228 continue;
10230 if(count==0)
10231 return EQUIP_ERR_OK;
10235 // search free place in special bag
10236 if( pProto->BagFamily )
10238 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10240 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10241 if(res!=EQUIP_ERR_OK)
10242 continue;
10244 if(count==0)
10245 return EQUIP_ERR_OK;
10249 // search free space
10250 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10251 if(res!=EQUIP_ERR_OK)
10252 return res;
10254 if(count==0)
10255 return EQUIP_ERR_OK;
10257 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10259 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10260 if(res!=EQUIP_ERR_OK)
10261 continue;
10263 if(count==0)
10264 return EQUIP_ERR_OK;
10266 return EQUIP_ERR_BANK_FULL;
10269 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10271 if (pItem)
10273 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10275 if (!isAlive() && not_loading)
10276 return EQUIP_ERR_YOU_ARE_DEAD;
10278 //if (isStunned())
10279 // return EQUIP_ERR_YOU_ARE_STUNNED;
10281 ItemPrototype const *pProto = pItem->GetProto();
10282 if (pProto)
10284 if (pItem->IsBindedNotWith(this))
10285 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10287 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
10288 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10290 if (uint32 item_use_skill = pItem->GetSkill())
10292 if (GetSkillValue(item_use_skill) == 0)
10294 // armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
10295 if (pProto->Class != ITEM_CLASS_ARMOR)
10296 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10298 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : NULL;
10299 if (!ssd)
10300 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10302 bool allowScaleSkill = false;
10303 for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i)
10305 SkillLineAbilityEntry const *skillInfo = sSkillLineAbilityStore.LookupEntry(i);
10306 if (!skillInfo)
10307 continue;
10309 if (skillInfo->skillId != item_use_skill)
10310 continue;
10312 // can't learn
10313 if (skillInfo->classmask && (skillInfo->classmask & getClassMask()) == 0)
10314 continue;
10316 if (skillInfo->racemask && (skillInfo->racemask & getRaceMask()) == 0)
10317 continue;
10319 allowScaleSkill = true;
10320 break;
10323 if (!allowScaleSkill)
10324 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10328 if (pProto->RequiredSkill != 0)
10330 if (GetSkillValue( pProto->RequiredSkill ) == 0)
10331 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10333 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
10334 return EQUIP_ERR_CANT_EQUIP_SKILL;
10337 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
10338 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10340 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
10341 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10343 if (getLevel() < pProto->RequiredLevel)
10344 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10346 return EQUIP_ERR_OK;
10349 return EQUIP_ERR_ITEM_NOT_FOUND;
10352 bool Player::CanUseItem( ItemPrototype const *pProto )
10354 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10356 if( pProto )
10358 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10359 return false;
10360 if( pProto->RequiredSkill != 0 )
10362 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10363 return false;
10364 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10365 return false;
10367 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10368 return false;
10369 if( getLevel() < pProto->RequiredLevel )
10370 return false;
10371 return true;
10373 return false;
10376 uint8 Player::CanUseAmmo( uint32 item ) const
10378 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10379 if( !isAlive() )
10380 return EQUIP_ERR_YOU_ARE_DEAD;
10381 //if( isStunned() )
10382 // return EQUIP_ERR_YOU_ARE_STUNNED;
10383 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
10384 if( pProto )
10386 if( pProto->InventoryType!= INVTYPE_AMMO )
10387 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10388 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10389 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10390 if( pProto->RequiredSkill != 0 )
10392 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10393 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10394 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10395 return EQUIP_ERR_CANT_EQUIP_SKILL;
10397 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10398 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10399 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10400 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10402 if( getLevel() < pProto->RequiredLevel )
10403 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10405 // Requires No Ammo
10406 if(GetDummyAura(46699))
10407 return EQUIP_ERR_BAG_FULL6;
10409 return EQUIP_ERR_OK;
10411 return EQUIP_ERR_ITEM_NOT_FOUND;
10414 void Player::SetAmmo( uint32 item )
10416 if(!item)
10417 return;
10419 // already set
10420 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10421 return;
10423 // check ammo
10424 if(item)
10426 uint8 msg = CanUseAmmo( item );
10427 if( msg != EQUIP_ERR_OK )
10429 SendEquipError( msg, NULL, NULL );
10430 return;
10434 SetUInt32Value(PLAYER_AMMO_ID, item);
10436 _ApplyAmmoBonuses();
10439 void Player::RemoveAmmo()
10441 SetUInt32Value(PLAYER_AMMO_ID, 0);
10443 m_ammoDPS = 0.0f;
10445 if(CanModifyStats())
10446 UpdateDamagePhysical(RANGED_ATTACK);
10449 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10450 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10452 uint32 count = 0;
10453 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10454 count += itr->count;
10456 Item *pItem = Item::CreateItem( item, count, this );
10457 if( pItem )
10459 ItemAddedQuestCheck( item, count );
10460 if(randomPropertyId)
10461 pItem->SetItemRandomProperties(randomPropertyId);
10462 pItem = StoreItem( dest, pItem, update );
10464 return pItem;
10467 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10469 if( !pItem )
10470 return NULL;
10472 Item* lastItem = pItem;
10473 uint32 entry = pItem->GetEntry();
10474 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10476 uint16 pos = itr->pos;
10477 uint32 count = itr->count;
10479 ++itr;
10481 if(itr == dest.end())
10483 lastItem = _StoreItem(pos,pItem,count,false,update);
10484 break;
10487 lastItem = _StoreItem(pos,pItem,count,true,update);
10489 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10490 return lastItem;
10493 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10494 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10496 if( !pItem )
10497 return NULL;
10499 uint8 bag = pos >> 8;
10500 uint8 slot = pos & 255;
10502 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10504 Item *pItem2 = GetItemByPos( bag, slot );
10506 if (!pItem2)
10508 if (clone)
10509 pItem = pItem->CloneItem(count, this);
10510 else
10511 pItem->SetCount(count);
10513 if (!pItem)
10514 return NULL;
10516 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10517 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10518 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10519 pItem->SetBinding( true );
10521 if (bag == INVENTORY_SLOT_BAG_0)
10523 m_items[slot] = pItem;
10524 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10525 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10526 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10528 pItem->SetSlot( slot );
10529 pItem->SetContainer( NULL );
10531 // need update known currency
10532 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10533 UpdateKnownCurrencies(pItem->GetEntry(), true);
10535 if (IsInWorld() && update)
10537 pItem->AddToWorld();
10538 pItem->SendCreateUpdateToPlayer( this );
10541 pItem->SetState(ITEM_CHANGED, this);
10543 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10545 pBag->StoreItem( slot, pItem, update );
10546 if( IsInWorld() && update )
10548 pItem->AddToWorld();
10549 pItem->SendCreateUpdateToPlayer( this );
10551 pItem->SetState(ITEM_CHANGED, this);
10552 pBag->SetState(ITEM_CHANGED, this);
10555 AddEnchantmentDurations(pItem);
10556 AddItemDurations(pItem);
10558 return pItem;
10560 else
10562 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10563 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10564 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10565 pItem2->SetBinding( true );
10567 pItem2->SetCount( pItem2->GetCount() + count );
10568 if (IsInWorld() && update)
10569 pItem2->SendCreateUpdateToPlayer( this );
10571 if (!clone)
10573 // delete item (it not in any slot currently)
10574 if (IsInWorld() && update)
10576 pItem->RemoveFromWorld();
10577 pItem->DestroyForPlayer( this );
10580 RemoveEnchantmentDurations(pItem);
10581 RemoveItemDurations(pItem);
10583 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10584 pItem->SetState(ITEM_REMOVED, this);
10587 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10588 AddEnchantmentDurations(pItem2);
10590 pItem2->SetState(ITEM_CHANGED, this);
10592 return pItem2;
10596 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10598 if (Item *pItem = Item::CreateItem( item, 1, this ))
10600 ItemAddedQuestCheck( item, 1 );
10601 return EquipItem( pos, pItem, update );
10604 return NULL;
10607 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10609 AddEnchantmentDurations(pItem);
10610 AddItemDurations(pItem);
10612 uint8 bag = pos >> 8;
10613 uint8 slot = pos & 255;
10615 Item *pItem2 = GetItemByPos( bag, slot );
10617 if( !pItem2 )
10619 VisualizeItem( slot, pItem);
10621 if(isAlive())
10623 ItemPrototype const *pProto = pItem->GetProto();
10625 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10626 if(pProto && pProto->ItemSet)
10627 AddItemsSetItem(this, pItem);
10629 _ApplyItemMods(pItem, slot, true);
10631 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10633 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10635 if (getClass() == CLASS_ROGUE)
10636 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10638 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10640 if (!spellProto)
10641 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10642 else
10644 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10646 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10647 data << uint64(GetGUID());
10648 data << uint8(1);
10649 data << uint32(cooldownSpell);
10650 data << uint32(0);
10651 GetSession()->SendPacket(&data);
10656 if( IsInWorld() && update )
10658 pItem->AddToWorld();
10659 pItem->SendCreateUpdateToPlayer( this );
10662 ApplyEquipCooldown(pItem);
10664 if( slot == EQUIPMENT_SLOT_MAINHAND )
10666 UpdateExpertise(BASE_ATTACK);
10667 UpdateArmorPenetration();
10669 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10671 UpdateExpertise(OFF_ATTACK);
10672 UpdateArmorPenetration();
10675 else
10677 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10678 if( IsInWorld() && update )
10679 pItem2->SendCreateUpdateToPlayer( this );
10681 // delete item (it not in any slot currently)
10682 //pItem->DeleteFromDB();
10683 if( IsInWorld() && update )
10685 pItem->RemoveFromWorld();
10686 pItem->DestroyForPlayer( this );
10689 RemoveEnchantmentDurations(pItem);
10690 RemoveItemDurations(pItem);
10692 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10693 pItem->SetState(ITEM_REMOVED, this);
10694 pItem2->SetState(ITEM_CHANGED, this);
10696 ApplyEquipCooldown(pItem2);
10698 return pItem2;
10701 // only for full equip instead adding to stack
10702 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10704 return pItem;
10707 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10709 if( pItem )
10711 AddEnchantmentDurations(pItem);
10712 AddItemDurations(pItem);
10714 uint8 slot = pos & 255;
10715 VisualizeItem( slot, pItem);
10717 if( IsInWorld() )
10719 pItem->AddToWorld();
10720 pItem->SendCreateUpdateToPlayer( this );
10723 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10727 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10729 if(pItem)
10731 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10732 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10733 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10735 else
10737 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10738 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10742 void Player::VisualizeItem( uint8 slot, Item *pItem)
10744 if(!pItem)
10745 return;
10747 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10748 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10749 pItem->SetBinding( true );
10751 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10753 m_items[slot] = pItem;
10754 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10755 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10756 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10757 pItem->SetSlot( slot );
10758 pItem->SetContainer( NULL );
10760 if( slot < EQUIPMENT_SLOT_END )
10761 SetVisibleItemSlot(slot, pItem);
10763 pItem->SetState(ITEM_CHANGED, this);
10766 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10768 // note: removeitem does not actually change the item
10769 // it only takes the item out of storage temporarily
10770 // note2: if removeitem is to be used for delinking
10771 // the item must be removed from the player's updatequeue
10773 Item *pItem = GetItemByPos( bag, slot );
10774 if( pItem )
10776 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10778 RemoveEnchantmentDurations(pItem);
10779 RemoveItemDurations(pItem);
10781 if( bag == INVENTORY_SLOT_BAG_0 )
10783 if ( slot < INVENTORY_SLOT_BAG_END )
10785 ItemPrototype const *pProto = pItem->GetProto();
10786 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10788 if(pProto && pProto->ItemSet)
10789 RemoveItemsSetItem(this, pProto);
10791 _ApplyItemMods(pItem, slot, false);
10793 // remove item dependent auras and casts (only weapon and armor slots)
10794 if(slot < EQUIPMENT_SLOT_END)
10796 RemoveItemDependentAurasAndCasts(pItem);
10798 // remove held enchantments, update expertise
10799 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10801 if (pItem->GetItemSuffixFactor())
10803 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10804 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10806 else
10808 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10809 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10812 UpdateExpertise(BASE_ATTACK);
10813 UpdateArmorPenetration();
10815 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10817 UpdateExpertise(OFF_ATTACK);
10818 UpdateArmorPenetration();
10822 // need update known currency
10823 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10824 UpdateKnownCurrencies(pItem->GetEntry(), false);
10826 m_items[slot] = NULL;
10827 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10829 if ( slot < EQUIPMENT_SLOT_END )
10830 SetVisibleItemSlot(slot, NULL);
10832 else
10834 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10835 if( pBag )
10836 pBag->RemoveItem(slot, update);
10838 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10839 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10840 pItem->SetSlot( NULL_SLOT );
10841 if( IsInWorld() && update )
10842 pItem->SendCreateUpdateToPlayer( this );
10846 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10847 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10849 if(Item* it = GetItemByPos(bag,slot))
10851 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10852 RemoveItem(bag, slot, update);
10853 it->RemoveFromUpdateQueueOf(this);
10854 if(it->IsInWorld())
10856 it->RemoveFromWorld();
10857 it->DestroyForPlayer( this );
10862 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10863 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10865 // update quest counters
10866 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10868 // store item
10869 Item* pLastItem = StoreItem(dest, pItem, update);
10871 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10872 if(pLastItem == pItem)
10874 // update owner for last item (this can be original item with wrong owner
10875 if(pLastItem->GetOwnerGUID() != GetGUID())
10876 pLastItem->SetOwnerGUID(GetGUID());
10878 // if this original item then it need create record in inventory
10879 // in case trade we already have item in other player inventory
10880 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10884 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10886 Item *pItem = GetItemByPos( bag, slot );
10887 if( pItem )
10889 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10891 // start from destroy contained items (only equipped bag can have its)
10892 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10894 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10895 DestroyItem(slot, i, update);
10898 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10899 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10901 RemoveEnchantmentDurations(pItem);
10902 RemoveItemDurations(pItem);
10904 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10906 if( bag == INVENTORY_SLOT_BAG_0 )
10908 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10910 // equipment and equipped bags can have applied bonuses
10911 if ( slot < INVENTORY_SLOT_BAG_END )
10913 ItemPrototype const *pProto = pItem->GetProto();
10915 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10916 if(pProto && pProto->ItemSet)
10917 RemoveItemsSetItem(this, pProto);
10919 _ApplyItemMods(pItem, slot, false);
10922 if ( slot < EQUIPMENT_SLOT_END )
10924 // remove item dependent auras and casts (only weapon and armor slots)
10925 RemoveItemDependentAurasAndCasts(pItem);
10927 // update expertise
10928 if( slot == EQUIPMENT_SLOT_MAINHAND )
10930 UpdateExpertise(BASE_ATTACK);
10931 UpdateArmorPenetration();
10933 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10935 UpdateExpertise(OFF_ATTACK);
10936 UpdateArmorPenetration();
10939 // equipment visual show
10940 SetVisibleItemSlot(slot, NULL);
10942 // need update known currency
10943 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10944 UpdateKnownCurrencies(pItem->GetEntry(), false);
10946 m_items[slot] = NULL;
10948 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10949 pBag->RemoveItem(slot, update);
10951 if( IsInWorld() && update )
10953 pItem->RemoveFromWorld();
10954 pItem->DestroyForPlayer(this);
10957 //pItem->SetOwnerGUID(0);
10958 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10959 pItem->SetSlot( NULL_SLOT );
10960 pItem->SetState(ITEM_REMOVED, this);
10964 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10966 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10967 uint32 remcount = 0;
10969 // in inventory
10970 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10972 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10974 if (pItem->GetEntry() == item)
10976 if (pItem->GetCount() + remcount <= count)
10978 // all items in inventory can unequipped
10979 remcount += pItem->GetCount();
10980 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10982 if (remcount >= count)
10983 return;
10985 else
10987 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10988 pItem->SetCount( pItem->GetCount() - count + remcount );
10989 if (IsInWorld() & update)
10990 pItem->SendCreateUpdateToPlayer( this );
10991 pItem->SetState(ITEM_CHANGED, this);
10992 return;
10998 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
11000 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11002 if (pItem->GetEntry() == item)
11004 if (pItem->GetCount() + remcount <= count)
11006 // all keys can be unequipped
11007 remcount += pItem->GetCount();
11008 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11010 if (remcount >= count)
11011 return;
11013 else
11015 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11016 pItem->SetCount( pItem->GetCount() - count + remcount );
11017 if (IsInWorld() & update)
11018 pItem->SendCreateUpdateToPlayer( this );
11019 pItem->SetState(ITEM_CHANGED, this);
11020 return;
11026 // in inventory bags
11027 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11029 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11031 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11033 if(Item* pItem = pBag->GetItemByPos(j))
11035 if (pItem->GetEntry() == item)
11037 // all items in bags can be unequipped
11038 if (pItem->GetCount() + remcount <= count)
11040 remcount += pItem->GetCount();
11041 DestroyItem( i, j, update );
11043 if (remcount >= count)
11044 return;
11046 else
11048 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11049 pItem->SetCount( pItem->GetCount() - count + remcount );
11050 if (IsInWorld() && update)
11051 pItem->SendCreateUpdateToPlayer( this );
11052 pItem->SetState(ITEM_CHANGED, this);
11053 return;
11061 // in equipment and bag list
11062 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11064 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11066 if (pItem && pItem->GetEntry() == item)
11068 if (pItem->GetCount() + remcount <= count)
11070 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
11072 remcount += pItem->GetCount();
11073 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11075 if (remcount >= count)
11076 return;
11079 else
11081 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11082 pItem->SetCount( pItem->GetCount() - count + remcount );
11083 if (IsInWorld() & update)
11084 pItem->SendCreateUpdateToPlayer( this );
11085 pItem->SetState(ITEM_CHANGED, this);
11086 return;
11093 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
11095 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
11097 // in inventory
11098 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11099 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11100 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11101 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11103 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
11104 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11105 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11106 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11108 // in inventory bags
11109 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11110 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11111 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11112 if (Item* pItem = pBag->GetItemByPos(j))
11113 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11114 DestroyItem(i, j, update);
11116 // in equipment and bag list
11117 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11118 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11119 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11120 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11123 void Player::DestroyConjuredItems( bool update )
11125 // used when entering arena
11126 // destroys all conjured items
11127 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
11129 // in inventory
11130 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11131 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11132 if (pItem->IsConjuredConsumable())
11133 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11135 // in inventory bags
11136 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11137 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11138 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11139 if (Item* pItem = pBag->GetItemByPos(j))
11140 if (pItem->IsConjuredConsumable())
11141 DestroyItem( i, j, update);
11143 // in equipment and bag list
11144 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11145 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11146 if (pItem->IsConjuredConsumable())
11147 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11150 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
11152 if(!pItem)
11153 return;
11155 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
11157 if( pItem->GetCount() <= count )
11159 count -= pItem->GetCount();
11161 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
11163 else
11165 ItemRemovedQuestCheck( pItem->GetEntry(), count);
11166 pItem->SetCount( pItem->GetCount() - count );
11167 count = 0;
11168 if( IsInWorld() & update )
11169 pItem->SendCreateUpdateToPlayer( this );
11170 pItem->SetState(ITEM_CHANGED, this);
11174 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
11176 uint8 srcbag = src >> 8;
11177 uint8 srcslot = src & 255;
11179 uint8 dstbag = dst >> 8;
11180 uint8 dstslot = dst & 255;
11182 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11183 if( !pSrcItem )
11185 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11186 return;
11189 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11191 //best error message found for attempting to split while looting
11192 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11193 return;
11196 // not let split all items (can be only at cheating)
11197 if(pSrcItem->GetCount() == count)
11199 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11200 return;
11203 // not let split more existed items (can be only at cheating)
11204 if(pSrcItem->GetCount() < count)
11206 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
11207 return;
11210 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11211 Item *pNewItem = pSrcItem->CloneItem( count, this );
11212 if( !pNewItem )
11214 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11215 return;
11218 if( IsInventoryPos( dst ) )
11220 // change item amount before check (for unique max count check)
11221 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11223 ItemPosCountVec dest;
11224 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11225 if( msg != EQUIP_ERR_OK )
11227 delete pNewItem;
11228 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11229 SendEquipError( msg, pSrcItem, NULL );
11230 return;
11233 if( IsInWorld() )
11234 pSrcItem->SendCreateUpdateToPlayer( this );
11235 pSrcItem->SetState(ITEM_CHANGED, this);
11236 StoreItem( dest, pNewItem, true);
11238 else if( IsBankPos ( dst ) )
11240 // change item amount before check (for unique max count check)
11241 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11243 ItemPosCountVec dest;
11244 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11245 if( msg != EQUIP_ERR_OK )
11247 delete pNewItem;
11248 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11249 SendEquipError( msg, pSrcItem, NULL );
11250 return;
11253 if( IsInWorld() )
11254 pSrcItem->SendCreateUpdateToPlayer( this );
11255 pSrcItem->SetState(ITEM_CHANGED, this);
11256 BankItem( dest, pNewItem, true);
11258 else if( IsEquipmentPos ( dst ) )
11260 // change item amount before check (for unique max count check), provide space for splitted items
11261 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11263 uint16 dest;
11264 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11265 if( msg != EQUIP_ERR_OK )
11267 delete pNewItem;
11268 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11269 SendEquipError( msg, pSrcItem, NULL );
11270 return;
11273 if( IsInWorld() )
11274 pSrcItem->SendCreateUpdateToPlayer( this );
11275 pSrcItem->SetState(ITEM_CHANGED, this);
11276 EquipItem( dest, pNewItem, true);
11277 AutoUnequipOffhandIfNeed();
11281 void Player::SwapItem( uint16 src, uint16 dst )
11283 uint8 srcbag = src >> 8;
11284 uint8 srcslot = src & 255;
11286 uint8 dstbag = dst >> 8;
11287 uint8 dstslot = dst & 255;
11289 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11290 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11292 if (!pSrcItem)
11293 return;
11295 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11297 if (!isAlive())
11299 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11300 return;
11303 // SRC checks
11305 // check unequip potability for equipped items and bank bags
11306 if (IsEquipmentPos(src) || IsBagPos(src))
11308 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11309 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty()));
11310 if (msg != EQUIP_ERR_OK)
11312 SendEquipError( msg, pSrcItem, pDstItem );
11313 return;
11317 // prevent put equipped/bank bag in self
11318 if (IsBagPos(src) && srcslot == dstbag)
11320 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11321 return;
11324 // prevent put equipped/bank bag in self
11325 if (IsBagPos(dst) && dstslot == srcbag)
11327 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pDstItem, pSrcItem );
11328 return;
11331 // DST checks
11333 if (pDstItem)
11335 // check unequip potability for equipped items and bank bags
11336 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11338 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11339 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty()));
11340 if(msg != EQUIP_ERR_OK)
11342 SendEquipError( msg, pSrcItem, pDstItem );
11343 return;
11348 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11349 // or swap empty bag with another empty or not empty bag (with items exchange)
11351 // Move case
11352 if( !pDstItem )
11354 if( IsInventoryPos( dst ) )
11356 ItemPosCountVec dest;
11357 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11358 if( msg != EQUIP_ERR_OK )
11360 SendEquipError( msg, pSrcItem, NULL );
11361 return;
11364 RemoveItem(srcbag, srcslot, true);
11365 StoreItem( dest, pSrcItem, true);
11367 else if( IsBankPos ( dst ) )
11369 ItemPosCountVec dest;
11370 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11371 if( msg != EQUIP_ERR_OK )
11373 SendEquipError( msg, pSrcItem, NULL );
11374 return;
11377 RemoveItem(srcbag, srcslot, true);
11378 BankItem( dest, pSrcItem, true);
11380 else if( IsEquipmentPos ( dst ) )
11382 uint16 dest;
11383 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11384 if( msg != EQUIP_ERR_OK )
11386 SendEquipError( msg, pSrcItem, NULL );
11387 return;
11390 RemoveItem(srcbag, srcslot, true);
11391 EquipItem(dest, pSrcItem, true);
11392 AutoUnequipOffhandIfNeed();
11395 return;
11398 // attempt merge to / fill target item
11399 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11401 uint8 msg;
11402 ItemPosCountVec sDest;
11403 uint16 eDest;
11404 if( IsInventoryPos( dst ) )
11405 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11406 else if( IsBankPos ( dst ) )
11407 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11408 else if( IsEquipmentPos ( dst ) )
11409 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11410 else
11411 return;
11413 // can be merge/fill
11414 if(msg == EQUIP_ERR_OK)
11416 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11418 RemoveItem(srcbag, srcslot, true);
11420 if( IsInventoryPos( dst ) )
11421 StoreItem( sDest, pSrcItem, true);
11422 else if( IsBankPos ( dst ) )
11423 BankItem( sDest, pSrcItem, true);
11424 else if( IsEquipmentPos ( dst ) )
11426 EquipItem( eDest, pSrcItem, true);
11427 AutoUnequipOffhandIfNeed();
11430 else
11432 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11433 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11434 pSrcItem->SetState(ITEM_CHANGED, this);
11435 pDstItem->SetState(ITEM_CHANGED, this);
11436 if( IsInWorld() )
11438 pSrcItem->SendCreateUpdateToPlayer( this );
11439 pDstItem->SendCreateUpdateToPlayer( this );
11442 return;
11446 // impossible merge/fill, do real swap
11447 uint8 msg;
11449 // check src->dest move possibility
11450 ItemPosCountVec sDest;
11451 uint16 eDest = 0;
11452 if( IsInventoryPos( dst ) )
11453 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11454 else if( IsBankPos( dst ) )
11455 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11456 else if( IsEquipmentPos( dst ) )
11458 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11459 if( msg == EQUIP_ERR_OK )
11460 msg = CanUnequipItem( eDest, true );
11463 if( msg != EQUIP_ERR_OK )
11465 SendEquipError( msg, pSrcItem, pDstItem );
11466 return;
11469 // check dest->src move possibility
11470 ItemPosCountVec sDest2;
11471 uint16 eDest2 = 0;
11472 if( IsInventoryPos( src ) )
11473 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11474 else if( IsBankPos( src ) )
11475 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11476 else if( IsEquipmentPos( src ) )
11478 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11479 if( msg == EQUIP_ERR_OK )
11480 msg = CanUnequipItem( eDest2, true);
11483 if( msg != EQUIP_ERR_OK )
11485 SendEquipError( msg, pDstItem, pSrcItem );
11486 return;
11489 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11490 if(pSrcItem->IsBag() && pDstItem->IsBag())
11492 Bag* emptyBag = NULL;
11493 Bag* fullBag = NULL;
11494 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11496 emptyBag = (Bag*)pSrcItem;
11497 fullBag = (Bag*)pDstItem;
11499 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11501 emptyBag = (Bag*)pDstItem;
11502 fullBag = (Bag*)pSrcItem;
11505 // bag swap (with items exchange) case
11506 if(emptyBag && fullBag)
11508 ItemPrototype const* emotyProto = emptyBag->GetProto();
11510 uint32 count = 0;
11512 for(uint32 i=0; i < fullBag->GetBagSize(); ++i)
11514 Item *bagItem = fullBag->GetItemByPos(i);
11515 if (!bagItem)
11516 continue;
11518 ItemPrototype const* bagItemProto = bagItem->GetProto();
11519 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11521 // one from items not go to empty target bag
11522 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11523 return;
11526 ++count;
11530 if (count > emptyBag->GetBagSize())
11532 // too small targeted bag
11533 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11534 return;
11537 // Items swap
11538 count = 0; // will pos in new bag
11539 for(uint32 i = 0; i< fullBag->GetBagSize(); ++i)
11541 Item *bagItem = fullBag->GetItemByPos(i);
11542 if (!bagItem)
11543 continue;
11545 fullBag->RemoveItem(i, true);
11546 emptyBag->StoreItem(count, bagItem, true);
11547 bagItem->SetState(ITEM_CHANGED, this);
11549 ++count;
11554 // now do moves, remove...
11555 RemoveItem(dstbag, dstslot, false);
11556 RemoveItem(srcbag, srcslot, false);
11558 // add to dest
11559 if (IsInventoryPos(dst))
11560 StoreItem(sDest, pSrcItem, true);
11561 else if (IsBankPos(dst))
11562 BankItem(sDest, pSrcItem, true);
11563 else if (IsEquipmentPos(dst))
11564 EquipItem(eDest, pSrcItem, true);
11566 // add to src
11567 if (IsInventoryPos(src))
11568 StoreItem(sDest2, pDstItem, true);
11569 else if (IsBankPos(src))
11570 BankItem(sDest2, pDstItem, true);
11571 else if (IsEquipmentPos(src))
11572 EquipItem(eDest2, pDstItem, true);
11574 AutoUnequipOffhandIfNeed();
11577 void Player::AddItemToBuyBackSlot( Item *pItem )
11579 if (pItem)
11581 uint32 slot = m_currentBuybackSlot;
11582 // if current back slot non-empty search oldest or free
11583 if (m_items[slot])
11585 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11586 uint32 oldest_slot = BUYBACK_SLOT_START;
11588 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11590 // found empty
11591 if (!m_items[i])
11593 slot = i;
11594 break;
11597 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11599 if (oldest_time > i_time)
11601 oldest_time = i_time;
11602 oldest_slot = i;
11606 // find oldest
11607 slot = oldest_slot;
11610 RemoveItemFromBuyBackSlot( slot, true );
11611 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11613 m_items[slot] = pItem;
11614 time_t base = time(NULL);
11615 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11616 uint32 eslot = slot - BUYBACK_SLOT_START;
11618 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11619 if (ItemPrototype const *pProto = pItem->GetProto())
11620 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11621 else
11622 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11623 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11625 // move to next (for non filled list is move most optimized choice)
11626 if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11627 ++m_currentBuybackSlot;
11631 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11633 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11634 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11635 return m_items[slot];
11636 return NULL;
11639 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11641 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11642 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11644 Item *pItem = m_items[slot];
11645 if (pItem)
11647 pItem->RemoveFromWorld();
11648 if(del) pItem->SetState(ITEM_REMOVED, this);
11651 m_items[slot] = NULL;
11653 uint32 eslot = slot - BUYBACK_SLOT_START;
11654 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11655 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11656 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11658 // if current backslot is filled set to now free slot
11659 if (m_items[m_currentBuybackSlot])
11660 m_currentBuybackSlot = slot;
11664 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11666 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11667 WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, 1+8+8+1);
11668 data << uint8(msg);
11670 if (msg != EQUIP_ERR_OK)
11672 data << uint64(pItem ? pItem->GetGUID() : 0);
11673 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11674 data << uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2
11676 switch(msg)
11678 case EQUIP_ERR_CANT_EQUIP_LEVEL_I:
11679 case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW:
11681 ItemPrototype const* proto = pItem ? pItem->GetProto() : NULL;
11682 data << uint32(proto ? proto->RequiredLevel : 0);
11683 } break;
11684 case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM: // no idea about this one...
11686 data << uint64(0);
11687 data << uint32(0);
11688 data << uint64(0);
11689 } break;
11690 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS:
11691 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS:
11692 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS:
11694 ItemPrototype const* proto = pItem ? pItem->GetProto() : NULL;
11695 data << uint32(proto ? proto->ItemLimitCategory : 0);
11696 } break;
11697 default:
11698 break;
11701 GetSession()->SendPacket(&data);
11704 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11706 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11707 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11708 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11709 data << uint32(item);
11710 if (param > 0)
11711 data << uint32(param);
11712 data << uint8(msg);
11713 GetSession()->SendPacket(&data);
11716 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11718 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11719 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11720 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11721 data << uint64(guid);
11722 if (param > 0)
11723 data << uint32(param);
11724 data << uint8(msg);
11725 GetSession()->SendPacket(&data);
11728 void Player::ClearTrade()
11730 tradeGold = 0;
11731 acceptTrade = false;
11732 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11733 tradeItems[i] = NULL_SLOT;
11736 void Player::TradeCancel(bool sendback)
11738 if (pTrader)
11740 // send yellow "Trade canceled" message to both traders
11741 WorldSession* ws;
11742 ws = GetSession();
11743 if (sendback)
11744 ws->SendCancelTrade();
11745 ws = pTrader->GetSession();
11746 if (!ws->PlayerLogout())
11747 ws->SendCancelTrade();
11749 // cleanup
11750 ClearTrade();
11751 pTrader->ClearTrade();
11752 // prevent loss of reference
11753 pTrader->pTrader = NULL;
11754 pTrader = NULL;
11758 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11760 if (m_itemDuration.empty())
11761 return;
11763 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11765 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11767 Item* item = *itr;
11768 ++itr; // current element can be erased in UpdateDuration
11770 if ((realtimeonly && item->GetProto()->Duration < 0) || !realtimeonly)
11771 item->UpdateDuration(this,time);
11775 void Player::UpdateEnchantTime(uint32 time)
11777 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11779 assert(itr->item);
11780 next = itr;
11781 if (!itr->item->GetEnchantmentId(itr->slot))
11783 next = m_enchantDuration.erase(itr);
11785 else if (itr->leftduration <= time)
11787 ApplyEnchantment(itr->item, itr->slot, false, false);
11788 itr->item->ClearEnchantment(itr->slot);
11789 next = m_enchantDuration.erase(itr);
11791 else if (itr->leftduration > time)
11793 itr->leftduration -= time;
11794 ++next;
11799 void Player::AddEnchantmentDurations(Item *item)
11801 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11803 if (!item->GetEnchantmentId(EnchantmentSlot(x)))
11804 continue;
11806 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11807 if (duration > 0)
11808 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11812 void Player::RemoveEnchantmentDurations(Item *item)
11814 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11816 if (itr->item == item)
11818 // save duration in item
11819 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11820 itr = m_enchantDuration.erase(itr);
11822 else
11823 ++itr;
11827 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11829 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11830 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11832 next = itr;
11833 if (itr->slot == slot)
11835 if (itr->item && itr->item->GetEnchantmentId(slot))
11837 // remove from stats
11838 ApplyEnchantment(itr->item, slot, false, false);
11839 // remove visual
11840 itr->item->ClearEnchantment(slot);
11842 // remove from update list
11843 next = m_enchantDuration.erase(itr);
11845 else
11846 ++next;
11849 // remove enchants from inventory items
11850 // NOTE: no need to remove these from stats, since these aren't equipped
11851 // in inventory
11852 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11853 if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
11854 if (pItem->GetEnchantmentId(slot))
11855 pItem->ClearEnchantment(slot);
11857 // in inventory bags
11858 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11859 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11860 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11861 if (Item* pItem = pBag->GetItemByPos(j))
11862 if (pItem->GetEnchantmentId(slot))
11863 pItem->ClearEnchantment(slot);
11866 // duration == 0 will remove item enchant
11867 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11869 if (!item)
11870 return;
11872 if (slot >= MAX_ENCHANTMENT_SLOT)
11873 return;
11875 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11877 if (itr->item == item && itr->slot == slot)
11879 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11880 m_enchantDuration.erase(itr);
11881 break;
11884 if (item && duration > 0 )
11886 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11887 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11891 void Player::ApplyEnchantment(Item *item,bool apply)
11893 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11894 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11897 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11899 if (!item)
11900 return;
11902 if (!item->IsEquipped())
11903 return;
11905 if (slot >= MAX_ENCHANTMENT_SLOT)
11906 return;
11908 uint32 enchant_id = item->GetEnchantmentId(slot);
11909 if (!enchant_id)
11910 return;
11912 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11913 if (!pEnchant)
11914 return;
11916 if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11917 return;
11919 if (!item->IsBroken())
11921 for (int s = 0; s < 3; ++s)
11923 uint32 enchant_display_type = pEnchant->type[s];
11924 uint32 enchant_amount = pEnchant->amount[s];
11925 uint32 enchant_spell_id = pEnchant->spellid[s];
11927 switch(enchant_display_type)
11929 case ITEM_ENCHANTMENT_TYPE_NONE:
11930 break;
11931 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11932 // processed in Player::CastItemCombatSpell
11933 break;
11934 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11935 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11936 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11937 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11938 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11939 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11940 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11941 break;
11942 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11943 if (enchant_spell_id)
11945 if (apply)
11947 int32 basepoints = 0;
11948 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11949 if (item->GetItemRandomPropertyId())
11951 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11952 if (item_rand)
11954 // Search enchant_amount
11955 for (int k = 0; k < 3; ++k)
11957 if(item_rand->enchant_id[k] == enchant_id)
11959 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11960 break;
11965 // Cast custom spell vs all equal basepoints getted from enchant_amount
11966 if (basepoints)
11967 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11968 else
11969 CastSpell(this, enchant_spell_id, true, item);
11971 else
11972 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11974 break;
11975 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11976 if (!enchant_amount)
11978 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11979 if(item_rand)
11981 for (int k = 0; k < 3; ++k)
11983 if(item_rand->enchant_id[k] == enchant_id)
11985 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11986 break;
11992 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11993 break;
11994 case ITEM_ENCHANTMENT_TYPE_STAT:
11996 if (!enchant_amount)
11998 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11999 if(item_rand_suffix)
12001 for (int k = 0; k < 3; ++k)
12003 if(item_rand_suffix->enchant_id[k] == enchant_id)
12005 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
12006 break;
12012 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
12013 switch (enchant_spell_id)
12015 case ITEM_MOD_MANA:
12016 sLog.outDebug("+ %u MANA",enchant_amount);
12017 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
12018 break;
12019 case ITEM_MOD_HEALTH:
12020 sLog.outDebug("+ %u HEALTH",enchant_amount);
12021 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
12022 break;
12023 case ITEM_MOD_AGILITY:
12024 sLog.outDebug("+ %u AGILITY",enchant_amount);
12025 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
12026 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
12027 break;
12028 case ITEM_MOD_STRENGTH:
12029 sLog.outDebug("+ %u STRENGTH",enchant_amount);
12030 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
12031 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
12032 break;
12033 case ITEM_MOD_INTELLECT:
12034 sLog.outDebug("+ %u INTELLECT",enchant_amount);
12035 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
12036 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
12037 break;
12038 case ITEM_MOD_SPIRIT:
12039 sLog.outDebug("+ %u SPIRIT",enchant_amount);
12040 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
12041 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
12042 break;
12043 case ITEM_MOD_STAMINA:
12044 sLog.outDebug("+ %u STAMINA",enchant_amount);
12045 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
12046 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
12047 break;
12048 case ITEM_MOD_DEFENSE_SKILL_RATING:
12049 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
12050 sLog.outDebug("+ %u DEFENCE", enchant_amount);
12051 break;
12052 case ITEM_MOD_DODGE_RATING:
12053 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
12054 sLog.outDebug("+ %u DODGE", enchant_amount);
12055 break;
12056 case ITEM_MOD_PARRY_RATING:
12057 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
12058 sLog.outDebug("+ %u PARRY", enchant_amount);
12059 break;
12060 case ITEM_MOD_BLOCK_RATING:
12061 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
12062 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
12063 break;
12064 case ITEM_MOD_HIT_MELEE_RATING:
12065 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12066 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
12067 break;
12068 case ITEM_MOD_HIT_RANGED_RATING:
12069 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12070 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
12071 break;
12072 case ITEM_MOD_HIT_SPELL_RATING:
12073 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12074 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
12075 break;
12076 case ITEM_MOD_CRIT_MELEE_RATING:
12077 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12078 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
12079 break;
12080 case ITEM_MOD_CRIT_RANGED_RATING:
12081 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12082 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
12083 break;
12084 case ITEM_MOD_CRIT_SPELL_RATING:
12085 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12086 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
12087 break;
12088 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12089 // in Enchantments
12090 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12091 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12092 // break;
12093 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12094 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12095 // break;
12096 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12097 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12098 // break;
12099 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12100 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12101 // break;
12102 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12103 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12104 // break;
12105 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12106 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12107 // break;
12108 // case ITEM_MOD_HASTE_MELEE_RATING:
12109 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12110 // break;
12111 // case ITEM_MOD_HASTE_RANGED_RATING:
12112 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12113 // break;
12114 case ITEM_MOD_HASTE_SPELL_RATING:
12115 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12116 break;
12117 case ITEM_MOD_HIT_RATING:
12118 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12119 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12120 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12121 sLog.outDebug("+ %u HIT", enchant_amount);
12122 break;
12123 case ITEM_MOD_CRIT_RATING:
12124 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12125 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12126 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12127 sLog.outDebug("+ %u CRITICAL", enchant_amount);
12128 break;
12129 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12130 // case ITEM_MOD_HIT_TAKEN_RATING:
12131 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12132 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12133 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12134 // break;
12135 // case ITEM_MOD_CRIT_TAKEN_RATING:
12136 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12137 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12138 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12139 // break;
12140 case ITEM_MOD_RESILIENCE_RATING:
12141 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12142 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12143 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12144 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
12145 break;
12146 case ITEM_MOD_HASTE_RATING:
12147 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12148 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12149 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12150 sLog.outDebug("+ %u HASTE", enchant_amount);
12151 break;
12152 case ITEM_MOD_EXPERTISE_RATING:
12153 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
12154 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
12155 break;
12156 case ITEM_MOD_ATTACK_POWER:
12157 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
12158 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12159 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
12160 break;
12161 case ITEM_MOD_RANGED_ATTACK_POWER:
12162 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12163 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
12164 break;
12165 case ITEM_MOD_MANA_REGENERATION:
12166 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
12167 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
12168 break;
12169 case ITEM_MOD_ARMOR_PENETRATION_RATING:
12170 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
12171 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
12172 break;
12173 case ITEM_MOD_SPELL_POWER:
12174 ((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
12175 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
12176 break;
12177 case ITEM_MOD_FERAL_ATTACK_POWER:
12178 case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
12179 case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
12180 default:
12181 break;
12183 break;
12185 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
12187 if(getClass() == CLASS_SHAMAN)
12189 float addValue = 0.0f;
12190 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12192 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12193 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
12195 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
12197 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12198 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
12201 break;
12203 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
12204 // processed in Player::CastItemUseSpell
12205 break;
12206 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
12207 // nothing do..
12208 break;
12209 default:
12210 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
12211 break;
12212 } /*switch(enchant_display_type)*/
12213 } /*for*/
12216 // visualize enchantment at player and equipped items
12217 if(slot == PERM_ENCHANTMENT_SLOT)
12218 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
12220 if(slot == TEMP_ENCHANTMENT_SLOT)
12221 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
12224 if(apply_dur)
12226 if(apply)
12228 // set duration
12229 uint32 duration = item->GetEnchantmentDuration(slot);
12230 if(duration > 0)
12231 AddEnchantmentDuration(item, slot, duration);
12233 else
12235 // duration == 0 will remove EnchantDuration
12236 AddEnchantmentDuration(item, slot, 0);
12241 void Player::SendEnchantmentDurations()
12243 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
12245 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
12249 void Player::SendItemDurations()
12251 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
12253 (*itr)->SendTimeUpdate(this);
12257 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12259 if(!item) // prevent crash
12260 return;
12262 // last check 2.0.10
12263 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12264 data << uint64(GetGUID()); // player GUID
12265 data << uint32(received); // 0=looted, 1=from npc
12266 data << uint32(created); // 0=received, 1=created
12267 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12268 data << uint8(item->GetBagSlot()); // bagslot
12269 // item slot, but when added to stack: 0xFFFFFFFF
12270 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
12271 data << uint32(item->GetEntry()); // item id
12272 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12273 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12274 data << uint32(count); // count of items
12275 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
12277 if (broadcast && GetGroup())
12278 GetGroup()->BroadcastPacket(&data, true);
12279 else
12280 GetSession()->SendPacket(&data);
12283 /*********************************************************/
12284 /*** GOSSIP SYSTEM ***/
12285 /*********************************************************/
12287 void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId)
12289 PlayerMenu* pMenu = PlayerTalkClass;
12290 pMenu->ClearMenus();
12292 pMenu->GetGossipMenu().SetMenuId(menuId);
12294 GossipMenuItemsMapBounds pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(menuId);
12296 // if default menuId and no menu options exist for this, use options from default options
12297 if (pMenuItemBounds.first == pMenuItemBounds.second && menuId == GetDefaultGossipMenuForSource(pSource))
12298 pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(0);
12300 for(GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr)
12302 bool bCanTalk = true;
12304 if (itr->second.cond_1 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1))
12305 continue;
12307 if (itr->second.cond_2 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12308 continue;
12310 if (itr->second.cond_3 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_3))
12311 continue;
12313 if (pSource->GetTypeId() == TYPEID_UNIT)
12315 Creature *pCreature = (Creature*)pSource;
12317 uint32 npcflags = pCreature->GetUInt32Value(UNIT_NPC_FLAGS);
12319 if (!(itr->second.npc_option_npcflag & npcflags))
12320 continue;
12322 switch(itr->second.option_id)
12324 case GOSSIP_OPTION_QUESTGIVER:
12325 PrepareQuestMenu(pSource->GetGUID());
12326 bCanTalk = false;
12327 break;
12328 case GOSSIP_OPTION_ARMORER:
12329 bCanTalk = false; // added in special mode
12330 break;
12331 case GOSSIP_OPTION_SPIRITHEALER:
12332 if (!isDead())
12333 bCanTalk = false;
12334 break;
12335 case GOSSIP_OPTION_VENDOR:
12337 VendorItemData const* vItems = pCreature->GetVendorItems();
12338 if (!vItems || vItems->Empty())
12340 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature->GetGUIDLow(), pCreature->GetEntry());
12341 bCanTalk = false;
12343 break;
12345 case GOSSIP_OPTION_TRAINER:
12346 if (!pCreature->isCanTrainingOf(this, false))
12347 bCanTalk = false;
12348 break;
12349 case GOSSIP_OPTION_UNLEARNTALENTS:
12350 if (!pCreature->isCanTrainingAndResetTalentsOf(this))
12351 bCanTalk = false;
12352 break;
12353 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12354 if (!GetPet() || GetPet()->getPetType() != HUNTER_PET || GetPet()->m_spells.size() <= 1 || pCreature->GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || pCreature->GetCreatureInfo()->trainer_class != CLASS_HUNTER)
12355 bCanTalk = false;
12356 break;
12357 case GOSSIP_OPTION_TAXIVENDOR:
12358 if (GetSession()->SendLearnNewTaxiNode(pCreature))
12359 return;
12360 break;
12361 case GOSSIP_OPTION_BATTLEFIELD:
12362 if (!pCreature->isCanInteractWithBattleMaster(this, false))
12363 bCanTalk = false;
12364 break;
12365 case GOSSIP_OPTION_STABLEPET:
12366 if (getClass() != CLASS_HUNTER)
12367 bCanTalk = false;
12368 break;
12369 case GOSSIP_OPTION_GOSSIP:
12370 case GOSSIP_OPTION_SPIRITGUIDE:
12371 case GOSSIP_OPTION_INNKEEPER:
12372 case GOSSIP_OPTION_BANKER:
12373 case GOSSIP_OPTION_PETITIONER:
12374 case GOSSIP_OPTION_TABARDDESIGNER:
12375 case GOSSIP_OPTION_AUCTIONEER:
12376 break; // no checks
12377 default:
12378 sLog.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature->GetEntry(), itr->second.option_id, itr->second.menu_id);
12379 bCanTalk = false;
12380 break;
12383 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12385 GameObject *pGo = (GameObject*)pSource;
12387 switch(itr->second.option_id)
12389 case GOSSIP_OPTION_QUESTGIVER:
12390 if (pGo->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
12391 PrepareQuestMenu(pSource->GetGUID());
12392 bCanTalk = false;
12393 break;
12394 case GOSSIP_OPTION_GOSSIP:
12395 if (pGo->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && pGo->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
12396 bCanTalk = false;
12397 break;
12398 default:
12399 bCanTalk = false;
12400 break;
12404 if (bCanTalk)
12406 std::string strOptionText = itr->second.option_text;
12407 std::string strBoxText = itr->second.box_text;
12409 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12411 if (loc_idx >= 0)
12413 uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.id);
12415 if (GossipMenuItemsLocale const *no = sObjectMgr.GetGossipMenuItemsLocale(idxEntry))
12417 if (no->OptionText.size() > (size_t)loc_idx && !no->OptionText[loc_idx].empty())
12418 strOptionText = no->OptionText[loc_idx];
12420 if (no->BoxText.size() > (size_t)loc_idx && !no->BoxText[loc_idx].empty())
12421 strBoxText = no->BoxText[loc_idx];
12425 pMenu->GetGossipMenu().AddMenuItem(itr->second.option_icon, strOptionText, 0, itr->second.option_id, strBoxText, itr->second.box_money, itr->second.box_coded);
12426 pMenu->GetGossipMenu().AddGossipMenuItemData(itr->second.action_menu_id, itr->second.action_poi_id, itr->second.action_script_id);
12430 // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
12431 /*if (pMenu->Empty())
12433 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
12435 // output error message if need
12436 pCreature->isCanTrainingOf(this, true);
12439 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
12441 // output error message if need
12442 pCreature->isCanInteractWithBattleMaster(this, true);
12447 void Player::SendPreparedGossip(WorldObject *pSource)
12449 if (!pSource)
12450 return;
12452 if (pSource->GetTypeId() == TYPEID_UNIT)
12454 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
12455 if (!((Creature*)pSource)->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
12457 SendPreparedQuest(pSource->GetGUID());
12458 return;
12461 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12463 // probably need to find a better way here
12464 if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
12466 SendPreparedQuest(pSource->GetGUID());
12467 return;
12471 // in case non empty gossip menu (that not included quests list size) show it
12472 // (quest entries from quest menu will be included in list)
12474 uint32 textId = GetGossipTextId(pSource);
12476 if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
12477 textId = GetGossipTextId(menuId);
12479 PlayerTalkClass->SendGossipMenu(textId, pSource->GetGUID());
12482 void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 menuId)
12484 GossipMenu& gossipmenu = PlayerTalkClass->GetGossipMenu();
12486 if (gossipListId >= gossipmenu.MenuItemCount())
12487 return;
12489 // if not same, then something funky is going on
12490 if (menuId != gossipmenu.GetMenuId())
12491 return;
12493 uint32 gossipOptionId = gossipmenu.GetItem(gossipListId).m_gOptionId;
12494 uint64 guid = pSource->GetGUID();
12496 if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12498 if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
12500 sLog.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource->GetEntry());
12501 return;
12505 GossipMenuItemData pMenuData = gossipmenu.GetItemData(gossipListId);
12507 switch(gossipOptionId)
12509 case GOSSIP_OPTION_GOSSIP:
12511 if (pMenuData.m_gAction_poi)
12512 PlayerTalkClass->SendPointOfInterest(pMenuData.m_gAction_poi);
12514 if (pMenuData.m_gAction_menu)
12516 PrepareGossipMenu(pSource, pMenuData.m_gAction_menu);
12517 SendPreparedGossip(pSource);
12520 if (pMenuData.m_gAction_script)
12522 if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12523 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, this, pSource);
12524 else if (pSource->GetTypeId() == TYPEID_UNIT)
12525 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, pSource, this);
12528 break;
12530 case GOSSIP_OPTION_SPIRITHEALER:
12531 if (isDead())
12532 ((Creature*)pSource)->CastSpell(((Creature*)pSource),17251,true,NULL,NULL,GetGUID());
12533 break;
12534 case GOSSIP_OPTION_QUESTGIVER:
12535 PrepareQuestMenu(guid);
12536 SendPreparedQuest(guid);
12537 break;
12538 case GOSSIP_OPTION_VENDOR:
12539 case GOSSIP_OPTION_ARMORER:
12540 GetSession()->SendListInventory(guid);
12541 break;
12542 case GOSSIP_OPTION_STABLEPET:
12543 GetSession()->SendStablePet(guid);
12544 break;
12545 case GOSSIP_OPTION_TRAINER:
12546 GetSession()->SendTrainerList(guid);
12547 break;
12548 case GOSSIP_OPTION_UNLEARNTALENTS:
12549 PlayerTalkClass->CloseGossip();
12550 SendTalentWipeConfirm(guid);
12551 break;
12552 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12553 PlayerTalkClass->CloseGossip();
12554 SendPetSkillWipeConfirm();
12555 break;
12556 case GOSSIP_OPTION_TAXIVENDOR:
12557 GetSession()->SendTaxiMenu(((Creature*)pSource));
12558 break;
12559 case GOSSIP_OPTION_INNKEEPER:
12560 PlayerTalkClass->CloseGossip();
12561 SetBindPoint(guid);
12562 break;
12563 case GOSSIP_OPTION_BANKER:
12564 GetSession()->SendShowBank(guid);
12565 break;
12566 case GOSSIP_OPTION_PETITIONER:
12567 PlayerTalkClass->CloseGossip();
12568 GetSession()->SendPetitionShowList(guid);
12569 break;
12570 case GOSSIP_OPTION_TABARDDESIGNER:
12571 PlayerTalkClass->CloseGossip();
12572 GetSession()->SendTabardVendorActivate(guid);
12573 break;
12574 case GOSSIP_OPTION_AUCTIONEER:
12575 GetSession()->SendAuctionHello(guid, ((Creature*)pSource));
12576 break;
12577 case GOSSIP_OPTION_SPIRITGUIDE:
12578 PrepareGossipMenu(pSource);
12579 SendPreparedGossip(pSource);
12580 break;
12581 case GOSSIP_OPTION_BATTLEFIELD:
12583 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(pSource->GetEntry());
12585 if (bgTypeId == BATTLEGROUND_TYPE_NONE)
12587 sLog.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
12588 return;
12591 GetSession()->SendBattlegGroundList(guid, bgTypeId);
12592 break;
12597 uint32 Player::GetGossipTextId(WorldObject *pSource)
12599 if (!pSource || pSource->GetTypeId() != TYPEID_UNIT || !((Creature*)pSource)->GetDBTableGUIDLow())
12600 return DEFAULT_GOSSIP_MESSAGE;
12602 if (uint32 pos = sObjectMgr.GetNpcGossip(((Creature*)pSource)->GetDBTableGUIDLow()))
12603 return pos;
12605 return DEFAULT_GOSSIP_MESSAGE;
12608 uint32 Player::GetGossipTextId(uint32 menuId)
12610 uint32 textId = DEFAULT_GOSSIP_MESSAGE;
12612 if (!menuId)
12613 return textId;
12615 GossipMenusMapBounds pMenuBounds = sObjectMgr.GetGossipMenusMapBounds(menuId);
12617 for(GossipMenusMap::const_iterator itr = pMenuBounds.first; itr != pMenuBounds.second; ++itr)
12619 if (sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1) && sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12620 textId = itr->second.text_id;
12623 return textId;
12626 uint32 Player::GetDefaultGossipMenuForSource(WorldObject *pSource)
12628 if (pSource->GetTypeId() == TYPEID_UNIT)
12629 return ((Creature*)pSource)->GetCreatureInfo()->GossipMenuId;
12630 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12631 return((GameObject*)pSource)->GetGOInfo()->GetGossipMenuId();
12633 return 0;
12636 /*********************************************************/
12637 /*** QUEST SYSTEM ***/
12638 /*********************************************************/
12640 void Player::PrepareQuestMenu( uint64 guid )
12642 Object *pObject;
12643 QuestRelations* pObjectQR;
12644 QuestRelations* pObjectQIR;
12646 // pets also can have quests
12647 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12649 pObject = (Object*)pCreature;
12650 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
12651 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
12653 else
12655 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12656 //only for quests which cast teleport spells on player
12657 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
12658 ASSERT(_map);
12659 GameObject *pGameObject = _map->GetGameObject(guid);
12660 if( pGameObject )
12662 pObject = (Object*)pGameObject;
12663 pObjectQR = &sObjectMgr.mGOQuestRelations;
12664 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
12666 else
12667 return;
12670 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12671 qm.ClearMenu();
12673 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12675 uint32 quest_id = i->second;
12676 QuestStatus status = GetQuestStatus( quest_id );
12677 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12678 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12679 else if ( status == QUEST_STATUS_INCOMPLETE )
12680 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12681 else if (status == QUEST_STATUS_AVAILABLE )
12682 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12685 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12687 uint32 quest_id = i->second;
12688 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12689 if(!pQuest) continue;
12691 QuestStatus status = GetQuestStatus( quest_id );
12693 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12694 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12695 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12696 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12700 void Player::SendPreparedQuest(uint64 guid)
12702 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12704 if (questMenu.Empty())
12705 return;
12707 QuestMenuItem const& qmi0 = questMenu.GetItem(0);
12709 uint32 status = qmi0.m_qIcon;
12711 // single element case
12712 if (questMenu.MenuItemCount() == 1)
12714 // Auto open -- maybe also should verify there is no greeting
12715 uint32 quest_id = qmi0.m_qId;
12716 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12718 if (pQuest)
12720 if (status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus(quest_id))
12721 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12722 else if (status == DIALOG_STATUS_UNK2)
12723 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12724 // Send completable on repeatable and autoCompletable quest if player don't have quest
12725 // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
12726 else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDaily())
12727 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true);
12728 else
12729 PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true);
12732 // multiply entries
12733 else
12735 QEmote qe;
12736 qe._Delay = 0;
12737 qe._Emote = 0;
12738 std::string title = "";
12740 // need pet case for some quests
12741 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12743 uint32 textid = GetGossipTextId(pCreature);
12745 GossipText const* gossiptext = sObjectMgr.GetGossipText(textid);
12746 if (!gossiptext)
12748 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12749 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12750 title = "";
12752 else
12754 qe = gossiptext->Options[0].Emotes[0];
12756 if(!gossiptext->Options[0].Text_0.empty())
12758 title = gossiptext->Options[0].Text_0;
12760 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12761 if (loc_idx >= 0)
12763 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12764 if (nl)
12766 if ((int32)nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12767 title = nl->Text_0[0][loc_idx];
12771 else
12773 title = gossiptext->Options[0].Text_1;
12775 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12776 if (loc_idx >= 0)
12778 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12779 if (nl)
12781 if ((int32)nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12782 title = nl->Text_1[0][loc_idx];
12788 PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
12792 bool Player::IsActiveQuest( uint32 quest_id ) const
12794 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12796 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12799 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12801 Object *pObject;
12802 QuestRelations* pObjectQR;
12803 QuestRelations* pObjectQIR;
12805 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12807 pObject = (Object*)pCreature;
12808 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
12809 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
12811 else
12813 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12814 //only for quests which cast teleport spells on player
12815 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
12816 ASSERT(_map);
12817 GameObject *pGameObject = _map->GetGameObject(guid);
12818 if( pGameObject )
12820 pObject = (Object*)pGameObject;
12821 pObjectQR = &sObjectMgr.mGOQuestRelations;
12822 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
12824 else
12825 return NULL;
12828 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12829 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12831 if (itr->second == nextQuestID)
12832 return sObjectMgr.GetQuestTemplate(nextQuestID);
12835 return NULL;
12838 bool Player::CanSeeStartQuest( Quest const *pQuest )
12840 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12841 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12842 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12843 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12845 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12848 return false;
12851 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12853 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12854 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12855 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12856 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12857 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12858 && SatisfyQuestDay( pQuest, msg );
12861 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12863 if( !SatisfyQuestLog( msg ) )
12864 return false;
12866 uint32 srcitem = pQuest->GetSrcItemId();
12867 if( srcitem > 0 )
12869 uint32 count = pQuest->GetSrcItemCount();
12870 ItemPosCountVec dest;
12871 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12873 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12874 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12875 return true;
12876 else if( msg2 != EQUIP_ERR_OK )
12878 SendEquipError( msg2, NULL, NULL );
12879 return false;
12882 return true;
12885 bool Player::CanCompleteQuest( uint32 quest_id )
12887 if( quest_id )
12889 QuestStatusData& q_status = mQuestStatus[quest_id];
12890 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12891 return false; // not allow re-complete quest
12893 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
12895 if(!qInfo)
12896 return false;
12898 // auto complete quest
12899 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12900 return true;
12902 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12905 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12907 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12909 if( qInfo->ReqItemCount[i] != 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12910 return false;
12914 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12916 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12918 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12919 continue;
12921 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12922 return false;
12926 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12927 return false;
12929 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12930 return false;
12932 if ( qInfo->GetRewOrReqMoney() < 0 )
12934 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12935 return false;
12938 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12939 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12940 return false;
12942 return true;
12945 return false;
12948 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12950 // Solve problem that player don't have the quest and try complete it.
12951 // if repeatable she must be able to complete event if player don't have it.
12952 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12953 if( !CanTakeQuest(pQuest, false) )
12954 return false;
12956 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12957 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12958 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i], pQuest->ReqItemCount[i]) )
12959 return false;
12961 if( !CanRewardQuest(pQuest, false) )
12962 return false;
12964 return true;
12967 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12969 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12970 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12971 return false;
12973 // daily quest can't be rewarded (25 daily quest already completed)
12974 if(!SatisfyQuestDay(pQuest,true))
12975 return false;
12977 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12978 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12979 return false;
12981 // prevent receive reward with quest items in bank
12982 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12984 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12986 if( pQuest->ReqItemCount[i] != 0 &&
12987 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12989 if(msg)
12990 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12991 return false;
12996 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12997 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12998 return false;
13000 return true;
13003 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
13005 // prevent receive reward with quest items in bank or for not completed quest
13006 if(!CanRewardQuest(pQuest,msg))
13007 return false;
13009 if ( pQuest->GetRewChoiceItemsCount() > 0 )
13011 if( pQuest->RewChoiceItemId[reward] )
13013 ItemPosCountVec dest;
13014 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
13015 if( res != EQUIP_ERR_OK )
13017 SendEquipError( res, NULL, NULL );
13018 return false;
13023 if ( pQuest->GetRewItemsCount() > 0 )
13025 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
13027 if( pQuest->RewItemId[i] )
13029 ItemPosCountVec dest;
13030 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
13031 if( res != EQUIP_ERR_OK )
13033 SendEquipError( res, NULL, NULL );
13034 return false;
13040 return true;
13043 void Player::SendPetTameFailure(PetTameFailureReason reason)
13045 WorldPacket data(SMSG_PET_TAME_FAILURE, 1);
13046 data << uint8(reason);
13047 GetSession()->SendPacket(&data);
13050 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
13052 uint16 log_slot = FindQuestSlot( 0 );
13053 assert(log_slot < MAX_QUEST_LOG_SIZE);
13055 uint32 quest_id = pQuest->GetQuestId();
13057 // if not exist then created with set uState==NEW and rewarded=false
13058 QuestStatusData& questStatusData = mQuestStatus[quest_id];
13060 // check for repeatable quests status reset
13061 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
13062 questStatusData.m_explored = false;
13064 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13066 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13067 questStatusData.m_itemcount[i] = 0;
13070 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
13072 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13073 questStatusData.m_creatureOrGOcount[i] = 0;
13076 GiveQuestSourceItem( pQuest );
13077 AdjustQuestReqItemCount( pQuest, questStatusData );
13079 if( pQuest->GetRepObjectiveFaction() )
13080 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
13081 GetReputationMgr().SetVisible(factionEntry);
13083 uint32 qtime = 0;
13084 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13086 uint32 limittime = pQuest->GetLimitTime();
13088 // shared timed quest
13089 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
13090 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
13092 AddTimedQuest( quest_id );
13093 questStatusData.m_timer = limittime * IN_MILISECONDS;
13094 qtime = static_cast<uint32>(time(NULL)) + limittime;
13096 else
13097 questStatusData.m_timer = 0;
13099 SetQuestSlot(log_slot, quest_id, qtime);
13101 if (questStatusData.uState != QUEST_NEW)
13102 questStatusData.uState = QUEST_CHANGED;
13104 //starting initial quest script
13105 if(questGiver && pQuest->GetQuestStartScript()!=0)
13106 GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
13108 // Some spells applied at quest activation
13109 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,true);
13110 if(saBounds.first != saBounds.second)
13112 uint32 zone, area;
13113 GetZoneAndAreaId(zone,area);
13115 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13116 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13117 if( !HasAura(itr->second->spellId,0) )
13118 CastSpell(this,itr->second->spellId,true);
13121 UpdateForQuestWorldObjects();
13124 void Player::CompleteQuest( uint32 quest_id )
13126 if( quest_id )
13128 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
13130 uint16 log_slot = FindQuestSlot( quest_id );
13131 if( log_slot < MAX_QUEST_LOG_SIZE)
13132 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13134 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
13136 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
13137 RewardQuest(qInfo,0,this,false);
13138 else
13139 SendQuestComplete( quest_id );
13144 void Player::IncompleteQuest( uint32 quest_id )
13146 if( quest_id )
13148 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
13150 uint16 log_slot = FindQuestSlot( quest_id );
13151 if( log_slot < MAX_QUEST_LOG_SIZE)
13152 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13156 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
13158 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
13159 //should work fine, cause far teleport will be executed in Player::Update()
13160 SetCanDelayTeleport(true);
13162 uint32 quest_id = pQuest->GetQuestId();
13164 for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i )
13166 if (pQuest->ReqItemId[i])
13167 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
13170 RemoveTimedQuest(quest_id);
13172 if (BattleGround* bg = GetBattleGround())
13173 if (bg->GetTypeID() == BATTLEGROUND_AV)
13174 ((BattleGroundAV*)bg)->HandleQuestComplete(pQuest->GetQuestId(), this);
13176 if (pQuest->GetRewChoiceItemsCount() > 0)
13178 if (uint32 itemId = pQuest->RewChoiceItemId[reward])
13180 ItemPosCountVec dest;
13181 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK)
13183 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13184 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
13189 if (pQuest->GetRewItemsCount() > 0)
13191 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
13193 if (uint32 itemId = pQuest->RewItemId[i])
13195 ItemPosCountVec dest;
13196 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i] ) == EQUIP_ERR_OK)
13198 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13199 SendNewItem(item, pQuest->RewItemCount[i], true, false);
13205 RewardReputation( pQuest );
13207 uint16 log_slot = FindQuestSlot( quest_id );
13208 if (log_slot < MAX_QUEST_LOG_SIZE)
13209 SetQuestSlot(log_slot,0);
13211 QuestStatusData& q_status = mQuestStatus[quest_id];
13213 // Not give XP in case already completed once repeatable quest
13214 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
13216 if (getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
13217 GiveXP( XP , NULL );
13218 else
13220 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
13221 ModifyMoney( money );
13222 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
13225 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
13226 if (pQuest->GetRewOrReqMoney())
13228 ModifyMoney( pQuest->GetRewOrReqMoney() );
13230 if (pQuest->GetRewOrReqMoney() > 0)
13231 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
13234 // honor reward
13235 if (pQuest->GetRewHonorAddition())
13236 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorAddition()));
13238 // title reward
13239 if (pQuest->GetCharTitleId())
13241 if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
13242 SetTitle(titleEntry);
13245 if (pQuest->GetBonusTalents())
13247 m_questRewardTalentCount+=pQuest->GetBonusTalents();
13248 InitTalentForLevel();
13251 // Send reward mail
13252 if (uint32 mail_template_id = pQuest->GetRewMailTemplateId())
13253 MailDraft(mail_template_id).SendMailTo(this, questGiver, MAIL_CHECK_MASK_NONE, pQuest->GetRewMailDelaySecs());
13255 if (pQuest->IsDaily())
13257 SetDailyQuestStatus(quest_id);
13258 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
13261 if (!pQuest->IsRepeatable())
13262 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
13263 else
13264 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
13266 q_status.m_rewarded = true;
13267 if (q_status.uState != QUEST_NEW)
13268 q_status.uState = QUEST_CHANGED;
13270 if (announce)
13271 SendQuestReward( pQuest, XP, questGiver );
13273 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
13274 if (pQuest->GetRewSpellCast() > 0)
13275 CastSpell( this, pQuest->GetRewSpellCast(), true);
13276 else if ( pQuest->GetRewSpell() > 0)
13277 CastSpell( this, pQuest->GetRewSpell(), true);
13279 if (pQuest->GetZoneOrSort() > 0)
13280 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
13281 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
13282 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
13284 uint32 zone = 0;
13285 uint32 area = 0;
13287 // remove auras from spells with quest reward state limitations
13288 SpellAreaForQuestMapBounds saEndBounds = sSpellMgr.GetSpellAreaForQuestEndMapBounds(quest_id);
13289 if(saEndBounds.first != saEndBounds.second)
13291 GetZoneAndAreaId(zone,area);
13293 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
13294 if(!itr->second->IsFitToRequirements(this,zone,area))
13295 RemoveAurasDueToSpell(itr->second->spellId);
13298 // Some spells applied at quest reward
13299 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,false);
13300 if(saBounds.first != saBounds.second)
13302 if(!zone || !area)
13303 GetZoneAndAreaId(zone,area);
13305 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13306 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13307 if( !HasAura(itr->second->spellId,0) )
13308 CastSpell(this,itr->second->spellId,true);
13311 //lets remove flag for delayed teleports
13312 SetCanDelayTeleport(false);
13315 void Player::FailQuest(uint32 questId)
13317 if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(questId))
13319 SetQuestStatus(questId, QUEST_STATUS_FAILED);
13321 uint16 log_slot = FindQuestSlot(questId);
13323 if (log_slot < MAX_QUEST_LOG_SIZE)
13325 SetQuestSlotTimer(log_slot, 1);
13326 SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
13329 if (pQuest->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13331 QuestStatusData& q_status = mQuestStatus[questId];
13333 RemoveTimedQuest(questId);
13334 q_status.m_timer = 0;
13336 SendQuestTimerFailed(questId);
13338 else
13339 SendQuestFailed(questId);
13343 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
13345 int32 zoneOrSort = qInfo->GetZoneOrSort();
13346 int32 skillOrClass = qInfo->GetSkillOrClass();
13348 // skip zone zoneOrSort and 0 case skillOrClass
13349 if( zoneOrSort >= 0 && skillOrClass == 0 )
13350 return true;
13352 int32 questSort = -zoneOrSort;
13353 uint8 reqSortClass = ClassByQuestSort(questSort);
13355 // check class sort cases in zoneOrSort
13356 if( reqSortClass != 0 && getClass() != reqSortClass)
13358 if( msg )
13359 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13360 return false;
13363 // check class
13364 if( skillOrClass < 0 )
13366 uint8 reqClass = -int32(skillOrClass);
13367 if(getClass() != reqClass)
13369 if( msg )
13370 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13371 return false;
13374 // check skill
13375 else if( skillOrClass > 0 )
13377 uint32 reqSkill = skillOrClass;
13378 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
13380 if( msg )
13381 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13382 return false;
13386 return true;
13389 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
13391 if( getLevel() < qInfo->GetMinLevel() )
13393 if( msg )
13394 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13395 return false;
13397 return true;
13400 bool Player::SatisfyQuestLog( bool msg )
13402 // exist free slot
13403 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
13404 return true;
13406 if( msg )
13408 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
13409 GetSession()->SendPacket( &data );
13410 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
13412 return false;
13415 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
13417 // No previous quest (might be first quest in a series)
13418 if( qInfo->prevQuests.empty())
13419 return true;
13421 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
13423 uint32 prevId = abs(*iter);
13425 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13426 Quest const* qPrevInfo = sObjectMgr.GetQuestTemplate(prevId);
13428 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
13430 // If any of the positive previous quests completed, return true
13431 if( *iter > 0 && i_prevstatus->second.m_rewarded )
13433 // skip one-from-all exclusive group
13434 if(qPrevInfo->GetExclusiveGroup() >= 0)
13435 return true;
13437 // each-from-all exclusive group ( < 0)
13438 // can be start if only all quests in prev quest exclusive group completed and rewarded
13439 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13440 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13442 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13444 for(; iter2 != end; ++iter2)
13446 uint32 exclude_Id = iter2->second;
13448 // skip checked quest id, only state of other quests in group is interesting
13449 if(exclude_Id == prevId)
13450 continue;
13452 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13454 // alternative quest from group also must be completed and rewarded(reported)
13455 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
13457 if( msg )
13458 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13459 return false;
13462 return true;
13464 // If any of the negative previous quests active, return true
13465 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13466 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
13468 // skip one-from-all exclusive group
13469 if(qPrevInfo->GetExclusiveGroup() >= 0)
13470 return true;
13472 // each-from-all exclusive group ( < 0)
13473 // can be start if only all quests in prev quest exclusive group active
13474 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13475 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13477 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13479 for(; iter2 != end; ++iter2)
13481 uint32 exclude_Id = iter2->second;
13483 // skip checked quest id, only state of other quests in group is interesting
13484 if(exclude_Id == prevId)
13485 continue;
13487 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13489 // alternative quest from group also must be active
13490 if( i_exstatus == mQuestStatus.end() ||
13491 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
13492 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
13494 if( msg )
13495 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13496 return false;
13499 return true;
13504 // Has only positive prev. quests in non-rewarded state
13505 // and negative prev. quests in non-active state
13506 if( msg )
13507 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13509 return false;
13512 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
13514 uint32 reqraces = qInfo->GetRequiredRaces();
13515 if ( reqraces == 0 )
13516 return true;
13517 if( (reqraces & getRaceMask()) == 0 )
13519 if( msg )
13520 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13521 return false;
13523 return true;
13526 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13528 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13529 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13531 if( msg )
13532 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13533 return false;
13536 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13537 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13539 if( msg )
13540 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13541 return false;
13544 return true;
13547 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13549 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13550 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13552 if( msg )
13553 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13554 return false;
13556 return true;
13559 bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
13561 if (!m_timedquests.empty() && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13563 if (msg)
13564 SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
13566 return false;
13568 return true;
13571 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13573 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13574 if(qInfo->GetExclusiveGroup() <= 0)
13575 return true;
13577 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = sObjectMgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13578 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13580 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13582 for(; iter != end; ++iter)
13584 uint32 exclude_Id = iter->second;
13586 // skip checked quest id, only state of other quests in group is interesting
13587 if(exclude_Id == qInfo->GetQuestId())
13588 continue;
13590 // not allow have daily quest if daily quest from exclusive group already recently completed
13591 Quest const* Nquest = sObjectMgr.GetQuestTemplate(exclude_Id);
13592 if( !SatisfyQuestDay(Nquest, false) )
13594 if( msg )
13595 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13596 return false;
13599 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13601 // alternative quest already started or completed
13602 if( i_exstatus != mQuestStatus.end()
13603 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13605 if( msg )
13606 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13607 return false;
13610 return true;
13613 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13615 if(!qInfo->GetNextQuestInChain())
13616 return true;
13618 // next quest in chain already started or completed
13619 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13620 if( itr != mQuestStatus.end()
13621 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13623 if( msg )
13624 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13625 return false;
13628 // check for all quests further up the chain
13629 // only necessary if there are quest chains with more than one quest that can be skipped
13630 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13631 return true;
13634 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13636 // No previous quest in chain
13637 if( qInfo->prevChainQuests.empty())
13638 return true;
13640 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13642 uint32 prevId = *iter;
13644 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13646 if( i_prevstatus != mQuestStatus.end() )
13648 // If any of the previous quests in chain active, return false
13649 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13650 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13652 if( msg )
13653 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13654 return false;
13658 // check for all quests further down the chain
13659 // only necessary if there are quest chains with more than one quest that can be skipped
13660 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13661 // return false;
13664 // No previous quest in chain active
13665 return true;
13668 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13670 if(!qInfo->IsDaily())
13671 return true;
13673 bool have_slot = false;
13674 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13676 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13677 if(qInfo->GetQuestId()==id)
13678 return false;
13680 if(!id)
13681 have_slot = true;
13684 if(!have_slot)
13686 if( msg )
13687 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13688 return false;
13691 return true;
13694 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13696 uint32 srcitem = pQuest->GetSrcItemId();
13697 if( srcitem > 0 )
13699 uint32 count = pQuest->GetSrcItemCount();
13700 if( count <= 0 )
13701 count = 1;
13703 ItemPosCountVec dest;
13704 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13705 if( msg == EQUIP_ERR_OK )
13707 Item * item = StoreNewItem(dest, srcitem, true);
13708 SendNewItem(item, count, true, false);
13709 return true;
13711 // player already have max amount required item, just report success
13712 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13713 return true;
13714 else
13715 SendEquipError( msg, NULL, NULL );
13716 return false;
13719 return true;
13722 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13724 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13725 if( qInfo )
13727 uint32 srcitem = qInfo->GetSrcItemId();
13728 if( srcitem > 0 )
13730 uint32 count = qInfo->GetSrcItemCount();
13731 if( count <= 0 )
13732 count = 1;
13734 // exist one case when destroy source quest item not possible:
13735 // non un-equippable item (equipped non-empty bag, for example)
13736 uint8 res = CanUnequipItems(srcitem,count);
13737 if(res != EQUIP_ERR_OK)
13739 if(msg)
13740 SendEquipError( res, NULL, NULL );
13741 return false;
13744 DestroyItemCount(srcitem, count, true, true);
13747 return true;
13750 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13752 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13753 if( qInfo )
13755 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13756 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13757 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13758 && !qInfo->IsRepeatable() )
13759 return itr->second.m_rewarded;
13761 return false;
13763 return false;
13766 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13768 if( quest_id )
13770 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13771 if( itr != mQuestStatus.end() )
13772 return itr->second.m_status;
13774 return QUEST_STATUS_NONE;
13777 bool Player::CanShareQuest(uint32 quest_id) const
13779 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13780 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13782 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13783 if( itr != mQuestStatus.end() )
13784 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13786 return false;
13789 void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
13791 if (sObjectMgr.GetQuestTemplate(quest_id))
13793 QuestStatusData& q_status = mQuestStatus[quest_id];
13795 q_status.m_status = status;
13797 if (q_status.uState != QUEST_NEW)
13798 q_status.uState = QUEST_CHANGED;
13801 UpdateForQuestWorldObjects();
13804 // not used in MaNGOS, but used in scripting code
13805 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13807 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13808 if( !qInfo )
13809 return 0;
13811 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13812 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13813 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13815 return 0;
13818 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13820 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13822 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13824 uint32 reqitemcount = pQuest->ReqItemCount[i];
13825 if( reqitemcount != 0 )
13827 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i], true);
13829 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13830 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13836 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13838 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13839 if ( GetQuestSlotQuestId(i) == quest_id )
13840 return i;
13842 return MAX_QUEST_LOG_SIZE;
13845 void Player::AreaExploredOrEventHappens( uint32 questId )
13847 if( questId )
13849 uint16 log_slot = FindQuestSlot( questId );
13850 if( log_slot < MAX_QUEST_LOG_SIZE)
13852 QuestStatusData& q_status = mQuestStatus[questId];
13854 if(!q_status.m_explored)
13856 q_status.m_explored = true;
13857 if (q_status.uState != QUEST_NEW)
13858 q_status.uState = QUEST_CHANGED;
13861 if( CanCompleteQuest( questId ) )
13862 CompleteQuest( questId );
13866 //not used in mangosd, function for external script library
13867 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13869 if( Group *pGroup = GetGroup() )
13871 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13873 Player *pGroupGuy = itr->getSource();
13875 // for any leave or dead (with not released body) group member at appropriate distance
13876 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13877 pGroupGuy->AreaExploredOrEventHappens(questId);
13880 else
13881 AreaExploredOrEventHappens(questId);
13884 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13886 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13888 uint32 questid = GetQuestSlotQuestId(i);
13889 if ( questid == 0 )
13890 continue;
13892 QuestStatusData& q_status = mQuestStatus[questid];
13894 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13895 continue;
13897 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13898 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13899 continue;
13901 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
13903 uint32 reqitem = qInfo->ReqItemId[j];
13904 if ( reqitem == entry )
13906 uint32 reqitemcount = qInfo->ReqItemCount[j];
13907 uint32 curitemcount = q_status.m_itemcount[j];
13908 if ( curitemcount < reqitemcount )
13910 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13911 q_status.m_itemcount[j] += additemcount;
13912 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13914 SendQuestUpdateAddItem( qInfo, j, additemcount );
13916 if ( CanCompleteQuest( questid ) )
13917 CompleteQuest( questid );
13918 return;
13922 UpdateForQuestWorldObjects();
13925 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13927 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13929 uint32 questid = GetQuestSlotQuestId(i);
13930 if(!questid)
13931 continue;
13932 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13933 if ( !qInfo )
13934 continue;
13935 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13936 continue;
13938 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
13940 uint32 reqitem = qInfo->ReqItemId[j];
13941 if ( reqitem == entry )
13943 QuestStatusData& q_status = mQuestStatus[questid];
13945 uint32 reqitemcount = qInfo->ReqItemCount[j];
13946 uint32 curitemcount;
13947 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13948 curitemcount = q_status.m_itemcount[j];
13949 else
13950 curitemcount = GetItemCount(entry, true);
13951 if ( curitemcount < reqitemcount + count )
13953 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13954 q_status.m_itemcount[j] = curitemcount - remitemcount;
13955 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13957 IncompleteQuest( questid );
13959 return;
13963 UpdateForQuestWorldObjects();
13966 void Player::KilledMonster( CreatureInfo const* cInfo, uint64 guid )
13968 if(cInfo->Entry)
13969 KilledMonsterCredit(cInfo->Entry,guid);
13971 for(int i = 0; i < MAX_KILL_CREDIT; ++i)
13972 if(cInfo->KillCredit[i])
13973 KilledMonsterCredit(cInfo->KillCredit[i],guid);
13976 void Player::KilledMonsterCredit( uint32 entry, uint64 guid )
13978 uint32 addkillcount = 1;
13979 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13980 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13982 uint32 questid = GetQuestSlotQuestId(i);
13983 if(!questid)
13984 continue;
13986 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13987 if( !qInfo )
13988 continue;
13989 // just if !ingroup || !noraidgroup || raidgroup
13990 QuestStatusData& q_status = mQuestStatus[questid];
13991 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13993 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13995 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13997 // skip GO activate objective or none
13998 if(qInfo->ReqCreatureOrGOId[j] <=0)
13999 continue;
14001 // skip Cast at creature objective
14002 if(qInfo->ReqSpell[j] !=0 )
14003 continue;
14005 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
14007 if ( reqkill == entry )
14009 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
14010 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
14011 if ( curkillcount < reqkillcount )
14013 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
14014 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14016 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
14018 if ( CanCompleteQuest( questid ) )
14019 CompleteQuest( questid );
14021 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14022 continue;
14030 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
14032 bool isCreature = IS_CREATURE_GUID(guid);
14034 uint32 addCastCount = 1;
14035 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
14037 uint32 questid = GetQuestSlotQuestId(i);
14038 if(!questid)
14039 continue;
14041 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14042 if ( !qInfo )
14043 continue;
14045 QuestStatusData& q_status = mQuestStatus[questid];
14047 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14049 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
14051 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14053 // skip kill creature objective (0) or wrong spell casts
14054 if(qInfo->ReqSpell[j] != spell_id )
14055 continue;
14057 uint32 reqTarget = 0;
14059 if(isCreature)
14061 // creature activate objectives
14062 if(qInfo->ReqCreatureOrGOId[j] > 0)
14063 // checked at quest_template loading
14064 reqTarget = qInfo->ReqCreatureOrGOId[j];
14066 else
14068 // GO activate objective
14069 if(qInfo->ReqCreatureOrGOId[j] < 0)
14070 // checked at quest_template loading
14071 reqTarget = - qInfo->ReqCreatureOrGOId[j];
14074 // other not this creature/GO related objectives
14075 if( reqTarget != entry )
14076 continue;
14078 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
14079 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
14080 if ( curCastCount < reqCastCount )
14082 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
14083 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14085 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
14088 if ( CanCompleteQuest( questid ) )
14089 CompleteQuest( questid );
14091 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14092 break;
14099 void Player::TalkedToCreature( uint32 entry, uint64 guid )
14101 uint32 addTalkCount = 1;
14102 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14104 uint32 questid = GetQuestSlotQuestId(i);
14105 if(!questid)
14106 continue;
14108 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14109 if ( !qInfo )
14110 continue;
14112 QuestStatusData& q_status = mQuestStatus[questid];
14114 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14116 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
14118 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14120 // skip spell casts and Gameobject objectives
14121 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
14122 continue;
14124 uint32 reqTarget = 0;
14126 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
14127 // checked at quest_template loading
14128 reqTarget = qInfo->ReqCreatureOrGOId[j];
14129 else
14130 continue;
14132 if ( reqTarget == entry )
14134 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
14135 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
14136 if ( curTalkCount < reqTalkCount )
14138 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
14139 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14141 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
14143 if ( CanCompleteQuest( questid ) )
14144 CompleteQuest( questid );
14146 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14147 continue;
14155 void Player::MoneyChanged( uint32 count )
14157 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14159 uint32 questid = GetQuestSlotQuestId(i);
14160 if (!questid)
14161 continue;
14163 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14164 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
14166 QuestStatusData& q_status = mQuestStatus[questid];
14168 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14170 if(int32(count) >= -qInfo->GetRewOrReqMoney())
14172 if ( CanCompleteQuest( questid ) )
14173 CompleteQuest( questid );
14176 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14178 if(int32(count) < -qInfo->GetRewOrReqMoney())
14179 IncompleteQuest( questid );
14185 void Player::ReputationChanged(FactionEntry const* factionEntry )
14187 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14189 if(uint32 questid = GetQuestSlotQuestId(i))
14191 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid))
14193 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
14195 QuestStatusData& q_status = mQuestStatus[questid];
14196 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14198 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
14199 if ( CanCompleteQuest( questid ) )
14200 CompleteQuest( questid );
14202 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14204 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
14205 IncompleteQuest( questid );
14213 bool Player::HasQuestForItem( uint32 itemid ) const
14215 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14217 uint32 questid = GetQuestSlotQuestId(i);
14218 if ( questid == 0 )
14219 continue;
14221 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
14222 if(qs_itr == mQuestStatus.end())
14223 continue;
14225 QuestStatusData const& q_status = qs_itr->second;
14227 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
14229 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
14230 if(!qinfo)
14231 continue;
14233 // hide quest if player is in raid-group and quest is no raid quest
14234 if (GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID
14235 && !InBattleGround())
14236 continue;
14238 // There should be no mixed ReqItem/ReqSource drop
14239 // This part for ReqItem drop
14240 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
14242 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
14243 return true;
14245 // This part - for ReqSource
14246 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
14248 // examined item is a source item
14249 if (qinfo->ReqSourceId[j] == itemid)
14251 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(itemid);
14253 // 'unique' item
14254 if (pProto->MaxCount && (int32)GetItemCount(itemid,true) < pProto->MaxCount)
14255 return true;
14257 // allows custom amount drop when not 0
14258 if (qinfo->ReqSourceCount[j])
14260 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
14261 return true;
14262 } else if ((int32)GetItemCount(itemid,true) < pProto->Stackable)
14263 return true;
14268 return false;
14271 void Player::SendQuestComplete( uint32 quest_id )
14273 if( quest_id )
14275 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
14276 data << uint32(quest_id);
14277 GetSession()->SendPacket( &data );
14278 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
14282 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
14284 uint32 questid = pQuest->GetQuestId();
14285 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
14286 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
14287 data << uint32(questid);
14289 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
14291 data << uint32(XP);
14292 data << uint32(pQuest->GetRewOrReqMoney());
14294 else
14296 data << uint32(0);
14297 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
14300 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorAddition()));
14301 data << uint32(pQuest->GetBonusTalents()); // bonus talents
14302 data << uint32(0);
14303 GetSession()->SendPacket( &data );
14305 if (pQuest->GetQuestCompleteScript() != 0)
14306 GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
14309 void Player::SendQuestFailed( uint32 quest_id )
14311 if( quest_id )
14313 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
14314 data << uint32(quest_id);
14315 data << uint32(0); // failed reason (4 for inventory is full)
14316 GetSession()->SendPacket( &data );
14317 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
14321 void Player::SendQuestTimerFailed( uint32 quest_id )
14323 if( quest_id )
14325 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
14326 data << uint32(quest_id);
14327 GetSession()->SendPacket( &data );
14328 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
14332 void Player::SendCanTakeQuestResponse( uint32 msg )
14334 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
14335 data << uint32(msg);
14336 GetSession()->SendPacket( &data );
14337 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
14340 void Player::SendQuestConfirmAccept(const Quest* pQuest, Player* pReceiver)
14342 if (pReceiver)
14344 std::string strTitle = pQuest->GetTitle();
14346 int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
14348 if (loc_idx >= 0)
14350 if (const QuestLocale* pLocale = sObjectMgr.GetQuestLocale(pQuest->GetQuestId()))
14352 if ((int32)pLocale->Title.size() > loc_idx && !pLocale->Title[loc_idx].empty())
14353 strTitle = pLocale->Title[loc_idx];
14357 WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8));
14358 data << uint32(pQuest->GetQuestId());
14359 data << strTitle;
14360 data << uint64(GetGUID());
14361 pReceiver->GetSession()->SendPacket(&data);
14363 sLog.outDebug("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
14367 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
14369 if( pPlayer )
14371 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
14372 data << uint64(pPlayer->GetGUID());
14373 data << uint8(msg); // valid values: 0-8
14374 GetSession()->SendPacket( &data );
14375 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
14379 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
14381 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
14382 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
14383 //data << pQuest->ReqItemId[item_idx];
14384 //data << count;
14385 GetSession()->SendPacket( &data );
14388 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
14390 assert(old_count + add_count < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
14392 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
14393 if (entry < 0)
14394 // client expected gameobject template id in form (id|0x80000000)
14395 entry = (-entry) | 0x80000000;
14397 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
14398 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
14399 data << uint32(pQuest->GetQuestId());
14400 data << uint32(entry);
14401 data << uint32(old_count + add_count);
14402 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
14403 data << uint64(guid);
14404 GetSession()->SendPacket(&data);
14406 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
14407 if( log_slot < MAX_QUEST_LOG_SIZE)
14408 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
14411 /*********************************************************/
14412 /*** LOAD SYSTEM ***/
14413 /*********************************************************/
14415 void Player::_LoadDeclinedNames(QueryResult* result)
14417 if(!result)
14418 return;
14420 if(m_declinedname)
14421 delete m_declinedname;
14423 m_declinedname = new DeclinedName;
14424 Field *fields = result->Fetch();
14425 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
14426 m_declinedname->name[i] = fields[i].GetCppString();
14428 delete result;
14431 void Player::_LoadArenaTeamInfo(QueryResult *result)
14433 // arenateamid, played_week, played_season, personal_rating
14434 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
14435 if (!result)
14436 return;
14440 Field *fields = result->Fetch();
14442 uint32 arenateamid = fields[0].GetUInt32();
14443 uint32 played_week = fields[1].GetUInt32();
14444 uint32 played_season = fields[2].GetUInt32();
14445 uint32 wons_season = fields[3].GetUInt32();
14446 uint32 personal_rating = fields[4].GetUInt32();
14448 ArenaTeam* aTeam = sObjectMgr.GetArenaTeamById(arenateamid);
14449 if(!aTeam)
14451 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid);
14452 continue;
14454 uint8 arenaSlot = aTeam->GetSlot();
14456 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_ID, arenateamid);
14457 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_TYPE, aTeam->GetType());
14458 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_MEMBER, (aTeam->GetCaptain() == GetGUID()) ? 0 : 1);
14459 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_WEEK, played_week);
14460 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_SEASON, played_season);
14461 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_WINS_SEASON, wons_season);
14462 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_PERSONAL_RATING, personal_rating);
14464 } while (result->NextRow());
14465 delete result;
14468 void Player::_LoadEquipmentSets(QueryResult *result)
14470 // 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));
14471 if (!result)
14472 return;
14474 uint32 count = 0;
14477 Field *fields = result->Fetch();
14479 EquipmentSet eqSet;
14481 eqSet.Guid = fields[0].GetUInt64();
14482 uint32 index = fields[1].GetUInt32();
14483 eqSet.Name = fields[2].GetCppString();
14484 eqSet.IconName = fields[3].GetCppString();
14485 eqSet.state = EQUIPMENT_SET_UNCHANGED;
14487 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
14488 eqSet.Items[i] = fields[4+i].GetUInt32();
14490 m_EquipmentSets[index] = eqSet;
14492 ++count;
14494 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
14495 break;
14496 } while (result->NextRow());
14497 delete result;
14500 void Player::_LoadBGData(QueryResult* result)
14502 if (!result)
14503 return;
14505 // Expecting only one row
14506 Field *fields = result->Fetch();
14507 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
14508 m_bgData.bgInstanceID = fields[0].GetUInt32();
14509 m_bgData.bgTeam = fields[1].GetUInt32();
14510 m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
14511 fields[2].GetFloat(), // X
14512 fields[3].GetFloat(), // Y
14513 fields[4].GetFloat(), // Z
14514 fields[5].GetFloat()); // Orientation
14515 m_bgData.taxiPath[0] = fields[7].GetUInt32();
14516 m_bgData.taxiPath[1] = fields[8].GetUInt32();
14517 m_bgData.mountSpell = fields[9].GetUInt32();
14519 delete result;
14522 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
14524 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
14525 if(!result)
14526 return false;
14528 Field *fields = result->Fetch();
14530 x = fields[0].GetFloat();
14531 y = fields[1].GetFloat();
14532 z = fields[2].GetFloat();
14533 o = fields[3].GetFloat();
14534 mapid = fields[4].GetUInt32();
14535 in_flight = !fields[5].GetCppString().empty();
14537 delete result;
14538 return true;
14541 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
14543 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
14544 if( !result )
14545 return false;
14547 Field *fields = result->Fetch();
14549 data = StrSplit(fields[0].GetCppString(), " ");
14551 delete result;
14553 return true;
14556 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
14558 if(index >= data.size())
14559 return 0;
14561 return (uint32)atoi(data[index].c_str());
14564 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
14566 float result;
14567 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
14568 memcpy(&result, &temp, sizeof(result));
14570 return result;
14573 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14575 Tokens data;
14576 if(!LoadValuesArrayFromDB(data,guid))
14577 return 0;
14579 return GetUInt32ValueFromArray(data,index);
14582 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14584 float result;
14585 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14586 memcpy(&result, &temp, sizeof(result));
14588 return result;
14591 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14593 // 0 1 2 3 4 5 6 7 8 9 10 11 12
14594 //SELECT guid, account, data, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags,"
14595 // 13 14 15 16 17 18 19 20 21 22 23 24 25
14596 //"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost,"
14597 // 26 27 28 29 30 31 32 33 34 35 36 37 38 39
14598 //"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,"
14599 // 40 41 42 43 44 45 46 47 48 49 50
14600 //"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk,"
14601 // 51 52 53 54 55 56 57 58 59 60
14602 //"health, power1, power2, power3, power4, power5, power6, power7, specCount, activeSpec FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid));
14603 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14605 if(!result)
14607 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14608 return false;
14611 Field *fields = result->Fetch();
14613 uint32 dbAccountId = fields[1].GetUInt32();
14615 // check if the character's account in the db and the logged in account match.
14616 // player should be able to load/delete character only with correct account!
14617 if( dbAccountId != GetSession()->GetAccountId() )
14619 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14620 delete result;
14621 return false;
14624 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14626 m_name = fields[3].GetCppString();
14628 // check name limitations
14629 if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
14630 (GetSession()->GetSecurity() == SEC_PLAYER && sObjectMgr.IsReservedName(m_name)))
14632 delete result;
14633 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14634 return false;
14637 if(!LoadValues( fields[2].GetString()))
14639 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
14640 delete result;
14641 return false;
14644 // overwrite possible wrong/corrupted guid
14645 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14647 // overwrite some data fields
14648 uint32 bytes0 = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0xFF000000;
14649 bytes0 |= fields[4].GetUInt8(); // race
14650 bytes0 |= fields[5].GetUInt8() << 8; // class
14651 bytes0 |= fields[6].GetUInt8() << 16; // gender
14652 SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
14654 SetUInt32Value(UNIT_FIELD_LEVEL, fields[7].GetUInt8());
14655 SetUInt32Value(PLAYER_XP, fields[8].GetUInt32());
14657 uint32 money = fields[9].GetUInt32();
14658 if(money > MAX_MONEY_AMOUNT)
14659 money = MAX_MONEY_AMOUNT;
14660 SetMoney(money);
14662 SetUInt32Value(PLAYER_BYTES, fields[10].GetUInt32());
14663 SetUInt32Value(PLAYER_BYTES_2, fields[11].GetUInt32());
14664 SetUInt32Value(PLAYER_BYTES_3, (fields[50].GetUInt16() & 0xFFFE) | fields[6].GetUInt8());
14665 SetUInt32Value(PLAYER_FLAGS, fields[12].GetUInt32());
14666 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[49].GetInt32());
14668 SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES, fields[48].GetUInt64());
14671 InitDisplayIds();
14673 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14674 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14676 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
14677 SetVisibleItemSlot(slot, NULL);
14679 if (m_items[slot])
14681 delete m_items[slot];
14682 m_items[slot] = NULL;
14686 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14687 outDebugValues();
14689 //Need to call it to initialize m_team (m_team can be calculated from race)
14690 //Other way is to saves m_team into characters table.
14691 setFactionForRace(getRace());
14692 SetCharm(NULL);
14694 // load home bind and check in same time class/race pair, it used later for restore broken positions
14695 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14697 delete result;
14698 return false;
14701 InitPrimaryProfessions(); // to max set before any spell loaded
14703 // init saved position, and fix it later if problematic
14704 uint32 transGUID = fields[31].GetUInt32();
14705 Relocate(fields[13].GetFloat(),fields[14].GetFloat(),fields[15].GetFloat(),fields[17].GetFloat());
14706 SetLocationMapId(fields[16].GetUInt32());
14708 uint32 difficulty = fields[39].GetUInt32();
14709 if(difficulty >= MAX_DUNGEON_DIFFICULTY)
14710 difficulty = DUNGEON_DIFFICULTY_NORMAL;
14711 SetDungeonDifficulty(Difficulty(difficulty)); // may be changed in _LoadGroup
14713 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14715 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14717 uint32 arena_currency = fields[40].GetUInt32();
14718 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
14719 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14721 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14723 // check arena teams integrity
14724 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14726 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14727 if(!arena_team_id)
14728 continue;
14730 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(arena_team_id))
14731 if(at->HaveMember(GetGUID()))
14732 continue;
14734 // arena team not exist or not member, cleanup fields
14735 for(int j = 0; j < ARENA_TEAM_END; ++j)
14736 SetArenaTeamInfoField(arena_slot, ArenaTeamInfoType(j), 0);
14739 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, fields[41].GetUInt32());
14740 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, fields[42].GetUInt32());
14741 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, fields[43].GetUInt32());
14742 SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, fields[44].GetUInt32());
14743 SetUInt16Value(PLAYER_FIELD_KILLS, 0, fields[45].GetUInt16());
14744 SetUInt16Value(PLAYER_FIELD_KILLS, 1, fields[46].GetUInt16());
14746 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14748 if(!IsPositionValid())
14750 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());
14751 RelocateToHomebind();
14753 transGUID = 0;
14755 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
14758 _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
14760 if(m_bgData.bgInstanceID) //saved in BattleGround
14762 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
14764 bool player_at_bg = currentBg && currentBg->IsPlayerInBattleGround(GetGUID());
14766 if(player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE)
14768 BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14769 AddBattleGroundQueueId(bgQueueTypeId);
14771 m_bgData.bgTypeID = currentBg->GetTypeID();
14773 //join player to battleground group
14774 currentBg->EventPlayerLoggedIn(this, GetGUID());
14775 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData.bgTeam);
14777 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14779 else
14781 // leave bg
14782 if (player_at_bg)
14783 currentBg->RemovePlayerAtLeave(GetGUID(), false, true);
14785 // move to bg enter point
14786 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14787 SetLocationMapId(_loc.mapid);
14788 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14790 // We are not in BG anymore
14791 m_bgData.bgInstanceID = 0;
14794 else
14796 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14797 // if server restart after player save in BG or area
14798 // player can have current coordinates in to BG/Arena map, fix this
14799 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14801 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14802 SetLocationMapId(_loc.mapid);
14803 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14807 if (transGUID != 0)
14809 m_movementInfo.SetTransportData(transGUID, fields[27].GetFloat(), fields[28].GetFloat(), fields[29].GetFloat(), fields[30].GetFloat(), 0, -1);
14811 if( !MaNGOS::IsValidMapCoord(
14812 GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
14813 GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o) ||
14814 // transport size limited
14815 m_movementInfo.GetTransportPos()->x > 50 || m_movementInfo.GetTransportPos()->y > 50 || m_movementInfo.GetTransportPos()->z > 50 )
14817 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14818 guid, GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
14819 GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o);
14821 RelocateToHomebind();
14823 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
14825 transGUID = 0;
14829 if (transGUID != 0)
14831 for (MapManager::TransportSet::const_iterator iter = sMapMgr.m_Transports.begin(); iter != sMapMgr.m_Transports.end(); ++iter)
14833 if( (*iter)->GetGUIDLow() == transGUID)
14835 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14836 // client without expansion support
14837 if(GetSession()->Expansion() < transMapEntry->Expansion())
14839 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14840 break;
14843 m_transport = *iter;
14844 m_transport->AddPassenger(this);
14845 SetLocationMapId(m_transport->GetMapId());
14846 break;
14850 if(!m_transport)
14852 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14853 guid,transGUID);
14855 RelocateToHomebind();
14857 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
14859 transGUID = 0;
14862 else // not transport case
14864 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14865 // client without expansion support
14866 if(GetSession()->Expansion() < mapEntry->Expansion())
14868 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14869 RelocateToHomebind();
14873 // NOW player must have valid map
14874 // load the player's map here if it's not already loaded
14875 SetMap(sMapMgr.CreateMap(GetMapId(), this));
14877 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14878 if(GetInstanceId() && !sInstanceSaveMgr.GetInstanceSave(GetInstanceId()))
14880 AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(GetMapId());
14881 if(at)
14882 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14883 else
14884 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());
14887 SaveRecallPosition();
14889 time_t now = time(NULL);
14890 time_t logoutTime = time_t(fields[23].GetUInt64());
14892 // since last logout (in seconds)
14893 uint64 time_diff = uint64(now - logoutTime);
14895 // set value, including drunk invisibility detection
14896 // calculate sobering. after 15 minutes logged out, the player will be sober again
14897 float soberFactor;
14898 if(time_diff > 15*MINUTE)
14899 soberFactor = 0;
14900 else
14901 soberFactor = 1-time_diff/(15.0f*MINUTE);
14902 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14903 SetDrunkValue(newDrunkenValue);
14905 m_rest_bonus = fields[22].GetFloat();
14906 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14907 float bubble0 = 0.031f;
14908 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14909 float bubble1 = 0.125f;
14911 if(time_diff > 0)
14913 float bubble = fields[24].GetUInt32() > 0
14914 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14915 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14917 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14920 m_cinematic = fields[19].GetUInt32();
14921 m_Played_time[PLAYED_TIME_TOTAL]= fields[20].GetUInt32();
14922 m_Played_time[PLAYED_TIME_LEVEL]= fields[21].GetUInt32();
14924 m_resetTalentsCost = fields[25].GetUInt32();
14925 m_resetTalentsTime = time_t(fields[26].GetUInt64());
14927 // reserve some flags
14928 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14930 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14931 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14933 m_taxi.LoadTaxiMask( fields[18].GetString() ); // must be before InitTaxiNodesForLevel
14935 uint32 extraflags = fields[32].GetUInt32();
14937 m_stableSlots = fields[33].GetUInt32();
14938 if(m_stableSlots > MAX_PET_STABLES)
14940 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14941 m_stableSlots = MAX_PET_STABLES;
14944 m_atLoginFlags = fields[34].GetUInt32();
14946 // Honor system
14947 // Update Honor kills data
14948 m_lastHonorUpdateTime = logoutTime;
14949 UpdateHonorFields();
14951 m_deathExpireTime = (time_t)fields[37].GetUInt64();
14952 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14953 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14955 std::string taxi_nodes = fields[38].GetCppString();
14957 // clear channel spell data (if saved at channel spell casting)
14958 SetChannelObjectGUID(0);
14959 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14961 // clear charm/summon related fields
14962 SetCharm(NULL);
14963 SetPet(NULL);
14964 SetTargetGUID(0);
14965 SetChannelObjectGUID(0);
14966 SetCharmerGUID(0);
14967 SetOwnerGUID(0);
14968 SetCreatorGUID(0);
14970 // reset some aura modifiers before aura apply
14971 SetFarSightGUID(0);
14972 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14973 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14975 // cleanup aura list explicitly before skill load wher some spells can be applied
14976 RemoveAllAuras();
14978 // make sure the unit is considered out of combat for proper loading
14979 ClearInCombat();
14981 // make sure the unit is considered not in duel for proper loading
14982 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14983 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14985 // reset stats before loading any modifiers
14986 InitStatsForLevel();
14987 InitGlyphsForLevel();
14988 InitTaxiNodesForLevel();
14989 InitRunes();
14991 // load skills after InitStatsForLevel because it triggering aura apply also
14992 _LoadSkills(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS));
14994 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14996 // Mail
14997 _LoadMail();
14999 m_specsCount = fields[59].GetUInt8();
15000 m_activeSpec = fields[60].GetUInt8();
15002 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
15003 _LoadGlyphAuras();
15005 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
15006 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
15007 m_deathState = DEAD;
15009 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
15011 // after spell load, learn rewarded spell if need also
15012 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
15013 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
15015 // after spell and quest load
15016 InitTalentForLevel();
15017 learnDefaultSpells();
15019 // must be before inventory (some items required reputation check)
15020 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
15022 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
15024 // update items with duration and realtime
15025 UpdateItemDuration(time_diff, true);
15027 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
15029 // unread mails and next delivery time, actual mails not loaded
15030 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
15032 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
15034 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
15035 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
15036 uint32 curTitle = fields[47].GetUInt32();
15037 if (curTitle && !HasTitle(curTitle))
15038 curTitle = 0;
15040 SetUInt32Value(PLAYER_CHOSEN_TITLE, curTitle);
15042 // Not finish taxi flight path
15043 if(m_bgData.HasTaxiPath())
15045 m_taxi.ClearTaxiDestinations();
15046 for (int i = 0; i < 2; ++i)
15047 m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
15049 else if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
15051 // problems with taxi path loading
15052 TaxiNodesEntry const* nodeEntry = NULL;
15053 if(uint32 node_id = m_taxi.GetTaxiSource())
15054 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
15056 if(!nodeEntry) // don't know taxi start node, to homebind
15058 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
15059 RelocateToHomebind();
15061 else // have start node, to it
15063 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
15064 SetLocationMapId(nodeEntry->map_id);
15065 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
15068 //we can be relocated from taxi and still have an outdated Map pointer!
15069 //so we need to get a new Map pointer!
15070 SetMap(sMapMgr.CreateMap(GetMapId(), this));
15071 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
15073 m_taxi.ClearTaxiDestinations();
15076 if(uint32 node_id = m_taxi.GetTaxiSource())
15078 // save source node as recall coord to prevent recall and fall from sky
15079 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
15080 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
15081 m_recallMap = nodeEntry->map_id;
15082 m_recallX = nodeEntry->x;
15083 m_recallY = nodeEntry->y;
15084 m_recallZ = nodeEntry->z;
15086 // flight will started later
15089 // has to be called after last Relocate() in Player::LoadFromDB
15090 SetFallInformation(0, GetPositionZ());
15092 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
15094 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
15095 // Do now before stats re-calculation cleanup for ghost state unexpected auras
15096 if(!isAlive())
15097 RemoveAllAurasOnDeath();
15099 //apply all stat bonuses from items and auras
15100 SetCanModifyStats(true);
15101 UpdateAllStats();
15103 // restore remembered power/health values (but not more max values)
15104 uint32 savedhealth = fields[51].GetUInt32();
15105 SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth);
15106 for(uint32 i = 0; i < MAX_POWERS; ++i)
15108 uint32 savedpower = fields[52+i].GetUInt32();
15109 SetPower(Powers(i),savedpower > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedpower);
15112 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
15113 outDebugValues();
15115 // all fields read
15116 delete result;
15118 // GM state
15119 if(GetSession()->GetSecurity() > SEC_PLAYER)
15121 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
15123 default:
15124 case 0: break; // disable
15125 case 1: SetGameMaster(true); break; // enable
15126 case 2: // save state
15127 if(extraflags & PLAYER_EXTRA_GM_ON)
15128 SetGameMaster(true);
15129 break;
15132 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
15134 default:
15135 case 0: SetGMVisible(false); break; // invisible
15136 case 1: break; // visible
15137 case 2: // save state
15138 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
15139 SetGMVisible(false);
15140 break;
15143 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
15145 default:
15146 case 0: break; // disable
15147 case 1: SetAcceptTicket(true); break; // enable
15148 case 2: // save state
15149 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
15150 SetAcceptTicket(true);
15151 break;
15154 switch(sWorld.getConfig(CONFIG_GM_CHAT))
15156 default:
15157 case 0: break; // disable
15158 case 1: SetGMChat(true); break; // enable
15159 case 2: // save state
15160 if(extraflags & PLAYER_EXTRA_GM_CHAT)
15161 SetGMChat(true);
15162 break;
15165 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
15167 default:
15168 case 0: break; // disable
15169 case 1: SetAcceptWhispers(true); break; // enable
15170 case 2: // save state
15171 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
15172 SetAcceptWhispers(true);
15173 break;
15177 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
15179 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
15180 m_achievementMgr.CheckAllAchievementCriteria();
15182 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
15184 return true;
15187 bool Player::isAllowedToLoot(Creature* creature)
15189 if(Player* recipient = creature->GetLootRecipient())
15191 if (recipient == this)
15192 return true;
15193 if( Group* otherGroup = recipient->GetGroup())
15195 Group* thisGroup = GetGroup();
15196 if(!thisGroup)
15197 return false;
15198 return thisGroup == otherGroup;
15200 return false;
15202 else
15203 // prevent other players from looting if the recipient got disconnected
15204 return !creature->hasLootRecipient();
15207 void Player::_LoadActions(QueryResult *result)
15209 for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
15210 m_actionButtons[i].clear();
15212 //QueryResult *result = CharacterDatabase.PQuery("SELECT spec, button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
15214 if(result)
15218 Field *fields = result->Fetch();
15220 uint8 spec = fields[0].GetUInt8();
15221 uint8 button = fields[1].GetUInt8();
15222 uint32 action = fields[2].GetUInt32();
15223 uint8 type = fields[3].GetUInt8();
15225 if(ActionButton* ab = addActionButton(spec, button, action, type))
15226 ab->uState = ACTIONBUTTON_UNCHANGED;
15227 else
15229 sLog.outError( " ...at loading, and will deleted in DB also");
15231 // Will deleted in DB at next save (it can create data until save but marked as deleted)
15232 m_actionButtons[spec][button].uState = ACTIONBUTTON_DELETED;
15235 while( result->NextRow() );
15237 delete result;
15241 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
15243 //RemoveAllAuras(); -- some spells casted before aura load, for example in LoadSkills, aura list explcitly cleaned early
15245 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15247 if(result)
15251 Field *fields = result->Fetch();
15252 uint64 caster_guid = fields[0].GetUInt64();
15253 uint32 spellid = fields[1].GetUInt32();
15254 uint32 effindex = fields[2].GetUInt32();
15255 uint32 stackcount = fields[3].GetUInt32();
15256 int32 damage = fields[4].GetInt32();
15257 int32 maxduration = fields[5].GetInt32();
15258 int32 remaintime = fields[6].GetInt32();
15259 int32 remaincharges = fields[7].GetInt32();
15261 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
15262 if(!spellproto)
15264 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
15265 continue;
15268 if(effindex >= 3)
15270 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
15271 continue;
15274 // negative effects should continue counting down after logout
15275 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
15277 if (remaintime/IN_MILISECONDS <= int32(timediff))
15278 continue;
15280 remaintime -= timediff*IN_MILISECONDS;
15283 // prevent wrong values of remaincharges
15284 if(spellproto->procCharges)
15286 if(remaincharges <= 0 || remaincharges > (int32)spellproto->procCharges)
15287 remaincharges = spellproto->procCharges;
15289 else
15290 remaincharges = 0;
15293 for(uint32 i=0; i<stackcount; ++i)
15295 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
15296 if(!damage)
15297 damage = aura->GetModifier()->m_amount;
15299 // reset stolen single target auras
15300 if (caster_guid != GetGUID() && aura->IsSingleTarget())
15301 aura->SetIsSingleTarget(false);
15303 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
15304 AddAura(aura);
15305 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
15308 while( result->NextRow() );
15310 delete result;
15313 if(getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
15314 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
15317 void Player::_LoadGlyphAuras()
15319 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
15321 if (uint32 glyph = GetGlyph(i))
15323 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
15325 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
15327 if(gp->TypeFlags == gs->TypeFlags)
15329 CastSpell(this, gp->SpellId, true);
15330 continue;
15332 else
15333 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
15335 else
15336 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
15338 else
15339 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
15341 // On any error remove glyph
15342 SetGlyph(i, 0);
15347 void Player::LoadCorpse()
15349 if( isAlive() )
15351 sObjectAccessor.ConvertCorpseForPlayer(GetGUID());
15353 else
15355 if(Corpse *corpse = GetCorpse())
15357 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
15359 else
15361 //Prevent Dead Player login without corpse
15362 ResurrectPlayer(0.5f);
15367 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
15369 //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());
15370 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
15371 //NOTE: the "order by `bag`" is important because it makes sure
15372 //the bagMap is filled before items in the bags are loaded
15373 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
15374 //expected to be equipped before offhand items (TODO: fixme)
15376 uint32 zone = GetZoneId();
15378 if (result)
15380 std::list<Item*> problematicItems;
15382 // prevent items from being added to the queue when stored
15383 m_itemUpdateQueueBlocked = true;
15386 Field *fields = result->Fetch();
15387 uint32 bag_guid = fields[1].GetUInt32();
15388 uint8 slot = fields[2].GetUInt8();
15389 uint32 item_guid = fields[3].GetUInt32();
15390 uint32 item_id = fields[4].GetUInt32();
15392 ItemPrototype const * proto = ObjectMgr::GetItemPrototype(item_id);
15394 if(!proto)
15396 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15397 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
15398 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
15399 continue;
15402 Item *item = NewItemOrBag(proto);
15404 if(!item->LoadFromDB(item_guid, GetGUID(), result))
15406 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
15407 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15408 item->FSetState(ITEM_REMOVED);
15409 item->SaveToDB(); // it also deletes item object !
15410 continue;
15413 // not allow have in alive state item limited to another map/zone
15414 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
15416 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15417 item->FSetState(ITEM_REMOVED);
15418 item->SaveToDB(); // it also deletes item object !
15419 continue;
15422 // "Conjured items disappear if you are logged out for more than 15 minutes"
15423 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
15425 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15426 item->FSetState(ITEM_REMOVED);
15427 item->SaveToDB(); // it also deletes item object !
15428 continue;
15431 bool success = true;
15433 // the item/bag is not in a bag
15434 if (!bag_guid)
15436 item->SetContainer( NULL );
15437 item->SetSlot(slot);
15439 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
15441 ItemPosCountVec dest;
15442 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
15443 item = StoreItem(dest, item, true);
15444 else
15445 success = false;
15447 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
15449 uint16 dest;
15450 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
15451 QuickEquipItem(dest, item);
15452 else
15453 success = false;
15455 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
15457 ItemPosCountVec dest;
15458 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
15459 item = BankItem(dest, item, true);
15460 else
15461 success = false;
15464 if(success)
15466 // store bags that may contain items in them
15467 if(item->IsBag() && IsBagPos(item->GetPos()))
15468 bagMap[item_guid] = (Bag*)item;
15471 // the item/bag in a bag
15472 else
15474 item->SetSlot(NULL_SLOT);
15475 // the item is in a bag, find the bag
15476 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
15477 if(itr != bagMap.end() && slot < itr->second->GetBagSize())
15479 ItemPosCountVec dest;
15480 if( CanStoreItem( itr->second->GetSlot(), slot, dest, item, false ) == EQUIP_ERR_OK )
15481 item = StoreItem(dest, item, true);
15482 else
15483 success = false;
15485 else
15486 success = false;
15489 // item's state may have changed after stored
15490 if (success)
15491 item->SetState(ITEM_UNCHANGED, this);
15492 else
15494 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);
15495 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15496 problematicItems.push_back(item);
15498 } while (result->NextRow());
15500 delete result;
15501 m_itemUpdateQueueBlocked = false;
15503 // send by mail problematic items
15504 while(!problematicItems.empty())
15506 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
15508 // fill mail
15509 MailDraft draft(subject);
15511 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
15513 Item* item = problematicItems.front();
15514 problematicItems.pop_front();
15516 draft.AddItem(item);
15519 draft.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
15522 //if(isAlive())
15523 _ApplyAllItemMods();
15526 // load mailed item which should receive current player
15527 void Player::_LoadMailedItems(Mail *mail)
15529 // data needs to be at first place for Item::LoadFromDB
15530 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);
15531 if(!result)
15532 return;
15536 Field *fields = result->Fetch();
15537 uint32 item_guid_low = fields[1].GetUInt32();
15538 uint32 item_template = fields[2].GetUInt32();
15540 mail->AddItem(item_guid_low, item_template);
15542 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(item_template);
15544 if(!proto)
15546 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);
15547 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15548 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
15549 continue;
15552 Item *item = NewItemOrBag(proto);
15554 if(!item->LoadFromDB(item_guid_low, 0, result))
15556 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
15557 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15558 item->FSetState(ITEM_REMOVED);
15559 item->SaveToDB(); // it also deletes item object !
15560 continue;
15563 AddMItem(item);
15564 } while (result->NextRow());
15566 delete result;
15569 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
15571 //set a count of unread mails
15572 //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);
15573 if (resultUnread)
15575 Field *fieldMail = resultUnread->Fetch();
15576 unReadMails = fieldMail[0].GetUInt8();
15577 delete resultUnread;
15580 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
15581 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
15582 if (resultDelivery)
15584 Field *fieldMail = resultDelivery->Fetch();
15585 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
15586 delete resultDelivery;
15590 void Player::_LoadMail()
15592 m_mail.clear();
15593 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15594 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());
15595 if(result)
15599 Field *fields = result->Fetch();
15600 Mail *m = new Mail;
15601 m->messageID = fields[0].GetUInt32();
15602 m->messageType = fields[1].GetUInt8();
15603 m->sender = fields[2].GetUInt32();
15604 m->receiver = fields[3].GetUInt32();
15605 m->subject = fields[4].GetCppString();
15606 m->itemTextId = fields[5].GetUInt32();
15607 bool has_items = fields[6].GetBool();
15608 m->expire_time = (time_t)fields[7].GetUInt64();
15609 m->deliver_time = (time_t)fields[8].GetUInt64();
15610 m->money = fields[9].GetUInt32();
15611 m->COD = fields[10].GetUInt32();
15612 m->checked = fields[11].GetUInt32();
15613 m->stationery = fields[12].GetUInt8();
15614 m->mailTemplateId = fields[13].GetInt16();
15616 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15618 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15619 m->mailTemplateId = 0;
15622 m->state = MAIL_STATE_UNCHANGED;
15624 if (has_items)
15625 _LoadMailedItems(m);
15627 m_mail.push_back(m);
15628 } while( result->NextRow() );
15629 delete result;
15633 void Player::LoadPet()
15635 //fixme: the pet should still be loaded if the player is not in world
15636 // just not added to the map
15637 if(IsInWorld())
15639 Pet *pet = new Pet;
15640 if(!pet->LoadPetFromDB(this,0,0,true))
15641 delete pet;
15645 void Player::_LoadQuestStatus(QueryResult *result)
15647 mQuestStatus.clear();
15649 uint32 slot = 0;
15651 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15652 //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());
15654 if(result)
15658 Field *fields = result->Fetch();
15660 uint32 quest_id = fields[0].GetUInt32();
15661 // used to be new, no delete?
15662 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15663 if( pQuest )
15665 // find or create
15666 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15668 uint32 qstatus = fields[1].GetUInt32();
15669 if(qstatus < MAX_QUEST_STATUS)
15670 questStatusData.m_status = QuestStatus(qstatus);
15671 else
15673 questStatusData.m_status = QUEST_STATUS_NONE;
15674 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15677 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15678 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15680 time_t quest_time = time_t(fields[4].GetUInt64());
15682 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15684 AddTimedQuest( quest_id );
15686 if (quest_time <= sWorld.GetGameTime())
15687 questStatusData.m_timer = 1;
15688 else
15689 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
15691 else
15692 quest_time = 0;
15694 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15695 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15696 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15697 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15698 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15699 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15700 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15701 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15703 questStatusData.uState = QUEST_UNCHANGED;
15705 // add to quest log
15706 if (slot < MAX_QUEST_LOG_SIZE &&
15707 ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
15708 questStatusData.m_status == QUEST_STATUS_COMPLETE ||
15709 questStatusData.m_status == QUEST_STATUS_FAILED) &&
15710 (!questStatusData.m_rewarded || pQuest->IsRepeatable())))
15712 SetQuestSlot(slot, quest_id, quest_time);
15714 if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
15715 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
15717 if (questStatusData.m_status == QUEST_STATUS_FAILED)
15718 SetQuestSlotState(slot, QUEST_STATE_FAIL);
15720 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15721 if(questStatusData.m_creatureOrGOcount[idx])
15722 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
15724 ++slot;
15727 if(questStatusData.m_rewarded)
15729 // learn rewarded spell if unknown
15730 learnQuestRewardedSpells(pQuest);
15732 // set rewarded title if any
15733 if(pQuest->GetCharTitleId())
15735 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15736 SetTitle(titleEntry);
15739 if(pQuest->GetBonusTalents())
15740 m_questRewardTalentCount += pQuest->GetBonusTalents();
15743 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15746 while( result->NextRow() );
15748 delete result;
15751 // clear quest log tail
15752 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15753 SetQuestSlot(i, 0);
15756 void Player::_LoadDailyQuestStatus(QueryResult *result)
15758 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15759 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15761 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15763 if(result)
15765 uint32 quest_daily_idx = 0;
15769 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15771 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15772 break;
15775 Field *fields = result->Fetch();
15777 uint32 quest_id = fields[0].GetUInt32();
15779 // save _any_ from daily quest times (it must be after last reset anyway)
15780 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15782 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15783 if( !pQuest )
15784 continue;
15786 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15787 ++quest_daily_idx;
15789 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15791 while( result->NextRow() );
15793 delete result;
15796 m_DailyQuestChanged = false;
15799 void Player::_LoadSpells(QueryResult *result)
15801 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15803 if(result)
15807 Field *fields = result->Fetch();
15809 addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool());
15811 while( result->NextRow() );
15813 delete result;
15817 void Player::_LoadGroup(QueryResult *result)
15819 //QueryResult *result = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15820 if (result)
15822 uint32 groupId = (*result)[0].GetUInt32();
15823 delete result;
15825 if (Group* group = sObjectMgr.GetGroupById(groupId))
15827 uint8 subgroup = group->GetMemberGroup(GetGUID());
15828 SetGroup(group, subgroup);
15829 if (getLevel() >= LEVELREQUIREMENT_HEROIC)
15831 // the group leader may change the instance difficulty while the player is offline
15832 SetDungeonDifficulty(group->GetDungeonDifficulty());
15833 SetRaidDifficulty(group->GetRaidDifficulty());
15839 void Player::_LoadBoundInstances(QueryResult *result)
15841 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15842 m_boundInstances[i].clear();
15844 Group *group = GetGroup();
15846 //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));
15847 if(result)
15851 Field *fields = result->Fetch();
15852 bool perm = fields[1].GetBool();
15853 uint32 mapId = fields[2].GetUInt32();
15854 uint32 instanceId = fields[0].GetUInt32();
15855 uint8 difficulty = fields[3].GetUInt8();
15857 time_t resetTime = (time_t)fields[4].GetUInt64();
15858 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15859 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15860 // and in that case it is not used
15862 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15863 if(!mapEntry || !mapEntry->IsDungeon())
15865 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15866 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15867 continue;
15870 if(difficulty >= MAX_DIFFICULTY)
15872 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15873 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15874 continue;
15877 MapDifficulty const* mapDiff = GetMapDifficultyData(mapId,Difficulty(difficulty));
15878 if(!mapDiff)
15880 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15881 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15882 continue;
15885 if(!perm && group)
15887 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);
15888 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15889 continue;
15892 // since non permanent binds are always solo bind, they can always be reset
15893 InstanceSave *save = sInstanceSaveMgr.AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, !perm, true);
15894 if(save) BindToInstance(save, perm, true);
15895 } while(result->NextRow());
15896 delete result;
15900 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
15902 // some instances only have one difficulty
15903 MapDifficulty const* mapDiff = GetMapDifficultyData(mapid,difficulty);
15904 if(!mapDiff)
15905 return NULL;
15907 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15908 if(itr != m_boundInstances[difficulty].end())
15909 return &itr->second;
15910 else
15911 return NULL;
15914 void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
15916 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15917 UnbindInstance(itr, difficulty, unload);
15920 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
15922 if(itr != m_boundInstances[difficulty].end())
15924 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15925 itr->second.save->RemovePlayer(this); // save can become invalid
15926 m_boundInstances[difficulty].erase(itr++);
15930 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15932 if(save)
15934 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15935 if(bind.save)
15937 // update the save when the group kills a boss
15938 if(permanent != bind.perm || save != bind.save)
15939 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());
15941 else
15942 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15944 if(bind.save != save)
15946 if(bind.save) bind.save->RemovePlayer(this);
15947 save->AddPlayer(this);
15950 if(permanent) save->SetCanReset(false);
15952 bind.save = save;
15953 bind.perm = permanent;
15954 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());
15955 return &bind;
15957 else
15958 return NULL;
15961 void Player::SendRaidInfo()
15963 uint32 counter = 0;
15965 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15967 size_t p_counter = data.wpos();
15968 data << uint32(counter); // placeholder
15970 time_t now = time(NULL);
15972 for(int i = 0; i < MAX_DIFFICULTY; ++i)
15974 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15976 if(itr->second.perm)
15978 InstanceSave *save = itr->second.save;
15979 data << uint32(save->GetMapId()); // map id
15980 data << uint32(save->GetDifficulty()); // difficulty
15981 data << uint64(save->GetInstanceId()); // instance id
15982 data << uint8(1); // expired = 0
15983 data << uint8(0); // extended = 1
15984 data << uint32(save->GetResetTime() - now); // reset time
15985 ++counter;
15989 data.put<uint32>(p_counter, counter);
15990 GetSession()->SendPacket(&data);
15994 - called on every successful teleportation to a map
15996 void Player::SendSavedInstances()
15998 bool hasBeenSaved = false;
15999 WorldPacket data;
16001 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16003 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
16005 if(itr->second.perm) // only permanent binds are sent
16007 hasBeenSaved = true;
16008 break;
16013 //Send opcode 811. true or false means, whether you have current raid/heroic instances
16014 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
16015 data << uint32(hasBeenSaved);
16016 GetSession()->SendPacket(&data);
16018 if(!hasBeenSaved)
16019 return;
16021 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16023 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
16025 if(itr->second.perm)
16027 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
16028 data << uint32(itr->second.save->GetMapId());
16029 GetSession()->SendPacket(&data);
16035 /// convert the player's binds to the group
16036 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
16038 bool has_binds = false;
16039 bool has_solo = false;
16041 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
16042 assert(player_guid);
16044 // copy all binds to the group, when changing leader it's assumed the character
16045 // will not have any solo binds
16047 if(player)
16049 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16051 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
16053 has_binds = true;
16054 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
16055 // permanent binds are not removed
16056 if(!itr->second.perm)
16058 // increments itr in call
16059 player->UnbindInstance(itr, Difficulty(i), true);
16060 has_solo = true;
16062 else
16063 ++itr;
16068 // if the player's not online we don't know what binds it has
16069 if(!player || !group || has_binds)
16070 CharacterDatabase.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid));
16072 // the following should not get executed when changing leaders
16073 if(!player || has_solo)
16074 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
16077 bool Player::_LoadHomeBind(QueryResult *result)
16079 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
16080 if(!info)
16082 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
16083 return false;
16086 bool ok = false;
16087 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
16088 if (result)
16090 Field *fields = result->Fetch();
16091 m_homebindMapId = fields[0].GetUInt32();
16092 m_homebindZoneId = fields[1].GetUInt16();
16093 m_homebindX = fields[2].GetFloat();
16094 m_homebindY = fields[3].GetFloat();
16095 m_homebindZ = fields[4].GetFloat();
16096 delete result;
16098 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
16100 // accept saved data only for valid position (and non instanceable), and accessable
16101 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
16102 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
16104 ok = true;
16106 else
16107 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
16110 if(!ok)
16112 m_homebindMapId = info->mapId;
16113 m_homebindZoneId = info->zoneId;
16114 m_homebindX = info->positionX;
16115 m_homebindY = info->positionY;
16116 m_homebindZ = info->positionZ;
16118 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);
16121 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
16122 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
16124 return true;
16127 /*********************************************************/
16128 /*** SAVE SYSTEM ***/
16129 /*********************************************************/
16131 void Player::SaveToDB()
16133 // we should assure this: assert((m_nextSave != sWorld.getConfig(CONFIG_INTERVAL_SAVE)));
16134 // delay auto save at any saves (manual, in code, or autosave)
16135 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
16137 //lets allow only players in world to be saved
16138 if(IsBeingTeleportedFar())
16140 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
16141 return;
16144 // first save/honor gain after midnight will also update the player's honor fields
16145 UpdateHonorFields();
16147 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
16148 outDebugValues();
16150 CharacterDatabase.BeginTransaction();
16152 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
16154 std::string sql_name = m_name;
16155 CharacterDatabase.escape_string(sql_name);
16157 std::ostringstream ss;
16158 ss << "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
16159 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
16160 "taximask, online, cinematic, "
16161 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
16162 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
16163 "death_expire_time, taxi_path, arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, "
16164 "todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, health, power1, power2, power3, "
16165 "power4, power5, power6, power7, specCount, activeSpec) VALUES ("
16166 << GetGUIDLow() << ", "
16167 << GetSession()->GetAccountId() << ", '"
16168 << sql_name << "', "
16169 << (uint32)getRace() << ", "
16170 << (uint32)getClass() << ", "
16171 << (uint32)getGender() << ", "
16172 << getLevel() << ", "
16173 << GetUInt32Value(PLAYER_XP) << ", "
16174 << GetMoney() << ", "
16175 << GetUInt32Value(PLAYER_BYTES) << ", "
16176 << GetUInt32Value(PLAYER_BYTES_2) << ", "
16177 << GetUInt32Value(PLAYER_FLAGS) << ", ";
16179 if(!IsBeingTeleported())
16181 ss << GetMapId() << ", "
16182 << (uint32)GetDungeonDifficulty() << ", "
16183 << finiteAlways(GetPositionX()) << ", "
16184 << finiteAlways(GetPositionY()) << ", "
16185 << finiteAlways(GetPositionZ()) << ", "
16186 << finiteAlways(GetOrientation()) << ", '";
16188 else
16190 ss << GetTeleportDest().mapid << ", "
16191 << (uint32)GetDungeonDifficulty() << ", "
16192 << finiteAlways(GetTeleportDest().coord_x) << ", "
16193 << finiteAlways(GetTeleportDest().coord_y) << ", "
16194 << finiteAlways(GetTeleportDest().coord_z) << ", "
16195 << finiteAlways(GetTeleportDest().orientation) << ", '";
16198 uint16 i;
16199 for( i = 0; i < m_valuesCount; ++i )
16201 ss << GetUInt32Value(i) << " ";
16204 ss << "', ";
16206 ss << m_taxi << ", "; // string with TaxiMaskSize numbers
16208 ss << (IsInWorld() ? 1 : 0) << ", ";
16210 ss << m_cinematic << ", ";
16212 ss << m_Played_time[PLAYED_TIME_TOTAL] << ", ";
16213 ss << m_Played_time[PLAYED_TIME_LEVEL] << ", ";
16215 ss << finiteAlways(m_rest_bonus) << ", ";
16216 ss << (uint64)time(NULL) << ", ";
16217 ss << (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0) << ", ";
16218 //save, far from tavern/city
16219 //save, but in tavern/city
16220 ss << m_resetTalentsCost << ", ";
16221 ss << (uint64)m_resetTalentsTime << ", ";
16223 ss << finiteAlways(m_movementInfo.GetTransportPos()->x) << ", ";
16224 ss << finiteAlways(m_movementInfo.GetTransportPos()->y) << ", ";
16225 ss << finiteAlways(m_movementInfo.GetTransportPos()->z) << ", ";
16226 ss << finiteAlways(m_movementInfo.GetTransportPos()->o) << ", ";
16227 if (m_transport)
16228 ss << m_transport->GetGUIDLow();
16229 else
16230 ss << "0";
16231 ss << ", ";
16233 ss << m_ExtraFlags << ", ";
16235 ss << uint32(m_stableSlots) << ", "; // to prevent save uint8 as char
16237 ss << uint32(m_atLoginFlags) << ", ";
16239 ss << GetZoneId() << ", ";
16241 ss << (uint64)m_deathExpireTime << ", '";
16243 ss << m_taxi.SaveTaxiDestinationsToString() << "', ";
16245 ss << GetArenaPoints() << ", ";
16247 ss << GetHonorPoints() << ", ";
16249 ss << GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION) << ", ";
16251 ss << GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION) << ", ";
16253 ss << GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS) << ", ";
16255 ss << GetUInt16Value(PLAYER_FIELD_KILLS, 0) << ", ";
16257 ss << GetUInt16Value(PLAYER_FIELD_KILLS, 1) << ", ";
16259 ss << GetUInt32Value(PLAYER_CHOSEN_TITLE) << ", ";
16261 ss << GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES) << ", ";
16263 // FIXME: at this moment send to DB as unsigned, including unit32(-1)
16264 ss << GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX) << ", ";
16266 ss << (uint16)(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE) << ", ";
16268 ss << GetHealth();
16270 for(uint32 i = 0; i < MAX_POWERS; ++i)
16271 ss << "," << GetPower(Powers(i));
16273 ss << ", ";
16274 ss << uint32(m_specsCount) << ", ";
16275 ss << uint32(m_activeSpec);
16277 ss << ")";
16279 CharacterDatabase.Execute( ss.str().c_str() );
16281 if(m_mailsUpdated) //save mails only when needed
16282 _SaveMail();
16284 _SaveBGData();
16285 _SaveInventory();
16286 _SaveQuestStatus();
16287 _SaveDailyQuestStatus();
16288 _SaveSpells();
16289 _SaveSpellCooldowns();
16290 _SaveActions();
16291 _SaveAuras();
16292 _SaveSkills();
16293 m_achievementMgr.SaveToDB();
16294 m_reputationMgr.SaveToDB();
16295 _SaveEquipmentSets();
16296 GetSession()->SaveTutorialsData(); // changed only while character in game
16298 CharacterDatabase.CommitTransaction();
16300 // save pet (hunter pet level and experience and all type pets health/mana).
16301 if(Pet* pet = GetPet())
16302 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
16305 // fast save function for item/money cheating preventing - save only inventory and money state
16306 void Player::SaveInventoryAndGoldToDB()
16308 _SaveInventory();
16309 SaveGoldToDB();
16312 void Player::SaveGoldToDB()
16314 CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
16317 void Player::_SaveActions()
16319 for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
16321 for(ActionButtonList::iterator itr = m_actionButtons[i].begin(); itr != m_actionButtons[i].end(); )
16323 switch (itr->second.uState)
16325 case ACTIONBUTTON_NEW:
16326 CharacterDatabase.PExecute("INSERT INTO character_action (guid,spec, button,action,type) VALUES ('%u', '%u', '%u', '%u', '%u')",
16327 GetGUIDLow(), i, (uint32)itr->first, (uint32)itr->second.GetAction(), (uint32)itr->second.GetType() );
16328 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16329 ++itr;
16330 break;
16331 case ACTIONBUTTON_CHANGED:
16332 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' AND spec = '%u'",
16333 (uint32)itr->second.GetAction(), (uint32)itr->second.GetType(), GetGUIDLow(), (uint32)itr->first, i );
16334 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16335 ++itr;
16336 break;
16337 case ACTIONBUTTON_DELETED:
16338 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' AND button = '%u' AND spec = '%u'", GetGUIDLow(), (uint32)itr->first, i);
16339 m_actionButtons[i].erase(itr++);
16340 break;
16341 default:
16342 ++itr;
16343 break;
16349 void Player::_SaveAuras()
16351 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
16353 AuraMap const& auras = GetAuras();
16355 if (auras.empty())
16356 return;
16358 spellEffectPair lastEffectPair = auras.begin()->first;
16359 uint32 stackCounter = 1;
16361 /* copied following sql-code partly from achievementmgr */
16362 bool first_round = true;
16363 std::ostringstream ss;
16364 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
16366 if(itr == auras.end() || lastEffectPair != itr->first)
16368 AuraMap::const_iterator itr2 = itr;
16369 // save previous spellEffectPair to db
16370 itr2--;
16372 //skip all auras from spells that are passive
16373 //do not save single target auras (unless they were cast by the player)
16374 if (!itr2->second->IsPassive() && (itr2->second->GetCasterGUID() == GetGUID() || !itr2->second->IsSingleTarget()))
16376 if (first_round)
16378 ss << "INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges)VALUES ";
16379 first_round = false;
16381 // next new/changed record prefix
16382 else
16383 ss << ", ";
16385 ss << "("<< GetGUIDLow() << "," << itr2->second->GetCasterGUID() << ","
16386 << (uint32)itr2->second->GetId() << "," << (uint32)itr2->second->GetEffIndex() << ","
16387 << stackCounter << "," << itr2->second->GetModifier()->m_amount << ","
16388 <<int(itr2->second->GetAuraMaxDuration()) << "," << int(itr2->second->GetAuraDuration()) << ","
16389 << int(itr2->second->GetAuraCharges()) << ")";
16392 if(itr == auras.end())
16393 break;
16396 if (lastEffectPair == itr->first)
16397 stackCounter++;
16398 else
16400 lastEffectPair = itr->first;
16401 stackCounter = 1;
16405 // if something changed execute
16406 if (!first_round)
16407 CharacterDatabase.Execute( ss.str().c_str() );
16410 void Player::_SaveInventory()
16412 // force items in buyback slots to new state
16413 // and remove those that aren't already
16414 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
16416 Item *item = m_items[i];
16417 if (!item || item->GetState() == ITEM_NEW) continue;
16418 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16419 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
16420 m_items[i]->FSetState(ITEM_NEW);
16423 // update enchantment durations
16424 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
16426 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
16429 // if no changes
16430 if (m_itemUpdateQueue.empty()) return;
16432 // do not save if the update queue is corrupt
16433 bool error = false;
16434 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16436 Item *item = m_itemUpdateQueue[i];
16437 if(!item || item->GetState() == ITEM_REMOVED) continue;
16438 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
16440 if (test == NULL)
16442 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());
16443 error = true;
16445 else if (test != item)
16447 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());
16448 error = true;
16452 if (error)
16454 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
16455 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
16456 return;
16459 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16461 Item *item = m_itemUpdateQueue[i];
16462 if(!item) continue;
16464 Bag *container = item->GetContainer();
16465 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
16467 switch(item->GetState())
16469 case ITEM_NEW:
16470 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());
16471 break;
16472 case ITEM_CHANGED:
16473 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());
16474 break;
16475 case ITEM_REMOVED:
16476 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16477 break;
16478 case ITEM_UNCHANGED:
16479 break;
16482 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
16484 m_itemUpdateQueue.clear();
16487 void Player::_SaveMail()
16489 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
16491 Mail *m = (*itr);
16492 if (m->state == MAIL_STATE_CHANGED)
16494 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'",
16495 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
16496 if(m->removedItems.size())
16498 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
16499 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
16500 m->removedItems.clear();
16502 m->state = MAIL_STATE_UNCHANGED;
16504 else if (m->state == MAIL_STATE_DELETED)
16506 if (m->HasItems())
16507 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
16508 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
16509 if (m->itemTextId)
16510 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
16511 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
16512 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
16516 //deallocate deleted mails...
16517 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
16519 if ((*itr)->state == MAIL_STATE_DELETED)
16521 Mail* m = *itr;
16522 m_mail.erase(itr);
16523 delete m;
16524 itr = m_mail.begin();
16526 else
16527 ++itr;
16530 m_mailsUpdated = false;
16533 void Player::_SaveQuestStatus()
16535 // we don't need transactions here.
16536 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
16538 switch (i->second.uState)
16540 case QUEST_NEW :
16541 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
16542 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
16543 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]);
16544 break;
16545 case QUEST_CHANGED :
16546 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' ",
16547 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 );
16548 break;
16549 case QUEST_UNCHANGED:
16550 break;
16552 i->second.uState = QUEST_UNCHANGED;
16556 void Player::_SaveDailyQuestStatus()
16558 if(!m_DailyQuestChanged)
16559 return;
16561 m_DailyQuestChanged = false;
16563 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
16565 // we don't need transactions here.
16566 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
16567 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
16568 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
16569 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
16570 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
16574 void Player::_SaveSkills()
16576 // we don't need transactions here.
16577 for( SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); )
16579 if(itr->second.uState == SKILL_UNCHANGED)
16581 ++itr;
16582 continue;
16585 if(itr->second.uState == SKILL_DELETED)
16587 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), itr->first );
16588 mSkillStatus.erase(itr++);
16589 continue;
16592 uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos));
16593 uint16 value = SKILL_VALUE(valueData);
16594 uint16 max = SKILL_MAX(valueData);
16596 switch (itr->second.uState)
16598 case SKILL_NEW:
16599 CharacterDatabase.PExecute("INSERT INTO character_skills (guid, skill, value, max) VALUES ('%u', '%u', '%u', '%u')",
16600 GetGUIDLow(), itr->first, value, max);
16601 break;
16602 case SKILL_CHANGED:
16603 CharacterDatabase.PExecute("UPDATE character_skills SET value = '%u',max = '%u'WHERE guid = '%u' AND skill = '%u' ",
16604 value, max, GetGUIDLow(), itr->first );
16605 break;
16607 itr->second.uState = SKILL_UNCHANGED;
16609 ++itr;
16613 void Player::_SaveSpells()
16615 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
16617 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
16618 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
16620 // add only changed/new not dependent spells
16621 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
16622 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);
16624 if (itr->second->state == PLAYERSPELL_REMOVED)
16626 delete itr->second;
16627 m_spells.erase(itr++);
16629 else
16631 itr->second->state = PLAYERSPELL_UNCHANGED;
16632 ++itr;
16638 void Player::outDebugValues() const
16640 if(!sLog.IsOutDebug()) // optimize disabled debug output
16641 return;
16643 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
16644 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
16645 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
16646 sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
16647 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
16648 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
16649 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
16650 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
16651 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
16652 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
16653 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
16654 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
16657 /*********************************************************/
16658 /*** FLOOD FILTER SYSTEM ***/
16659 /*********************************************************/
16661 void Player::UpdateSpeakTime()
16663 // ignore chat spam protection for GMs in any mode
16664 if(GetSession()->GetSecurity() > SEC_PLAYER)
16665 return;
16667 time_t current = time (NULL);
16668 if(m_speakTime > current)
16670 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
16671 if(!max_count)
16672 return;
16674 ++m_speakCount;
16675 if(m_speakCount >= max_count)
16677 // prevent overwrite mute time, if message send just before mutes set, for example.
16678 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
16679 if(GetSession()->m_muteTime < new_mute)
16680 GetSession()->m_muteTime = new_mute;
16682 m_speakCount = 0;
16685 else
16686 m_speakCount = 0;
16688 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
16691 bool Player::CanSpeak() const
16693 return GetSession()->m_muteTime <= time (NULL);
16696 /*********************************************************/
16697 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16698 /*********************************************************/
16700 void Player::SendAttackSwingNotInRange()
16702 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16703 GetSession()->SendPacket( &data );
16706 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16708 std::ostringstream ss;
16709 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16710 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16711 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16712 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16713 sLog.outDebug("%s", ss.str().c_str());
16714 CharacterDatabase.Execute(ss.str().c_str());
16717 void Player::SaveDataFieldToDB()
16719 std::ostringstream ss;
16720 ss<<"UPDATE characters SET data='";
16722 for(uint16 i = 0; i < m_valuesCount; ++i )
16724 ss << GetUInt32Value(i) << " ";
16726 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16728 CharacterDatabase.Execute(ss.str().c_str());
16731 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16733 std::ostringstream ss2;
16734 ss2 << "UPDATE characters SET data='";
16735 int i = 0;
16736 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16738 ss2 << tokens[i] << " ";
16740 ss2 << "' WHERE guid='" << GUID_LOPART(guid) << "'";
16742 return CharacterDatabase.Execute(ss2.str().c_str());
16745 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16747 char buf[11];
16748 snprintf(buf,11,"%u",value);
16750 if(index >= tokens.size())
16751 return;
16753 tokens[index] = buf;
16756 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16758 Tokens tokens;
16759 if(!LoadValuesArrayFromDB(tokens,guid))
16760 return;
16762 if(index >= tokens.size())
16763 return;
16765 char buf[11];
16766 snprintf(buf,11,"%u",value);
16767 tokens[index] = buf;
16769 SaveValuesArrayInDB(tokens,guid);
16772 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16774 uint32 temp;
16775 memcpy(&temp, &value, sizeof(value));
16776 Player::SetUInt32ValueInDB(index, temp, guid);
16779 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16781 // 0
16782 QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
16783 if(!result)
16784 return;
16786 Field* fields = result->Fetch();
16788 uint32 player_bytes2 = fields[0].GetUInt32();
16789 player_bytes2 &= ~0xFF;
16790 player_bytes2 |= facialHair;
16792 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));
16794 delete result;
16797 void Player::SendAttackSwingDeadTarget()
16799 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16800 GetSession()->SendPacket( &data );
16803 void Player::SendAttackSwingCantAttack()
16805 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16806 GetSession()->SendPacket( &data );
16809 void Player::SendAttackSwingCancelAttack()
16811 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16812 GetSession()->SendPacket( &data );
16815 void Player::SendAttackSwingBadFacingAttack()
16817 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16818 GetSession()->SendPacket( &data );
16821 void Player::SendAutoRepeatCancel(Unit *target)
16823 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
16824 data.append(target->GetPackGUID()); // may be it's target guid
16825 GetSession()->SendPacket( &data );
16828 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16830 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16831 data << uint32(Area);
16832 data << uint32(Experience);
16833 GetSession()->SendPacket(&data);
16836 void Player::SendDungeonDifficulty(bool IsInGroup)
16838 uint8 val = 0x00000001;
16839 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16840 data << uint32(GetDungeonDifficulty());
16841 data << uint32(val);
16842 data << uint32(IsInGroup);
16843 GetSession()->SendPacket(&data);
16846 void Player::SendRaidDifficulty(bool IsInGroup)
16848 uint8 val = 0x00000001;
16849 WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
16850 data << uint32(GetRaidDifficulty());
16851 data << uint32(val);
16852 data << uint32(IsInGroup);
16853 GetSession()->SendPacket(&data);
16856 void Player::SendResetFailedNotify(uint32 mapid)
16858 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16859 data << uint32(mapid);
16860 GetSession()->SendPacket(&data);
16863 /// Reset all solo instances and optionally send a message on success for each
16864 void Player::ResetInstances(uint8 method, bool isRaid)
16866 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16868 // we assume that when the difficulty changes, all instances that can be reset will be
16869 Difficulty diff = GetDifficulty(isRaid);
16871 for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
16873 InstanceSave *p = itr->second.save;
16874 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16875 if(!entry || entry->IsRaid() != isRaid || !p->CanReset())
16877 ++itr;
16878 continue;
16881 if(method == INSTANCE_RESET_ALL)
16883 // the "reset all instances" method can only reset normal maps
16884 if(entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
16886 ++itr;
16887 continue;
16891 // if the map is loaded, reset it
16892 Map *map = sMapMgr.FindMap(p->GetMapId(), p->GetInstanceId());
16893 if(map && map->IsDungeon())
16894 ((InstanceMap*)map)->Reset(method);
16896 // since this is a solo instance there should not be any players inside
16897 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16898 SendResetInstanceSuccess(p->GetMapId());
16900 p->DeleteFromDB();
16901 m_boundInstances[diff].erase(itr++);
16903 // the following should remove the instance save from the manager and delete it as well
16904 p->RemovePlayer(this);
16908 void Player::SendResetInstanceSuccess(uint32 MapId)
16910 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16911 data << uint32(MapId);
16912 GetSession()->SendPacket(&data);
16915 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16917 // TODO: find what other fail reasons there are besides players in the instance
16918 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16919 data << uint32(reason);
16920 data << uint32(MapId);
16921 GetSession()->SendPacket(&data);
16924 /*********************************************************/
16925 /*** Update timers ***/
16926 /*********************************************************/
16928 ///checks the 15 afk reports per 5 minutes limit
16929 void Player::UpdateAfkReport(time_t currTime)
16931 if(m_bgData.bgAfkReportedTimer <= currTime)
16933 m_bgData.bgAfkReportedCount = 0;
16934 m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
16938 void Player::UpdateContestedPvP(uint32 diff)
16940 if(!m_contestedPvPTimer||isInCombat())
16941 return;
16942 if(m_contestedPvPTimer <= diff)
16944 ResetContestedPvP();
16946 else
16947 m_contestedPvPTimer -= diff;
16950 void Player::UpdatePvPFlag(time_t currTime)
16952 if(!IsPvP())
16953 return;
16954 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16955 return;
16957 UpdatePvP(false);
16960 void Player::UpdateDuelFlag(time_t currTime)
16962 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16963 return;
16965 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16966 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16968 duel->startTimer = 0;
16969 duel->startTime = currTime;
16970 duel->opponent->duel->startTimer = 0;
16971 duel->opponent->duel->startTime = currTime;
16974 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16976 if(!pet)
16977 pet = GetPet();
16979 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16980 return;
16982 // not save secondary permanent pet as current
16983 if (pet && m_temporaryUnsummonedPetNumber != pet->GetCharmInfo()->GetPetNumber() && mode == PET_SAVE_AS_CURRENT)
16984 mode = PET_SAVE_NOT_IN_SLOT;
16986 if(returnreagent && pet && mode != PET_SAVE_AS_CURRENT)
16988 //returning of reagents only for players, so best done here
16989 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16990 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16992 if(spellInfo)
16994 for(uint32 i = 0; i < 7; ++i)
16996 if(spellInfo->Reagent[i] > 0)
16998 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16999 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
17000 if( msg == EQUIP_ERR_OK )
17002 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
17003 if(IsInWorld())
17004 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
17011 // only if current pet in slot
17012 switch(pet->getPetType())
17014 case MINI_PET:
17015 m_miniPet = 0;
17016 break;
17017 case GUARDIAN_PET:
17018 RemoveGuardian(pet);
17019 break;
17020 default:
17021 if(GetPetGUID() == pet->GetGUID())
17022 SetPet(NULL);
17023 break;
17026 pet->CombatStop();
17028 pet->SavePetToDB(mode);
17030 pet->AddObjectToRemoveList();
17031 pet->m_removed = true;
17033 if(pet->isControlled())
17035 RemovePetActionBar();
17037 if(GetGroup())
17038 SetGroupUpdateFlag(GROUP_UPDATE_PET);
17042 void Player::RemoveMiniPet()
17044 if(Pet* pet = GetMiniPet())
17046 pet->Remove(PET_SAVE_AS_DELETED);
17047 m_miniPet = 0;
17051 Pet* Player::GetMiniPet()
17053 if(!m_miniPet)
17054 return NULL;
17055 return GetMap()->GetPet(m_miniPet);
17058 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
17060 *data << (uint8)msgtype;
17061 *data << (uint32)language;
17062 *data << (uint64)GetGUID();
17063 *data << (uint32)language; //language 2.1.0 ?
17064 *data << (uint64)GetGUID();
17065 *data << (uint32)(text.length()+1);
17066 *data << text;
17067 *data << (uint8)chatTag();
17070 void Player::Say(const std::string& text, const uint32 language)
17072 WorldPacket data(SMSG_MESSAGECHAT, 200);
17073 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
17074 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
17077 void Player::Yell(const std::string& text, const uint32 language)
17079 WorldPacket data(SMSG_MESSAGECHAT, 200);
17080 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
17081 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
17084 void Player::TextEmote(const std::string& text)
17086 WorldPacket data(SMSG_MESSAGECHAT, 200);
17087 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
17088 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
17091 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
17093 if (language != LANG_ADDON) // if not addon data
17094 language = LANG_UNIVERSAL; // whispers should always be readable
17096 Player *rPlayer = sObjectMgr.GetPlayer(receiver);
17098 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
17099 if(!rPlayer->isDND() || isGameMaster())
17101 WorldPacket data(SMSG_MESSAGECHAT, 200);
17102 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
17103 rPlayer->GetSession()->SendPacket(&data);
17105 // not send confirmation for addon messages
17106 if (language != LANG_ADDON)
17108 data.Initialize(SMSG_MESSAGECHAT, 200);
17109 rPlayer->BuildPlayerChat(&data, CHAT_MSG_WHISPER_INFORM, text, language);
17110 GetSession()->SendPacket(&data);
17113 else
17115 // announce to player that player he is whispering to is dnd and cannot receive his message
17116 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
17119 if(!isAcceptWhispers())
17121 SetAcceptWhispers(true);
17122 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
17125 // announce to player that player he is whispering to is afk
17126 if(rPlayer->isAFK())
17127 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
17129 // if player whisper someone, auto turn of dnd to be able to receive an answer
17130 if(isDND() && !rPlayer->isGameMaster())
17131 ToggleDND();
17134 void Player::PetSpellInitialize()
17136 Pet* pet = GetPet();
17138 if(!pet)
17139 return;
17141 sLog.outDebug("Pet Spells Groups");
17143 CharmInfo *charmInfo = pet->GetCharmInfo();
17145 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17146 data << uint64(pet->GetGUID());
17147 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
17148 data << uint32(0);
17149 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17151 // action bar loop
17152 charmInfo->BuildActionBar(&data);
17154 size_t spellsCountPos = data.wpos();
17156 // spells count
17157 uint8 addlist = 0;
17158 data << uint8(addlist); // placeholder
17160 if (pet->IsPermanentPetFor(this))
17162 // spells loop
17163 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
17165 if(itr->second.state == PETSPELL_REMOVED)
17166 continue;
17168 data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
17169 ++addlist;
17173 data.put<uint8>(spellsCountPos, addlist);
17175 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
17176 data << uint8(cooldownsCount);
17178 time_t curTime = time(NULL);
17180 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
17182 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
17184 data << uint32(itr->first); // spellid
17185 data << uint16(0); // spell category?
17186 data << uint32(cooldown); // cooldown
17187 data << uint32(0); // category cooldown
17190 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
17192 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
17194 data << uint32(itr->first); // spellid
17195 data << uint16(0); // spell category?
17196 data << uint32(0); // cooldown
17197 data << uint32(cooldown); // category cooldown
17200 GetSession()->SendPacket(&data);
17203 void Player::SendPetGUIDs()
17205 if(!GetPetGUID())
17206 return;
17208 // Later this function might get modified for multiple guids
17209 WorldPacket data(SMSG_PET_GUIDS, 12);
17210 data << uint32(1); // count
17211 data << uint64(GetPetGUID());
17212 GetSession()->SendPacket(&data);
17215 void Player::PossessSpellInitialize()
17217 Unit* charm = GetCharm();
17219 if(!charm)
17220 return;
17222 CharmInfo *charmInfo = charm->GetCharmInfo();
17224 if(!charmInfo)
17226 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17227 return;
17230 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17231 data << uint64(charm->GetGUID());
17232 data << uint16(0);
17233 data << uint32(0);
17234 data << uint32(0);
17236 charmInfo->BuildActionBar(&data);
17238 data << uint8(0); // spells count
17239 data << uint8(0); // cooldowns count
17241 GetSession()->SendPacket(&data);
17244 void Player::CharmSpellInitialize()
17246 Unit* charm = GetCharm();
17248 if(!charm)
17249 return;
17251 CharmInfo *charmInfo = charm->GetCharmInfo();
17252 if(!charmInfo)
17254 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17255 return;
17258 uint8 addlist = 0;
17260 if(charm->GetTypeId() != TYPEID_PLAYER)
17262 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
17264 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
17266 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17268 if(charmInfo->GetCharmSpell(i)->GetAction())
17269 ++addlist;
17274 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
17275 data << uint64(charm->GetGUID());
17276 data << uint16(0);
17277 data << uint32(0);
17279 if(charm->GetTypeId() != TYPEID_PLAYER)
17280 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17281 else
17282 data << uint8(0) << uint8(0) << uint16(0);
17284 charmInfo->BuildActionBar(&data);
17286 data << uint8(addlist);
17288 if(addlist)
17290 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17292 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
17293 if(cspell->GetAction())
17294 data << uint32(cspell->packedData);
17298 data << uint8(0); // cooldowns count
17300 GetSession()->SendPacket(&data);
17303 void Player::RemovePetActionBar()
17305 WorldPacket data(SMSG_PET_SPELLS, 8);
17306 data << uint64(0);
17307 SendDirectMessage(&data);
17310 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
17312 if (!mod || !spellInfo)
17313 return false;
17315 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
17317 // prevent apply to any spell except spell that trigger expire
17318 if(spell)
17320 if(mod->lastAffected != spell)
17321 return false;
17323 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
17324 return false;
17327 return mod->isAffectedOnSpell(spellInfo);
17330 void Player::AddSpellMod(SpellModifier* mod, bool apply)
17332 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
17334 for(int eff = 0; eff < 96; ++eff)
17336 uint64 _mask = 0;
17337 uint32 _mask2= 0;
17339 if (eff < 64)
17340 _mask = uint64(1) << (eff - 0);
17341 else
17342 _mask2= uint32(1) << (eff - 64);
17344 if ( mod->mask & _mask || mod->mask2 & _mask2)
17346 int32 val = 0;
17347 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
17349 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
17350 val += (*itr)->value;
17352 val += apply ? mod->value : -(mod->value);
17353 WorldPacket data(Opcode, (1+1+4));
17354 data << uint8(eff);
17355 data << uint8(mod->op);
17356 data << int32(val);
17357 SendDirectMessage(&data);
17361 if (apply)
17362 m_spellMods[mod->op].push_back(mod);
17363 else
17365 if (mod->charges == -1)
17366 --m_SpellModRemoveCount;
17367 m_spellMods[mod->op].remove(mod);
17368 delete mod;
17372 void Player::RemoveSpellMods(Spell const* spell)
17374 if(!spell || (m_SpellModRemoveCount == 0))
17375 return;
17377 for(int i=0;i<MAX_SPELLMOD;++i)
17379 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
17381 SpellModifier *mod = *itr;
17382 ++itr;
17384 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
17386 RemoveAurasDueToSpell(mod->spellId);
17387 if (m_spellMods[i].empty())
17388 break;
17389 else
17390 itr = m_spellMods[i].begin();
17396 // send Proficiency
17397 void Player::SendProficiency(uint8 pr1, uint32 pr2)
17399 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
17400 data << uint8(pr1) << uint32(pr2);
17401 GetSession()->SendPacket (&data);
17404 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
17406 QueryResult *result = NULL;
17407 if(type == 10)
17408 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17409 else
17410 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17411 if(result)
17413 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.
17414 { // and SendPetitionQueryOpcode reads data from the DB
17415 Field *fields = result->Fetch();
17416 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
17417 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
17419 // send update if charter owner in game
17420 Player* owner = sObjectMgr.GetPlayer(ownerguid);
17421 if(owner)
17422 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
17424 } while ( result->NextRow() );
17426 delete result;
17428 if(type==10)
17429 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17430 else
17431 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17434 CharacterDatabase.BeginTransaction();
17435 if(type == 10)
17437 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
17438 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
17440 else
17442 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17443 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17445 CharacterDatabase.CommitTransaction();
17448 void Player::LeaveAllArenaTeams(uint64 guid)
17450 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));
17451 if(!result)
17452 return;
17456 Field *fields = result->Fetch();
17457 uint32 at_id = fields[0].GetUInt32();
17458 if(at_id != 0)
17460 ArenaTeam * at = sObjectMgr.GetArenaTeamById(at_id);
17461 if(at)
17462 at->DelMember(guid);
17464 } while (result->NextRow());
17466 delete result;
17469 void Player::SetRestBonus (float rest_bonus_new)
17471 // Prevent resting on max level
17472 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
17473 rest_bonus_new = 0;
17475 if(rest_bonus_new < 0)
17476 rest_bonus_new = 0;
17478 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
17480 if(rest_bonus_new > rest_bonus_max)
17481 m_rest_bonus = rest_bonus_max;
17482 else
17483 m_rest_bonus = rest_bonus_new;
17485 // update data for client
17486 if(m_rest_bonus>10)
17487 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
17488 else if(m_rest_bonus<=1)
17489 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
17491 //RestTickUpdate
17492 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
17495 void Player::HandleStealthedUnitsDetection()
17497 std::list<Unit*> stealthedUnits;
17499 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17500 Cell cell(p);
17501 cell.data.Part.reserved = ALL_DISTRICT;
17502 cell.SetNoCreate();
17504 MaNGOS::AnyStealthedCheck u_check;
17505 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
17507 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
17508 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
17510 cell.Visit(p, world_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17511 cell.Visit(p, grid_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17513 WorldObject const* viewPoint = GetViewPoint();
17515 for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
17517 if((*i)==this)
17518 continue;
17520 bool hasAtClient = HaveAtClient((*i));
17521 bool hasDetected = (*i)->isVisibleForOrDetect(this, viewPoint, true);
17523 if (hasDetected)
17525 if(!hasAtClient)
17527 (*i)->SendCreateUpdateToPlayer(this);
17528 m_clientGUIDs.insert((*i)->GetGUID());
17530 #ifdef MANGOS_DEBUG
17531 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17532 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
17533 #endif
17535 // target aura duration for caster show only if target exist at caster client
17536 // send data at target visibility change (adding to client)
17537 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
17538 SendAurasForTarget(*i);
17541 else
17543 if(hasAtClient)
17545 (*i)->DestroyForPlayer(this);
17546 m_clientGUIDs.erase((*i)->GetGUID());
17552 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
17554 if(nodes.size() < 2)
17555 return false;
17557 // 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
17558 if(GetSession()->isLogingOut() || isInCombat())
17560 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17561 data << uint32(ERR_TAXIPLAYERBUSY);
17562 GetSession()->SendPacket(&data);
17563 return false;
17566 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
17567 return false;
17569 // taximaster case
17570 if(npc)
17572 // not let cheating with start flight mounted
17573 if(IsMounted())
17575 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17576 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
17577 GetSession()->SendPacket(&data);
17578 return false;
17581 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17583 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17584 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
17585 GetSession()->SendPacket(&data);
17586 return false;
17589 // 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
17590 if(IsNonMeleeSpellCasted(false))
17592 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17593 data << uint32(ERR_TAXIPLAYERBUSY);
17594 GetSession()->SendPacket(&data);
17595 return false;
17598 // cast case or scripted call case
17599 else
17601 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
17603 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17604 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
17606 if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
17607 if (spell->m_spellInfo->Id != spellid)
17608 InterruptSpell(CURRENT_GENERIC_SPELL,false);
17610 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
17612 if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
17613 if (spell->m_spellInfo->Id != spellid)
17614 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
17617 uint32 sourcenode = nodes[0];
17619 // starting node too far away (cheat?)
17620 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
17621 if (!node)
17623 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17624 data << uint32(ERR_TAXINOSUCHPATH);
17625 GetSession()->SendPacket(&data);
17626 return false;
17629 // check node starting pos data set case if provided
17630 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
17632 if (node->map_id != GetMapId() ||
17633 (node->x - GetPositionX())*(node->x - GetPositionX())+
17634 (node->y - GetPositionY())*(node->y - GetPositionY())+
17635 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
17636 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
17638 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17639 data << uint32(ERR_TAXITOOFARAWAY);
17640 GetSession()->SendPacket(&data);
17641 return false;
17644 // node must have pos if taxi master case (npc != NULL)
17645 else if (npc)
17647 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17648 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17649 GetSession()->SendPacket(&data);
17650 return false;
17653 // Prepare to flight start now
17655 // stop combat at start taxi flight if any
17656 CombatStop();
17658 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17659 TradeCancel(true);
17661 // clean not finished taxi path if any
17662 m_taxi.ClearTaxiDestinations();
17664 // 0 element current node
17665 m_taxi.AddTaxiDestination(sourcenode);
17667 // fill destinations path tail
17668 uint32 sourcepath = 0;
17669 uint32 totalcost = 0;
17671 uint32 prevnode = sourcenode;
17672 uint32 lastnode = 0;
17674 for(uint32 i = 1; i < nodes.size(); ++i)
17676 uint32 path, cost;
17678 lastnode = nodes[i];
17679 sObjectMgr.GetTaxiPath(prevnode, lastnode, path, cost);
17681 if(!path)
17683 m_taxi.ClearTaxiDestinations();
17684 return false;
17687 totalcost += cost;
17689 if(prevnode == sourcenode)
17690 sourcepath = path;
17692 m_taxi.AddTaxiDestination(lastnode);
17694 prevnode = lastnode;
17697 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
17698 uint32 mount_display_id = sObjectMgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
17700 // in spell case allow 0 model
17701 if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
17703 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17704 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17705 GetSession()->SendPacket(&data);
17706 m_taxi.ClearTaxiDestinations();
17707 return false;
17710 uint32 money = GetMoney();
17712 if (npc)
17713 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17715 if(money < totalcost)
17717 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17718 data << uint32(ERR_TAXINOTENOUGHMONEY);
17719 GetSession()->SendPacket(&data);
17720 m_taxi.ClearTaxiDestinations();
17721 return false;
17724 //Checks and preparations done, DO FLIGHT
17725 ModifyMoney(-(int32)totalcost);
17726 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
17727 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
17729 // prevent stealth flight
17730 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17732 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17733 data << uint32(ERR_TAXIOK);
17734 GetSession()->SendPacket(&data);
17736 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17738 GetSession()->SendDoFlight(mount_display_id, sourcepath);
17740 return true;
17743 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
17745 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
17746 if(!entry)
17747 return false;
17749 std::vector<uint32> nodes;
17751 nodes.resize(2);
17752 nodes[0] = entry->from;
17753 nodes[1] = entry->to;
17755 return ActivateTaxiPathTo(nodes,NULL,spellid);
17758 void Player::ContinueTaxiFlight()
17760 uint32 sourceNode = m_taxi.GetTaxiSource();
17761 if (!sourceNode)
17762 return;
17764 sLog.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
17766 uint32 mountDisplayId = sObjectMgr.GetTaxiMountDisplayId(sourceNode, GetTeam(),true);
17767 uint32 path = m_taxi.GetCurrentTaxiPath();
17769 // search appropriate start path node
17770 uint32 startNode = 0;
17772 TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
17774 float distPrev = MAP_SIZE*MAP_SIZE;
17775 float distNext =
17776 (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
17777 (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
17778 (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
17780 for(uint32 i = 1; i < nodeList.size(); ++i)
17782 TaxiPathNode const& node = nodeList[i];
17783 TaxiPathNode const& prevNode = nodeList[i-1];
17785 // skip nodes at another map
17786 if(node.mapid != GetMapId())
17787 continue;
17789 distPrev = distNext;
17791 distNext =
17792 (node.x-GetPositionX())*(node.x-GetPositionX())+
17793 (node.y-GetPositionY())*(node.y-GetPositionY())+
17794 (node.z-GetPositionZ())*(node.z-GetPositionZ());
17796 float distNodes =
17797 (node.x-prevNode.x)*(node.x-prevNode.x)+
17798 (node.y-prevNode.y)*(node.y-prevNode.y)+
17799 (node.z-prevNode.z)*(node.z-prevNode.z);
17801 if(distNext + distPrev < distNodes)
17803 startNode = i;
17804 break;
17808 GetSession()->SendDoFlight(mountDisplayId, path, startNode);
17811 void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17813 // last check 2.0.10
17814 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17815 data << uint64(GetGUID());
17816 data << uint8(0x0); // flags (0x1, 0x2)
17817 time_t curTime = time(NULL);
17818 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17820 if (itr->second->state == PLAYERSPELL_REMOVED)
17821 continue;
17822 uint32 unSpellId = itr->first;
17823 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17824 if (!spellInfo)
17826 ASSERT(spellInfo);
17827 continue;
17830 // Not send cooldown for this spells
17831 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17832 continue;
17834 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17836 data << uint32(unSpellId);
17837 data << uint32(unTimeMs); // in m.secs
17838 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17841 GetSession()->SendPacket(&data);
17844 void Player::InitDataForForm(bool reapplyMods)
17846 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17847 if(ssEntry && ssEntry->attackSpeed)
17849 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17850 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17851 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17853 else
17854 SetRegularAttackTime();
17856 switch(m_form)
17858 case FORM_CAT:
17860 if(getPowerType()!=POWER_ENERGY)
17861 setPowerType(POWER_ENERGY);
17862 break;
17864 case FORM_BEAR:
17865 case FORM_DIREBEAR:
17867 if(getPowerType()!=POWER_RAGE)
17868 setPowerType(POWER_RAGE);
17869 break;
17871 default: // 0, for example
17873 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17874 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17875 setPowerType(Powers(cEntry->powerType));
17876 break;
17880 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17881 if (!reapplyMods)
17882 UpdateEquipSpellsAtFormChange();
17884 UpdateAttackPowerAndDamage();
17885 UpdateAttackPowerAndDamage(true);
17888 void Player::InitDisplayIds()
17890 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
17891 if(!info)
17893 sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
17894 return;
17897 uint8 gender = getGender();
17898 switch(gender)
17900 case GENDER_FEMALE:
17901 SetDisplayId(info->displayId_f );
17902 SetNativeDisplayId(info->displayId_f );
17903 break;
17904 case GENDER_MALE:
17905 SetDisplayId(info->displayId_m );
17906 SetNativeDisplayId(info->displayId_m );
17907 break;
17908 default:
17909 sLog.outError("Invalid gender %u for player",gender);
17910 return;
17914 // Return true is the bought item has a max count to force refresh of window by caller
17915 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot)
17917 // cheating attempt
17918 if (count < 1) count = 1;
17920 if (!isAlive())
17921 return false;
17923 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
17924 if (!pProto)
17926 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17927 return false;
17930 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
17931 if (!pCreature)
17933 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17934 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17935 return false;
17938 VendorItemData const* vItems = pCreature->GetVendorItems();
17939 if(!vItems || vItems->Empty())
17941 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17942 return false;
17945 size_t vendor_slot = vItems->FindItemSlot(item);
17946 if (vendor_slot >= vItems->GetItemCount())
17948 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17949 return false;
17952 VendorItem const* crItem = vItems->m_items[vendor_slot];
17954 // check current item amount if it limited
17955 if (crItem->maxcount != 0)
17957 if (pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17959 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17960 return false;
17964 if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17966 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17967 return false;
17970 if (crItem->ExtendedCost)
17972 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17973 if (!iece)
17975 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17976 return false;
17979 // honor points price
17980 if (GetHonorPoints() < (iece->reqhonorpoints * count))
17982 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17983 return false;
17986 // arena points price
17987 if (GetArenaPoints() < (iece->reqarenapoints * count))
17989 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17990 return false;
17993 // item base price
17994 for (uint8 i = 0; i < 5; ++i)
17996 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17998 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17999 return false;
18003 // check for personal arena rating requirement
18004 if( GetMaxPersonalArenaRatingRequirement(iece->reqarenaslot) < iece->reqpersonalarenarating )
18006 // probably not the proper equip err
18007 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
18008 return false;
18012 uint32 price = pProto->BuyPrice * count;
18014 // reputation discount
18015 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
18017 if (GetMoney() < price)
18019 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
18020 return false;
18023 if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
18025 ItemPosCountVec dest;
18026 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
18027 if (msg != EQUIP_ERR_OK)
18029 SendEquipError( msg, NULL, NULL );
18030 return false;
18033 ModifyMoney( -(int32)price );
18034 if (crItem->ExtendedCost) // case for new honor system
18036 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
18037 if (iece->reqhonorpoints)
18038 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
18039 if (iece->reqarenapoints)
18040 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
18041 for (uint8 i = 0; i < 5; ++i)
18043 if (iece->reqitem[i])
18044 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
18048 if (Item *it = StoreNewItem( dest, item, true ))
18050 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
18052 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
18053 data << uint64(pCreature->GetGUID());
18054 data << uint32(vendor_slot+1); // numbered from 1 at client
18055 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
18056 data << uint32(count);
18057 GetSession()->SendPacket(&data);
18059 SendNewItem(it, pProto->BuyCount*count, true, false, false);
18062 else if (IsEquipmentPos(bag, slot))
18064 if (pProto->BuyCount * count != 1)
18066 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
18067 return false;
18070 uint16 dest;
18071 uint8 msg = CanEquipNewItem( slot, dest, item, false );
18072 if (msg != EQUIP_ERR_OK)
18074 SendEquipError( msg, NULL, NULL );
18075 return false;
18078 ModifyMoney( -(int32)price );
18079 if (crItem->ExtendedCost) // case for new honor system
18081 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
18082 if (iece->reqhonorpoints)
18083 ModifyHonorPoints( - int32(iece->reqhonorpoints));
18084 if (iece->reqarenapoints)
18085 ModifyArenaPoints( - int32(iece->reqarenapoints));
18086 for (uint8 i = 0; i < 5; ++i)
18088 if(iece->reqitem[i])
18089 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
18093 if (Item *it = EquipNewItem( dest, item, true ))
18095 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
18097 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
18098 data << uint64(pCreature->GetGUID());
18099 data << uint32(vendor_slot + 1); // numbered from 1 at client
18100 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
18101 data << uint32(count);
18102 GetSession()->SendPacket(&data);
18104 SendNewItem(it, pProto->BuyCount*count, true, false, false);
18106 AutoUnequipOffhandIfNeed();
18109 else
18111 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
18112 return false;
18115 return crItem->maxcount != 0;
18118 uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot)
18120 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
18121 // the personal rating of the arena team must match the required limit as well
18122 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
18123 uint32 max_personal_rating = 0;
18124 for(int i = minarenaslot; i < MAX_ARENA_SLOT; ++i)
18126 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(GetArenaTeamId(i)))
18128 uint32 p_rating = GetArenaPersonalRating(i);
18129 uint32 t_rating = at->GetRating();
18130 p_rating = p_rating < t_rating ? p_rating : t_rating;
18131 if(max_personal_rating < p_rating)
18132 max_personal_rating = p_rating;
18135 return max_personal_rating;
18138 void Player::UpdateHomebindTime(uint32 time)
18140 // GMs never get homebind timer online
18141 if (m_InstanceValid || isGameMaster())
18143 if(m_HomebindTimer) // instance valid, but timer not reset
18145 // hide reminder
18146 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
18147 data << uint32(0);
18148 data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
18149 GetSession()->SendPacket(&data);
18151 // instance is valid, reset homebind timer
18152 m_HomebindTimer = 0;
18154 else if (m_HomebindTimer > 0)
18156 if (time >= m_HomebindTimer)
18158 // teleport to nearest graveyard
18159 RepopAtGraveyard();
18161 else
18162 m_HomebindTimer -= time;
18164 else
18166 // instance is invalid, start homebind timer
18167 m_HomebindTimer = 60000;
18168 // send message to player
18169 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
18170 data << uint32(m_HomebindTimer);
18171 data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
18172 GetSession()->SendPacket(&data);
18173 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
18177 void Player::UpdatePvP(bool state, bool ovrride)
18179 if(!state || ovrride)
18181 SetPvP(state);
18182 pvpInfo.endTimer = 0;
18184 else
18186 if(pvpInfo.endTimer != 0)
18187 pvpInfo.endTimer = time(NULL);
18188 else
18189 SetPvP(state);
18193 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
18195 // init cooldown values
18196 uint32 cat = 0;
18197 int32 rec = -1;
18198 int32 catrec = -1;
18200 // some special item spells without correct cooldown in SpellInfo
18201 // cooldown information stored in item prototype
18202 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
18204 if(itemId)
18206 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
18208 for(int idx = 0; idx < 5; ++idx)
18210 if(proto->Spells[idx].SpellId == spellInfo->Id)
18212 cat = proto->Spells[idx].SpellCategory;
18213 rec = proto->Spells[idx].SpellCooldown;
18214 catrec = proto->Spells[idx].SpellCategoryCooldown;
18215 break;
18221 // if no cooldown found above then base at DBC data
18222 if(rec < 0 && catrec < 0)
18224 cat = spellInfo->Category;
18225 rec = spellInfo->RecoveryTime;
18226 catrec = spellInfo->CategoryRecoveryTime;
18229 time_t curTime = time(NULL);
18231 time_t catrecTime;
18232 time_t recTime;
18234 // overwrite time for selected category
18235 if(infinityCooldown)
18237 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
18238 // but not allow ignore until reset or re-login
18239 catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
18240 recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
18242 else
18244 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
18245 // prevent 0 cooldowns set by another way
18246 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
18247 rec = GetAttackTime(RANGED_ATTACK);
18249 // Now we have cooldown data (if found any), time to apply mods
18250 if(rec > 0)
18251 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
18253 if(catrec > 0)
18254 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
18256 // replace negative cooldowns by 0
18257 if (rec < 0) rec = 0;
18258 if (catrec < 0) catrec = 0;
18260 // no cooldown after applying spell mods
18261 if( rec == 0 && catrec == 0)
18262 return;
18264 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
18265 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
18268 // self spell cooldown
18269 if(recTime > 0)
18270 AddSpellCooldown(spellInfo->Id, itemId, recTime);
18272 // category spells
18273 if (cat && catrec > 0)
18275 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
18276 if(i_scstore != sSpellCategoryStore.end())
18278 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
18280 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
18281 continue;
18283 AddSpellCooldown(*i_scset, itemId, catrecTime);
18289 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
18291 SpellCooldown sc;
18292 sc.end = end_time;
18293 sc.itemid = itemid;
18294 m_spellCooldowns[spellid] = sc;
18297 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
18299 // start cooldowns at server side, if any
18300 AddSpellAndCategoryCooldowns(spellInfo, itemId, spell);
18302 // Send activate cooldown timer (possible 0) at client side
18303 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
18304 data << uint32(spellInfo->Id);
18305 data << uint64(GetGUID());
18306 SendDirectMessage(&data);
18309 void Player::UpdatePotionCooldown(Spell* spell)
18311 // no potion used i combat or still in combat
18312 if(!m_lastPotionId || isInCombat())
18313 return;
18315 // Call not from spell cast, send cooldown event for item spells if no in combat
18316 if(!spell)
18318 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
18319 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
18320 for(int idx = 0; idx < 5; ++idx)
18321 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
18322 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
18323 SendCooldownEvent(spellInfo,m_lastPotionId);
18325 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
18326 else
18327 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
18329 m_lastPotionId = 0;
18332 //slot to be excluded while counting
18333 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
18335 if(!enchantmentcondition)
18336 return true;
18338 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
18340 if(!Condition)
18341 return true;
18343 uint8 curcount[4] = {0, 0, 0, 0};
18345 //counting current equipped gem colors
18346 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
18348 if(i == slot)
18349 continue;
18350 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
18351 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
18353 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18355 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18356 if(!enchant_id)
18357 continue;
18359 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18360 if(!enchantEntry)
18361 continue;
18363 uint32 gemid = enchantEntry->GemID;
18364 if(!gemid)
18365 continue;
18367 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
18368 if(!gemProto)
18369 continue;
18371 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
18372 if(!gemProperty)
18373 continue;
18375 uint8 GemColor = gemProperty->color;
18377 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
18379 if(tmpcolormask & GemColor)
18380 ++curcount[b];
18386 bool activate = true;
18388 for(int i = 0; i < 5; ++i)
18390 if(!Condition->Color[i])
18391 continue;
18393 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
18395 // if have <CompareColor> use them as count, else use <value> from Condition
18396 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
18398 switch(Condition->Comparator[i])
18400 case 2: // requires less <color> than (<value> || <comparecolor>) gems
18401 activate &= (_cur_gem < _cmp_gem) ? true : false;
18402 break;
18403 case 3: // requires more <color> than (<value> || <comparecolor>) gems
18404 activate &= (_cur_gem > _cmp_gem) ? true : false;
18405 break;
18406 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
18407 activate &= (_cur_gem >= _cmp_gem) ? true : false;
18408 break;
18412 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");
18414 return activate;
18417 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
18419 //cycle all equipped items
18420 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18422 //enchants for the slot being socketed are handled by Player::ApplyItemMods
18423 if(slot == exceptslot)
18424 continue;
18426 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18428 if(!pItem || !pItem->GetProto()->Socket[0].Color)
18429 continue;
18431 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18433 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18434 if(!enchant_id)
18435 continue;
18437 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18438 if(!enchantEntry)
18439 continue;
18441 uint32 condition = enchantEntry->EnchantmentCondition;
18442 if(condition)
18444 //was enchant active with/without item?
18445 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
18446 //should it now be?
18447 if(wasactive != EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
18449 // ignore item gem conditions
18450 //if state changed, (dis)apply enchant
18451 ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true);
18458 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
18459 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
18461 //cycle all equipped items
18462 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18464 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
18465 if(slot == exceptslot)
18466 continue;
18468 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18470 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
18471 continue;
18473 //cycle all (gem)enchants
18474 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18476 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18477 if(!enchant_id) //if no enchant go to next enchant(slot)
18478 continue;
18480 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18481 if(!enchantEntry)
18482 continue;
18484 //only metagems to be (de)activated, so only enchants with condition
18485 uint32 condition = enchantEntry->EnchantmentCondition;
18486 if(condition)
18487 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
18492 void Player::SetBattleGroundEntryPoint()
18494 // Taxi path store
18495 if (!m_taxi.empty())
18497 m_bgData.mountSpell = 0;
18498 m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
18499 m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
18501 // On taxi we don't need check for dungeon
18502 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18503 return;
18505 else
18507 m_bgData.ClearTaxiPath();
18509 // Mount spell id storing
18510 if (IsMounted())
18512 AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED);
18513 if (!auras.empty())
18514 m_bgData.mountSpell = (*auras.begin())->GetId();
18516 else
18517 m_bgData.mountSpell = 0;
18519 // If map is dungeon find linked graveyard
18520 if(GetMap()->IsDungeon())
18522 if (const WorldSafeLocsEntry* entry = sObjectMgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
18524 m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
18525 return;
18527 else
18528 sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
18530 // If new entry point is not BG or arena set it
18531 else if (!GetMap()->IsBattleGroundOrArena())
18533 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18534 return;
18538 // In error cases use homebind position
18539 m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
18542 void Player::LeaveBattleground(bool teleportToEntryPoint)
18544 if(BattleGround *bg = GetBattleGround())
18546 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
18548 // call after remove to be sure that player resurrected for correct cast
18549 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
18551 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
18553 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
18554 if(IsBeingTeleportedFar())
18556 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
18557 return;
18560 CastSpell(this, 26013, true); // Deserter
18566 bool Player::CanJoinToBattleground() const
18568 // check Deserter debuff
18569 if(GetDummyAura(26013))
18570 return false;
18572 return true;
18575 bool Player::CanReportAfkDueToLimit()
18577 // a player can complain about 15 people per 5 minutes
18578 if(m_bgData.bgAfkReportedCount++ >= 15)
18579 return false;
18581 return true;
18584 ///This player has been blamed to be inactive in a battleground
18585 void Player::ReportedAfkBy(Player* reporter)
18587 BattleGround *bg = GetBattleGround();
18588 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
18589 return;
18591 // check if player has 'Idle' or 'Inactive' debuff
18592 if(m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680, 0) && !HasAura(43681, 0) && reporter->CanReportAfkDueToLimit())
18594 m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
18595 // 3 players have to complain to apply debuff
18596 if(m_bgData.bgAfkReporter.size() >= 3)
18598 // cast 'Idle' spell
18599 CastSpell(this, 43680, true);
18600 m_bgData.bgAfkReporter.clear();
18605 WorldObject const* Player::GetViewPoint() const
18607 if(uint64 far_sight = GetFarSight())
18609 WorldObject const* viewPoint = GetMap()->GetWorldObject(far_sight);
18610 return viewPoint ? viewPoint : this; // always expected not NULL
18612 else
18613 return this;
18616 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
18618 // gamemaster in GM mode see all, including ghosts
18619 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
18620 return true;
18622 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
18623 if (InBattleGround())
18625 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
18626 return false;
18627 return true;
18630 // Live player see live player or dead player with not realized corpse
18631 if(pl->isAlive() || pl->m_deathTimer > 0)
18633 return isAlive() || m_deathTimer > 0;
18636 // Ghost see other friendly ghosts, that's for sure
18637 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
18638 return true;
18640 // Dead player see live players near own corpse
18641 if(isAlive())
18643 Corpse *corpse = pl->GetCorpse();
18644 if(corpse)
18646 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
18647 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
18648 return true;
18652 // and not see any other
18653 return false;
18656 bool Player::IsVisibleGloballyFor( Player* u ) const
18658 if(!u)
18659 return false;
18661 // Always can see self
18662 if (u==this)
18663 return true;
18665 // Visible units, always are visible for all players
18666 if (GetVisibility() == VISIBILITY_ON)
18667 return true;
18669 // GMs are visible for higher gms (or players are visible for gms)
18670 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
18671 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
18673 // non faction visibility non-breakable for non-GMs
18674 if (GetVisibility() == VISIBILITY_OFF)
18675 return false;
18677 // non-gm stealth/invisibility not hide from global player lists
18678 return true;
18681 template<class T>
18682 inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/)
18686 template<>
18687 inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
18689 if (p->GetPetGUID()==t->GetGUID() && ((Creature*)t)->isPet())
18690 ((Pet*)t)->Remove(PET_SAVE_NOT_IN_SLOT, true);
18693 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target)
18695 if(HaveAtClient(target))
18697 if(!target->isVisibleForInState(this, viewPoint, true))
18699 if (target->GetTypeId()==TYPEID_UNIT)
18700 BeforeVisibilityDestroy<Creature>((Creature*)target,this);
18702 target->DestroyForPlayer(this);
18703 m_clientGUIDs.erase(target->GetGUID());
18705 #ifdef MANGOS_DEBUG
18706 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18707 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18708 #endif
18711 else
18713 if(target->isVisibleForInState(this, viewPoint, false))
18715 target->SendCreateUpdateToPlayer(this);
18716 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
18717 m_clientGUIDs.insert(target->GetGUID());
18719 #ifdef MANGOS_DEBUG
18720 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18721 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18722 #endif
18724 // target aura duration for caster show only if target exist at caster client
18725 // send data at target visibility change (adding to client)
18726 if(target!=this && target->isType(TYPEMASK_UNIT))
18727 SendAurasForTarget((Unit*)target);
18729 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
18730 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18735 template<class T>
18736 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
18738 s64.insert(target->GetGUID());
18741 template<>
18742 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
18744 if(!target->IsTransport())
18745 s64.insert(target->GetGUID());
18748 template<class T>
18749 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
18751 if(HaveAtClient(target))
18753 if(!target->isVisibleForInState(this,viewPoint,true))
18755 BeforeVisibilityDestroy<T>(target,this);
18757 target->BuildOutOfRangeUpdateBlock(&data);
18758 m_clientGUIDs.erase(target->GetGUID());
18760 #ifdef MANGOS_DEBUG
18761 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18762 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));
18763 #endif
18766 else
18768 if(target->isVisibleForInState(this,viewPoint,false))
18770 visibleNow.insert(target);
18771 target->BuildCreateUpdateBlockForPlayer(&data, this);
18772 UpdateVisibilityOf_helper(m_clientGUIDs,target);
18774 #ifdef MANGOS_DEBUG
18775 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18776 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));
18777 #endif
18782 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18783 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18784 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18785 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18786 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18788 void Player::InitPrimaryProfessions()
18790 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
18793 void Player::SendComboPoints()
18795 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
18796 if (combotarget)
18798 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
18799 data.append(combotarget->GetPackGUID());
18800 data << uint8(m_comboPoints);
18801 GetSession()->SendPacket(&data);
18805 void Player::AddComboPoints(Unit* target, int8 count)
18807 if(!count)
18808 return;
18810 // without combo points lost (duration checked in aura)
18811 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18813 if(target->GetGUID() == m_comboTarget)
18815 m_comboPoints += count;
18817 else
18819 if(m_comboTarget)
18820 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
18821 target2->RemoveComboPointHolder(GetGUIDLow());
18823 m_comboTarget = target->GetGUID();
18824 m_comboPoints = count;
18826 target->AddComboPointHolder(GetGUIDLow());
18829 if (m_comboPoints > 5) m_comboPoints = 5;
18830 if (m_comboPoints < 0) m_comboPoints = 0;
18832 SendComboPoints();
18835 void Player::ClearComboPoints()
18837 if(!m_comboTarget)
18838 return;
18840 // without combopoints lost (duration checked in aura)
18841 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18843 m_comboPoints = 0;
18845 SendComboPoints();
18847 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18848 target->RemoveComboPointHolder(GetGUIDLow());
18850 m_comboTarget = 0;
18853 void Player::SetGroup(Group *group, int8 subgroup)
18855 if(group == NULL)
18856 m_group.unlink();
18857 else
18859 // never use SetGroup without a subgroup unless you specify NULL for group
18860 assert(subgroup >= 0);
18861 m_group.link(group, this);
18862 m_group.setSubGroup((uint8)subgroup);
18866 void Player::SendInitialPacketsBeforeAddToMap()
18868 GetSocial()->SendSocialList();
18870 // Homebind
18871 WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
18872 data << m_homebindX << m_homebindY << m_homebindZ;
18873 data << (uint32) m_homebindMapId;
18874 data << (uint32) m_homebindZoneId;
18875 GetSession()->SendPacket(&data);
18877 // SMSG_SET_PROFICIENCY
18878 // SMSG_SET_PCT_SPELL_MODIFIER
18879 // SMSG_SET_FLAT_SPELL_MODIFIER
18881 SendTalentsInfoData(false);
18883 data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4+4);
18884 data << uint32(0);
18885 data << uint32(0);
18886 GetSession()->SendPacket(&data);
18888 SendInitialSpells();
18890 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
18891 data << uint32(0); // count, for(count) uint32;
18892 GetSession()->SendPacket(&data);
18894 SendInitialActionButtons();
18895 m_reputationMgr.SendInitialReputations();
18897 if(!isAlive())
18898 SendCorpseReclaimDelay(true);
18900 SendInitWorldStates(GetZoneId(), GetAreaId());
18902 SendEquipmentSetList();
18904 m_achievementMgr.SendAllAchievementData();
18906 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
18907 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18908 data << (float)0.01666667f; // game speed
18909 data << uint32(0); // added in 3.1.2
18910 GetSession()->SendPacket( &data );
18912 // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
18913 // SMSG_PET_GUIDS
18914 // SMSG_POWER_UPDATE
18916 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18917 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || HasAuraType(SPELL_AURA_FLY) || isInFlight())
18918 m_movementInfo.AddMovementFlag(MOVEFLAG_FLYING);
18920 m_mover = this;
18923 void Player::SendInitialPacketsAfterAddToMap()
18925 // update zone
18926 uint32 newzone, newarea;
18927 GetZoneAndAreaId(newzone,newarea);
18928 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
18930 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18931 data << uint32(0x00000000); // on blizz it increments periodically
18932 GetSession()->SendPacket(&data);
18934 CastSpell(this, 836, true); // LOGINEFFECT
18936 // set some aura effects that send packet to player client after add player to map
18937 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18938 // same auras state lost at far teleport, send it one more time in this case also
18939 static const AuraType auratypes[] =
18941 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18942 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18943 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18945 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18947 Unit::AuraList const& auraList = GetAurasByType(*itr);
18948 if(!auraList.empty())
18949 auraList.front()->ApplyModifier(true,true);
18952 if(HasAuraType(SPELL_AURA_MOD_STUN))
18953 SetMovement(MOVE_ROOT);
18955 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18956 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18958 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
18959 data2.append(GetPackGUID());
18960 data2 << (uint32)2;
18961 SendMessageToSet(&data2,true);
18964 SendAurasForTarget(this);
18965 SendEnchantmentDurations(); // must be after add to map
18966 SendItemDurations(); // must be after add to map
18969 void Player::SendUpdateToOutOfRangeGroupMembers()
18971 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18972 return;
18973 if(Group* group = GetGroup())
18974 group->UpdatePlayerOutOfRange(this);
18976 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18977 m_auraUpdateMask = 0;
18978 if(Pet *pet = GetPet())
18979 pet->ResetAuraUpdateMask();
18982 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18984 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18985 data << uint32(mapid);
18986 data << uint8(reason); // transfer abort reason
18987 switch(reason)
18989 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18990 case TRANSFER_ABORT_DIFFICULTY:
18991 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18992 data << uint8(arg);
18993 break;
18995 GetSession()->SendPacket(&data);
18998 void Player::SendInstanceResetWarning( uint32 mapid, Difficulty difficulty, uint32 time )
19000 // type of warning, based on the time remaining until reset
19001 uint32 type;
19002 if(time > 3600)
19003 type = RAID_INSTANCE_WELCOME;
19004 else if(time > 900 && time <= 3600)
19005 type = RAID_INSTANCE_WARNING_HOURS;
19006 else if(time > 300 && time <= 900)
19007 type = RAID_INSTANCE_WARNING_MIN;
19008 else
19009 type = RAID_INSTANCE_WARNING_MIN_SOON;
19011 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
19012 data << uint32(type);
19013 data << uint32(mapid);
19014 data << uint32(difficulty); // difficulty
19015 data << uint32(time);
19016 if(type == RAID_INSTANCE_WELCOME)
19018 data << uint8(0); // is your (1)
19019 data << uint8(0); // is extended (1), ignored if prev field is 0
19021 GetSession()->SendPacket(&data);
19024 void Player::ApplyEquipCooldown( Item * pItem )
19026 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
19028 _Spell const& spellData = pItem->GetProto()->Spells[i];
19030 // no spell
19031 if( !spellData.SpellId )
19032 continue;
19034 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
19035 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
19036 continue;
19038 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
19040 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
19041 data << pItem->GetGUID();
19042 data << uint32(spellData.SpellId);
19043 GetSession()->SendPacket(&data);
19047 void Player::resetSpells()
19049 // not need after this call
19050 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
19051 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
19053 // make full copy of map (spells removed and marked as deleted at another spell remove
19054 // and we can't use original map for safe iterative with visit each spell at loop end
19055 PlayerSpellMap smap = GetSpellMap();
19057 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
19058 removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
19060 learnDefaultSpells();
19061 learnQuestRewardedSpells();
19064 void Player::learnDefaultSpells()
19066 // learn default race/class spells
19067 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(),getClass());
19068 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
19070 uint32 tspell = *itr;
19071 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
19072 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
19073 addSpell(tspell,true,true,true,false);
19074 else // but send in normal spell in game learn case
19075 learnSpell(tspell,true);
19079 void Player::learnQuestRewardedSpells(Quest const* quest)
19081 uint32 spell_id = quest->GetRewSpellCast();
19083 // skip quests without rewarded spell
19084 if( !spell_id )
19085 return;
19087 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
19088 if(!spellInfo)
19089 return;
19091 // check learned spells state
19092 bool found = false;
19093 for(int i=0; i < 3; ++i)
19095 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
19097 found = true;
19098 break;
19102 // skip quests with not teaching spell or already known spell
19103 if(!found)
19104 return;
19106 // prevent learn non first rank unknown profession and second specialization for same profession)
19107 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
19108 if( sSpellMgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
19110 // not have first rank learned (unlearned prof?)
19111 uint32 first_spell = sSpellMgr.GetFirstSpellInChain(learned_0);
19112 if( !HasSpell(first_spell) )
19113 return;
19115 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
19116 if(!learnedInfo)
19117 return;
19119 // specialization
19120 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
19122 // search other specialization for same prof
19123 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
19125 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
19126 continue;
19128 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
19129 if(!itrInfo)
19130 return;
19132 // compare only specializations
19133 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
19134 continue;
19136 // compare same chain spells
19137 if(sSpellMgr.GetFirstSpellInChain(itr->first) != first_spell)
19138 continue;
19140 // now we have 2 specialization, learn possible only if found is lesser specialization rank
19141 if(!sSpellMgr.IsHighRankOfSpell(learned_0,itr->first))
19142 return;
19147 CastSpell( this, spell_id, true);
19150 void Player::learnQuestRewardedSpells()
19152 // learn spells received from quest completing
19153 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
19155 // skip no rewarded quests
19156 if(!itr->second.m_rewarded)
19157 continue;
19159 Quest const* quest = sObjectMgr.GetQuestTemplate(itr->first);
19160 if( !quest )
19161 continue;
19163 learnQuestRewardedSpells(quest);
19167 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
19169 uint32 raceMask = getRaceMask();
19170 uint32 classMask = getClassMask();
19171 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
19173 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
19174 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
19175 continue;
19176 // Check race if set
19177 if (pAbility->racemask && !(pAbility->racemask & raceMask))
19178 continue;
19179 // Check class if set
19180 if (pAbility->classmask && !(pAbility->classmask & classMask))
19181 continue;
19183 if (sSpellStore.LookupEntry(pAbility->spellId))
19185 // need unlearn spell
19186 if (skill_value < pAbility->req_skill_value)
19187 removeSpell(pAbility->spellId);
19188 // need learn
19189 else if (!IsInWorld())
19190 addSpell(pAbility->spellId,true,true,true,false);
19191 else
19192 learnSpell(pAbility->spellId,true);
19197 void Player::SendAurasForTarget(Unit *target)
19199 if(target->GetVisibleAuras()->empty()) // speedup things
19200 return;
19202 WorldPacket data(SMSG_AURA_UPDATE_ALL);
19203 data.append(target->GetPackGUID());
19205 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
19206 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
19208 for(uint32 j = 0; j < 3; ++j)
19210 if(Aura *aura = target->GetAura(itr->second, j))
19212 data << uint8(aura->GetAuraSlot());
19213 data << uint32(aura->GetId());
19215 if(aura->GetId())
19217 uint8 auraFlags = aura->GetAuraFlags();
19218 // flags
19219 data << uint8(auraFlags);
19220 // level
19221 data << uint8(aura->GetAuraLevel());
19222 // charges
19223 if (aura->GetAuraCharges())
19224 data << uint8(aura->GetAuraCharges() * aura->GetStackAmount());
19225 else
19226 data << uint8(aura->GetStackAmount());
19228 if(!(auraFlags & AFLAG_NOT_CASTER))
19230 data << uint8(0); // packed GUID of someone (caster?)
19233 if(auraFlags & AFLAG_DURATION) // include aura duration
19235 data << uint32(aura->GetAuraMaxDuration());
19236 data << uint32(aura->GetAuraDuration());
19239 break;
19244 GetSession()->SendPacket(&data);
19247 void Player::SetDailyQuestStatus( uint32 quest_id )
19249 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19251 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
19253 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
19254 m_lastDailyQuestTime = time(NULL); // last daily quest time
19255 m_DailyQuestChanged = true;
19256 break;
19261 void Player::ResetDailyQuestStatus()
19263 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19264 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
19266 // DB data deleted in caller
19267 m_DailyQuestChanged = false;
19268 m_lastDailyQuestTime = 0;
19271 BattleGround* Player::GetBattleGround() const
19273 if(GetBattleGroundId()==0)
19274 return NULL;
19276 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
19279 bool Player::InArena() const
19281 BattleGround *bg = GetBattleGround();
19282 if(!bg || !bg->isArena())
19283 return false;
19285 return true;
19288 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
19290 // get a template bg instead of running one
19291 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
19292 if(!bg)
19293 return false;
19295 // limit check leel to dbc compatible level range
19296 uint32 level = getLevel();
19297 if (level > DEFAULT_MAX_LEVEL)
19298 level = DEFAULT_MAX_LEVEL;
19300 if(level < bg->GetMinLevel() || level > bg->GetMaxLevel())
19301 return false;
19303 return true;
19306 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
19308 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
19309 if(!vendor_faction || !vendor_faction->faction)
19310 return 1.0f;
19312 ReputationRank rank = GetReputationRank(vendor_faction->faction);
19313 if(rank <= REP_NEUTRAL)
19314 return 1.0f;
19316 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
19319 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
19321 uint32 racemask = getRaceMask();
19322 uint32 classmask = getClassMask();
19324 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
19325 if (bounds.first==bounds.second)
19326 return true;
19328 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
19330 // skip wrong race skills
19331 if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
19332 continue;
19334 // skip wrong class skills
19335 if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
19336 continue;
19338 return true;
19341 return false;
19344 bool Player::HasQuestForGO(int32 GOId) const
19346 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
19348 uint32 questid = GetQuestSlotQuestId(i);
19349 if ( questid == 0 )
19350 continue;
19352 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
19353 if(qs_itr == mQuestStatus.end())
19354 continue;
19356 QuestStatusData const& qs = qs_itr->second;
19358 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
19360 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
19361 if(!qinfo)
19362 continue;
19364 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
19365 continue;
19367 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
19369 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
19370 continue;
19372 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
19373 return true;
19377 return false;
19380 void Player::UpdateForQuestWorldObjects()
19382 if(m_clientGUIDs.empty())
19383 return;
19385 UpdateData udata;
19386 WorldPacket packet;
19387 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
19389 if(IS_GAMEOBJECT_GUID(*itr))
19391 GameObject *obj = GetMap()->GetGameObject(*itr);
19392 if(obj)
19393 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
19395 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
19397 Creature *obj = GetMap()->GetCreatureOrPetOrVehicle(*itr);
19398 if(!obj)
19399 continue;
19401 // check if this unit requires quest specific flags
19402 if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
19403 continue;
19405 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(obj->GetEntry());
19406 for(SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
19408 if(_itr->second.questStart || _itr->second.questEnd)
19410 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
19411 break;
19416 udata.BuildPacket(&packet);
19417 GetSession()->SendPacket(&packet);
19420 void Player::SummonIfPossible(bool agree)
19422 if(!agree)
19424 m_summon_expire = 0;
19425 return;
19428 // expire and auto declined
19429 if(m_summon_expire < time(NULL))
19430 return;
19432 // stop taxi flight at summon
19433 if(isInFlight())
19435 GetMotionMaster()->MovementExpired();
19436 m_taxi.ClearTaxiDestinations();
19439 // drop flag at summon
19440 // 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
19441 if(BattleGround *bg = GetBattleGround())
19442 bg->EventPlayerDroppedFlag(this);
19444 m_summon_expire = 0;
19446 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
19448 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
19451 void Player::RemoveItemDurations( Item *item )
19453 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
19455 if(*itr==item)
19457 m_itemDuration.erase(itr);
19458 break;
19463 void Player::AddItemDurations( Item *item )
19465 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
19467 m_itemDuration.push_back(item);
19468 item->SendTimeUpdate(this);
19472 void Player::AutoUnequipOffhandIfNeed()
19474 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
19475 if(!offItem)
19476 return;
19478 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
19479 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
19480 return;
19482 ItemPosCountVec off_dest;
19483 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
19484 if( off_msg == EQUIP_ERR_OK )
19486 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19487 StoreItem( off_dest, offItem, true );
19489 else
19491 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19492 CharacterDatabase.BeginTransaction();
19493 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
19494 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
19495 CharacterDatabase.CommitTransaction();
19497 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
19498 MailDraft(subject).AddItem(offItem).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
19502 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
19504 if(spellInfo->EquippedItemClass < 0)
19505 return true;
19507 // scan other equipped items for same requirements (mostly 2 daggers/etc)
19508 // for optimize check 2 used cases only
19509 switch(spellInfo->EquippedItemClass)
19511 case ITEM_CLASS_WEAPON:
19513 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
19514 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19515 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19516 return true;
19517 break;
19519 case ITEM_CLASS_ARMOR:
19521 // tabard not have dependent spells
19522 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
19523 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19524 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19525 return true;
19527 // shields can be equipped to offhand slot
19528 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
19529 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19530 return true;
19532 // ranged slot can have some armor subclasses
19533 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
19534 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19535 return true;
19537 break;
19539 default:
19540 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
19541 break;
19544 return false;
19547 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
19549 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
19550 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
19551 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
19552 return true;
19554 // Check no reagent use mask
19555 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
19556 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
19557 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
19558 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
19559 return true;
19561 return false;
19564 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
19566 AuraMap& auras = GetAuras();
19567 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
19569 Aura* aura = itr->second;
19571 // skip passive (passive item dependent spells work in another way) and not self applied auras
19572 SpellEntry const* spellInfo = aura->GetSpellProto();
19573 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
19575 ++itr;
19576 continue;
19579 // skip if not item dependent or have alternative item
19580 if(HasItemFitToSpellReqirements(spellInfo,pItem))
19582 ++itr;
19583 continue;
19586 // no alt item, remove aura, restart check
19587 RemoveAurasDueToSpell(aura->GetId());
19588 itr = auras.begin();
19591 // currently casted spells can be dependent from item
19592 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
19593 if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
19594 if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
19595 InterruptSpell(CurrentSpellTypes(i));
19598 uint32 Player::GetResurrectionSpellId()
19600 // search priceless resurrection possibilities
19601 uint32 prio = 0;
19602 uint32 spell_id = 0;
19603 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
19604 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
19606 // Soulstone Resurrection // prio: 3 (max, non death persistent)
19607 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
19609 switch((*itr)->GetId())
19611 case 20707: spell_id = 3026; break; // rank 1
19612 case 20762: spell_id = 20758; break; // rank 2
19613 case 20763: spell_id = 20759; break; // rank 3
19614 case 20764: spell_id = 20760; break; // rank 4
19615 case 20765: spell_id = 20761; break; // rank 5
19616 case 27239: spell_id = 27240; break; // rank 6
19617 case 47883: spell_id = 47882; break; // rank 7
19618 default:
19619 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
19620 continue;
19623 prio = 3;
19625 // Twisting Nether // prio: 2 (max)
19626 else if((*itr)->GetId()==23701 && roll_chance_i(10))
19628 prio = 2;
19629 spell_id = 23700;
19633 // Reincarnation (passive spell) // prio: 1
19634 // Glyph of Renewed Life remove reagent requiremnnt
19635 if (prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasItemCount(17030,1) || HasAura(58059, 0)))
19636 spell_id = 21169;
19638 return spell_id;
19641 // Used in triggers for check "Only to targets that grant experience or honor" req
19642 bool Player::isHonorOrXPTarget(Unit* pVictim)
19644 uint32 v_level = pVictim->getLevel();
19645 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
19647 // Victim level less gray level
19648 if(v_level<=k_grey)
19649 return false;
19651 if(pVictim->GetTypeId() == TYPEID_UNIT)
19653 if (((Creature*)pVictim)->isTotem() ||
19654 ((Creature*)pVictim)->isPet() ||
19655 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
19656 return false;
19658 return true;
19661 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
19663 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
19665 // prepare data for near group iteration (PvP and !PvP cases)
19666 uint32 xp = 0;
19667 bool honored_kill = false;
19669 if(Group *pGroup = GetGroup())
19671 uint32 count = 0;
19672 uint32 sum_level = 0;
19673 Player* member_with_max_level = NULL;
19674 Player* not_gray_member_with_max_level = NULL;
19676 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
19678 if(member_with_max_level)
19680 /// not get Xp in PvP or no not gray players in group
19681 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
19683 /// skip in check PvP case (for speed, not used)
19684 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
19685 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
19686 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
19688 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19690 Player* pGroupGuy = itr->getSource();
19691 if(!pGroupGuy)
19692 continue;
19694 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
19695 continue; // member (alive or dead) or his corpse at req. distance
19697 // honor can be in PvP and !PvP (racial leader) cases (for alive)
19698 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
19699 honored_kill = true;
19701 // xp and reputation only in !PvP case
19702 if(!PvP)
19704 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
19706 // if is in dungeon then all receive full reputation at kill
19707 // rewarded any alive/dead/near_corpse group member
19708 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
19710 // XP updated only for alive group member
19711 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
19712 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
19714 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
19716 pGroupGuy->GiveXP(itr_xp, pVictim);
19717 if(Pet* pet = pGroupGuy->GetPet())
19718 pet->GivePetXP(itr_xp/2);
19721 // quest objectives updated only for alive group member or dead but with not released body
19722 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19724 // normal creature (not pet/etc) can be only in !PvP case
19725 if(pVictim->GetTypeId()==TYPEID_UNIT)
19726 pGroupGuy->KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19732 else // if (!pGroup)
19734 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
19736 // honor can be in PvP and !PvP (racial leader) cases
19737 if(RewardHonor(pVictim,1))
19738 honored_kill = true;
19740 // xp and reputation only in !PvP case
19741 if(!PvP)
19743 RewardReputation(pVictim,1);
19744 GiveXP(xp, pVictim);
19746 if(Pet* pet = GetPet())
19747 pet->GivePetXP(xp);
19749 // normal creature (not pet/etc) can be only in !PvP case
19750 if(pVictim->GetTypeId()==TYPEID_UNIT)
19751 KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19754 return xp || honored_kill;
19757 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
19759 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
19761 // prepare data for near group iteration
19762 if(Group *pGroup = GetGroup())
19764 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19766 Player* pGroupGuy = itr->getSource();
19767 if(!pGroupGuy)
19768 continue;
19770 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
19771 continue; // member (alive or dead) or his corpse at req. distance
19773 // quest objectives updated only for alive group member or dead but with not released body
19774 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19775 pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
19778 else // if (!pGroup)
19779 KilledMonsterCredit(creature_id, creature_guid);
19782 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
19784 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
19785 return true;
19787 if (isAlive())
19788 return false;
19790 Corpse* corpse = GetCorpse();
19791 if (!corpse)
19792 return false;
19794 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
19797 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
19799 Item* item = GetWeaponForAttack(attType,true,true);
19801 // unarmed only with base attack
19802 if(attType != BASE_ATTACK && !item)
19803 return 0;
19805 // weapon skill or (unarmed for base attack)
19806 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
19807 return GetBaseSkillValue(skill);
19810 void Player::ResurectUsingRequestData()
19812 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
19813 if(IS_PLAYER_GUID(m_resurrectGUID))
19814 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
19816 //we cannot resurrect player when we triggered far teleport
19817 //player will be resurrected upon teleportation
19818 if(IsBeingTeleportedFar())
19820 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
19821 return;
19824 ResurrectPlayer(0.0f,false);
19826 if(GetMaxHealth() > m_resurrectHealth)
19827 SetHealth( m_resurrectHealth );
19828 else
19829 SetHealth( GetMaxHealth() );
19831 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
19832 SetPower(POWER_MANA, m_resurrectMana );
19833 else
19834 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
19836 SetPower(POWER_RAGE, 0 );
19838 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
19840 SpawnCorpseBones();
19843 void Player::SetClientControl(Unit* target, uint8 allowMove)
19845 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
19846 data.append(target->GetPackGUID());
19847 data << uint8(allowMove);
19848 GetSession()->SendPacket(&data);
19851 void Player::UpdateZoneDependentAuras( uint32 newZone )
19853 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19854 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newZone);
19855 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19856 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
19857 if( !HasAura(itr->second->spellId,0) )
19858 CastSpell(this,itr->second->spellId,true);
19861 void Player::UpdateAreaDependentAuras( uint32 newArea )
19863 // remove auras from spells with area limitations
19864 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
19866 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19867 if(sSpellMgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
19868 RemoveAura(iter);
19869 else
19870 ++iter;
19873 // some auras applied at subzone enter
19874 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newArea);
19875 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19876 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
19877 if( !HasAura(itr->second->spellId,0) )
19878 CastSpell(this,itr->second->spellId,true);
19881 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
19883 if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
19884 (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
19886 return copseReclaimDelay[0];
19889 time_t now = time(NULL);
19890 // 0..2 full period
19891 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
19892 return copseReclaimDelay[count];
19895 void Player::UpdateCorpseReclaimDelay()
19897 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
19899 if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
19900 (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
19901 return;
19903 time_t now = time(NULL);
19904 if(now < m_deathExpireTime)
19906 // full and partly periods 1..3
19907 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
19908 if(count < MAX_DEATH_COUNT)
19909 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19910 else
19911 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19913 else
19914 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19917 void Player::SendCorpseReclaimDelay(bool load)
19919 Corpse* corpse = GetCorpse();
19920 if(!corpse)
19921 return;
19923 uint32 delay;
19924 if(load)
19926 if(corpse->GetGhostTime() > m_deathExpireTime)
19927 return;
19929 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19931 uint32 count;
19932 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19933 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19935 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19936 if(count>=MAX_DEATH_COUNT)
19937 count = MAX_DEATH_COUNT-1;
19939 else
19940 count=0;
19942 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19944 time_t now = time(NULL);
19945 if(now >= expected_time)
19946 return;
19948 delay = expected_time-now;
19950 else
19951 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19953 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19954 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19955 data << uint32(delay*IN_MILISECONDS);
19956 GetSession()->SendPacket( &data );
19959 Player* Player::GetNextRandomRaidMember(float radius)
19961 Group *pGroup = GetGroup();
19962 if(!pGroup)
19963 return NULL;
19965 std::vector<Player*> nearMembers;
19966 nearMembers.reserve(pGroup->GetMembersCount());
19968 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19970 Player* Target = itr->getSource();
19972 // IsHostileTo check duel and controlled by enemy
19973 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19974 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19975 nearMembers.push_back(Target);
19978 if (nearMembers.empty())
19979 return NULL;
19981 uint32 randTarget = urand(0,nearMembers.size()-1);
19982 return nearMembers[randTarget];
19985 PartyResult Player::CanUninviteFromGroup() const
19987 const Group* grp = GetGroup();
19988 if(!grp)
19989 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19991 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19992 return PARTY_RESULT_YOU_NOT_LEADER;
19994 if(InBattleGround())
19995 return PARTY_RESULT_INVITE_RESTRICTED;
19997 return PARTY_RESULT_OK;
20000 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
20002 //we must move references from m_group to m_originalGroup
20003 SetOriginalGroup(GetGroup(), GetSubGroup());
20005 m_group.unlink();
20006 m_group.link(group, this);
20007 m_group.setSubGroup((uint8)subgroup);
20010 void Player::RemoveFromBattleGroundRaid()
20012 //remove existing reference
20013 m_group.unlink();
20014 if( Group* group = GetOriginalGroup() )
20016 m_group.link(group, this);
20017 m_group.setSubGroup(GetOriginalSubGroup());
20019 SetOriginalGroup(NULL);
20022 void Player::SetOriginalGroup(Group *group, int8 subgroup)
20024 if( group == NULL )
20025 m_originalGroup.unlink();
20026 else
20028 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
20029 assert(subgroup >= 0);
20030 m_originalGroup.link(group, this);
20031 m_originalGroup.setSubGroup((uint8)subgroup);
20035 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
20037 LiquidData liquid_status;
20038 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
20039 if (!res)
20041 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
20042 // Small hack for enable breath in WMO
20043 if (IsInWater())
20044 m_MirrorTimerFlags|=UNDERWATER_INWATER;
20045 return;
20048 // All liquids type - check under water position
20049 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
20051 if ( res & LIQUID_MAP_UNDER_WATER)
20052 m_MirrorTimerFlags |= UNDERWATER_INWATER;
20053 else
20054 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
20057 // Allow travel in dark water on taxi or transport
20058 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
20059 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
20060 else
20061 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
20063 // in lava check, anywhere in lava level
20064 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
20066 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
20067 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
20068 else
20069 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
20071 // in slime check, anywhere in slime level
20072 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
20074 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
20075 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
20076 else
20077 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
20081 void Player::SetCanParry( bool value )
20083 if(m_canParry==value)
20084 return;
20086 m_canParry = value;
20087 UpdateParryPercentage();
20090 void Player::SetCanBlock( bool value )
20092 if(m_canBlock==value)
20093 return;
20095 m_canBlock = value;
20096 UpdateBlockPercentage();
20099 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
20101 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
20102 if(itr->pos == pos)
20103 return true;
20105 return false;
20108 bool Player::CanUseBattleGroundObject()
20110 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
20111 // maybe gameobject code should handle that ForceReaction usage
20112 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
20113 return ( //InBattleGround() && // in battleground - not need, check in other cases
20114 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
20115 //player cannot use object when he is invulnerable (immune)
20116 !isTotalImmune() && // not totally immune
20117 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
20118 !HasStealthAura() && // not stealthed
20119 !HasInvisibilityAura() && // not invisible
20120 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
20121 isAlive() // live player
20125 bool Player::CanCaptureTowerPoint()
20127 return ( !HasStealthAura() && // not stealthed
20128 !HasInvisibilityAura() && // not invisible
20129 isAlive() // live player
20133 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
20135 uint32 level = getLevel();
20137 if(level > GT_MAX_LEVEL)
20138 level = GT_MAX_LEVEL; // max level in this dbc
20140 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
20141 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
20142 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
20144 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
20145 return 0;
20147 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
20149 if(!bsc) // shouldn't happen
20150 return 0xFFFFFFFF;
20152 float cost = 0;
20154 if(hairstyle != newhairstyle)
20155 cost += bsc->cost; // full price
20157 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
20158 cost += bsc->cost * 0.5f; // +1/2 of price
20160 if(facialhair != newfacialhair)
20161 cost += bsc->cost * 0.75f; // +3/4 of price
20163 return uint32(cost);
20166 void Player::InitGlyphsForLevel()
20168 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
20169 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
20170 if(gs->Order)
20171 SetGlyphSlot(gs->Order - 1, gs->Id);
20173 uint32 level = getLevel();
20174 uint32 value = 0;
20176 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
20177 if(level >= 15)
20178 value |= (0x01 | 0x02);
20179 if(level >= 30)
20180 value |= 0x08;
20181 if(level >= 50)
20182 value |= 0x04;
20183 if(level >= 70)
20184 value |= 0x10;
20185 if(level >= 80)
20186 value |= 0x20;
20188 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
20191 void Player::EnterVehicle(Vehicle *vehicle)
20193 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
20194 if(!ve)
20195 return;
20197 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
20198 if(!veSeat)
20199 return;
20201 vehicle->SetCharmerGUID(GetGUID());
20202 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20203 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20204 vehicle->setFaction(getFaction());
20206 SetCharm(vehicle); // charm
20207 SetFarSightGUID(vehicle->GetGUID()); // set view
20209 SetClientControl(vehicle, 1); // redirect controls to vehicle
20210 SetMover(vehicle);
20212 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
20213 GetSession()->SendPacket(&data);
20215 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
20216 data.append(GetPackGUID());
20217 data << uint32(0); // counter?
20218 data << uint32(MOVEFLAG_ONTRANSPORT); // transport
20219 data << uint16(0); // special flags
20220 data << uint32(getMSTime()); // time
20221 data << vehicle->GetPositionX(); // x
20222 data << vehicle->GetPositionY(); // y
20223 data << vehicle->GetPositionZ(); // z
20224 data << vehicle->GetOrientation(); // o
20225 // transport part, TODO: load/calculate seat offsets
20226 data << uint64(vehicle->GetGUID()); // transport guid
20227 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
20228 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
20229 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
20230 data << float(0); // transport orientation
20231 data << uint32(getMSTime()); // transport time
20232 data << uint8(0); // seat
20233 // end of transport part
20234 data << uint32(0); // fall time
20235 GetSession()->SendPacket(&data);
20237 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
20238 data << uint64(vehicle->GetGUID());
20239 data << uint16(0);
20240 data << uint32(0);
20241 data << uint32(0x00000101);
20243 for(uint32 i = 0; i < 10; ++i)
20244 data << uint16(0) << uint8(0) << uint8(i+8);
20246 data << uint8(0);
20247 data << uint8(0);
20248 GetSession()->SendPacket(&data);
20251 void Player::ExitVehicle(Vehicle *vehicle)
20253 vehicle->SetCharmerGUID(0);
20254 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20255 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20256 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
20258 SetCharm(NULL);
20259 SetFarSightGUID(0);
20261 SetClientControl(vehicle, 0);
20262 SetMover(NULL);
20264 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
20265 data.append(GetPackGUID());
20266 data << uint32(0); // counter?
20267 data << uint32(MOVEFLAG_ROOT); // fly unk
20268 data << uint16(MOVEFLAG2_UNK4); // special flags
20269 data << uint32(getMSTime()); // time
20270 data << vehicle->GetPositionX(); // x
20271 data << vehicle->GetPositionY(); // y
20272 data << vehicle->GetPositionZ(); // z
20273 data << vehicle->GetOrientation(); // o
20274 data << uint32(0); // fall time
20275 GetSession()->SendPacket(&data);
20277 RemovePetActionBar();
20279 // maybe called at dummy aura remove?
20280 // CastSpell(this, 45472, true); // Parachute
20283 bool Player::isTotalImmune()
20285 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
20287 uint32 immuneMask = 0;
20288 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
20290 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
20291 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
20292 return true;
20294 return false;
20297 bool Player::HasTitle(uint32 bitIndex)
20299 if (bitIndex > MAX_TITLE_INDEX)
20300 return false;
20302 uint32 fieldIndexOffset = bitIndex / 32;
20303 uint32 flag = 1 << (bitIndex % 32);
20304 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20307 void Player::SetTitle(CharTitlesEntry const* title, bool lost)
20309 uint32 fieldIndexOffset = title->bit_index / 32;
20310 uint32 flag = 1 << (title->bit_index % 32);
20312 if(lost)
20314 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20315 return;
20317 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20319 else
20321 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20322 return;
20324 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20327 WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
20328 data << uint32(title->bit_index);
20329 data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
20330 GetSession()->SendPacket(&data);
20333 void Player::ConvertRune(uint8 index, RuneType newType)
20335 SetCurrentRune(index, newType);
20337 WorldPacket data(SMSG_CONVERT_RUNE, 2);
20338 data << uint8(index);
20339 data << uint8(newType);
20340 GetSession()->SendPacket(&data);
20343 void Player::ResyncRunes(uint8 count)
20345 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
20346 for(uint32 i = 0; i < count; ++i)
20348 data << uint8(GetCurrentRune(i)); // rune type
20349 data << uint8(255 - ((GetRuneCooldown(i) / REGEN_TIME_FULL) * 51)); // passed cooldown time (0-255)
20351 GetSession()->SendPacket(&data);
20354 void Player::AddRunePower(uint8 index)
20356 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
20357 data << uint32(1 << index); // mask (0x00-0x3F probably)
20358 GetSession()->SendPacket(&data);
20361 static RuneType runeSlotTypes[MAX_RUNES] = {
20362 /*0*/ RUNE_BLOOD,
20363 /*1*/ RUNE_BLOOD,
20364 /*2*/ RUNE_UNHOLY,
20365 /*3*/ RUNE_UNHOLY,
20366 /*4*/ RUNE_FROST,
20367 /*5*/ RUNE_FROST
20370 void Player::InitRunes()
20372 if(getClass() != CLASS_DEATH_KNIGHT)
20373 return;
20375 m_runes = new Runes;
20377 m_runes->runeState = 0;
20379 for(uint32 i = 0; i < MAX_RUNES; ++i)
20381 SetBaseRune(i, runeSlotTypes[i]); // init base types
20382 SetCurrentRune(i, runeSlotTypes[i]); // init current types
20383 SetRuneCooldown(i, 0); // reset cooldowns
20384 m_runes->SetRuneState(i);
20387 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
20388 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
20392 bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType ) const
20394 for(uint32 i = 0; i < MAX_RUNES; ++i)
20395 if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
20396 return false;
20398 return true;
20401 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
20403 Loot loot;
20404 loot.FillLoot (loot_id,store,this,true);
20406 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
20407 for(uint32 i = 0; i < max_slot; ++i)
20409 LootItem* lootItem = loot.LootItemInSlot(i,this);
20411 ItemPosCountVec dest;
20412 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
20413 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
20414 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20415 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
20416 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20417 if(msg != EQUIP_ERR_OK)
20419 SendEquipError( msg, NULL, NULL );
20420 continue;
20423 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
20424 SendNewItem(pItem, lootItem->count, false, false, broadcast);
20428 uint32 Player::CalculateTalentsPoints() const
20430 uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
20432 if(getClass() != CLASS_DEATH_KNIGHT)
20433 return uint32(base_talent * sWorld.getRate(RATE_TALENT));
20435 uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
20436 talentPointsForLevel += m_questRewardTalentCount;
20438 if(talentPointsForLevel > base_talent)
20439 talentPointsForLevel = base_talent;
20441 return uint32(talentPointsForLevel * sWorld.getRate(RATE_TALENT));
20444 bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
20446 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
20447 uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
20448 return v_map != 571 || HasSpell(54197); // Cold Weather Flying
20451 struct DoPlayerLearnSpell
20453 DoPlayerLearnSpell(Player& _player) : player(_player) {}
20454 void operator() (uint32 spell_id) { player.learnSpell(spell_id,false); }
20455 Player& player;
20458 void Player::learnSpellHighRank(uint32 spellid)
20460 learnSpell(spellid,false);
20462 DoPlayerLearnSpell worker(*this);
20463 sSpellMgr.doForHighRanks(spellid,worker);
20466 void Player::_LoadSkills(QueryResult *result)
20468 // 0 1 2
20469 // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
20471 uint32 count = 0;
20472 if (result)
20476 Field *fields = result->Fetch();
20478 uint16 skill = fields[0].GetUInt16();
20479 uint16 value = fields[1].GetUInt16();
20480 uint16 max = fields[2].GetUInt16();
20482 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(skill);
20483 if(!pSkill)
20485 sLog.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill);
20486 continue;
20489 // set fixed skill ranges
20490 switch(GetSkillRangeType(pSkill,false))
20492 case SKILL_RANGE_LANGUAGE: // 300..300
20493 value = max = 300;
20494 break;
20495 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
20496 value = max = 1;
20497 break;
20498 default:
20499 break;
20502 if(value == 0)
20504 sLog.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
20505 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill );
20506 continue;
20509 // enable unlearn button for primary professions only
20510 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
20511 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,1));
20512 else
20513 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,0));
20515 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),MAKE_SKILL_VALUE(value, max));
20516 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20518 mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
20520 learnSkillRewardedSpells(skill, value);
20522 ++count;
20524 if(count >= PLAYER_MAX_SKILLS) // client limit
20526 sLog.outError("Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS);
20527 break;
20529 } while (result->NextRow());
20530 delete result;
20533 for (; count < PLAYER_MAX_SKILLS; ++count)
20535 SetUInt32Value(PLAYER_SKILL_INDEX(count), 0);
20536 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),0);
20537 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20540 // special settings
20541 if(getClass()==CLASS_DEATH_KNIGHT)
20543 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
20544 if(base_level < 1)
20545 base_level = 1;
20546 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
20547 if(base_skill < 1)
20548 base_skill = 1; // skill mast be known and then > 0 in any case
20550 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
20551 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
20552 if(GetPureSkillValue (SKILL_AXES) < base_skill)
20553 SetSkill(SKILL_AXES, base_skill,base_skill);
20554 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
20555 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
20556 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
20557 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
20558 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
20559 SetSkill(SKILL_SWORDS, base_skill,base_skill);
20560 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
20561 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
20562 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
20563 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
20564 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
20565 SetSkill(SKILL_UNARMED, base_skill,base_skill);
20569 uint32 Player::GetPhaseMaskForSpawn() const
20571 uint32 phase = PHASEMASK_NORMAL;
20572 if(!isGameMaster())
20573 phase = GetPhaseMask();
20574 else
20576 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
20577 if(!phases.empty())
20578 phase = phases.front()->GetMiscValue();
20581 // some aura phases include 1 normal map in addition to phase itself
20582 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
20583 return n_phase;
20585 return PHASEMASK_NORMAL;
20588 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
20590 ItemPrototype const* pProto = pItem->GetProto();
20592 // proto based limitations
20593 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
20594 return res;
20596 // check unique-equipped on gems
20597 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
20599 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
20600 if(!enchant_id)
20601 continue;
20602 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
20603 if(!enchantEntry)
20604 continue;
20606 ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID);
20607 if(!pGem)
20608 continue;
20610 // include for check equip another gems with same limit category for not equipped item (and then not counted)
20611 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
20612 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
20614 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
20615 return res;
20618 return EQUIP_ERR_OK;
20621 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
20623 // check unique-equipped on item
20624 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
20626 // there is an equip limit on this item
20627 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
20628 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20631 // check unique-equipped limit
20632 if (itemProto->ItemLimitCategory)
20634 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
20635 if(!limitEntry)
20636 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20638 if(limit_count > limitEntry->maxCount)
20639 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
20641 // there is an equip limit on this item
20642 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
20643 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20646 return EQUIP_ERR_OK;
20649 void Player::HandleFall(MovementInfo const& movementInfo)
20651 // calculate total z distance of the fall
20652 float z_diff = m_lastFallZ - movementInfo.GetPos()->z;
20653 sLog.outDebug("zDiff = %f", z_diff);
20655 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
20656 // 14.57 can be calculated by resolving damageperc formula below to 0
20657 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
20658 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
20659 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
20661 //Safe fall, fall height reduction
20662 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
20664 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
20666 if(damageperc >0 )
20668 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
20670 float height = movementInfo.GetPos()->z;
20671 UpdateGroundPositionZ(movementInfo.GetPos()->x, movementInfo.GetPos()->y, height);
20673 if (damage > 0)
20675 //Prevent fall damage from being more than the player maximum health
20676 if (damage > GetMaxHealth())
20677 damage = GetMaxHealth();
20679 // Gust of Wind
20680 if (GetDummyAura(43621))
20681 damage = GetMaxHealth()/2;
20683 uint32 original_health = GetHealth();
20684 uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
20686 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
20687 if (isAlive() && final_damage < original_health)
20688 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
20691 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
20692 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.GetPos()->z, height, GetPositionZ(), movementInfo.GetFallTime(), height, damage, safe_fall);
20697 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
20699 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
20702 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
20704 uint32 CurTalentPoints = GetFreeTalentPoints();
20706 if(CurTalentPoints == 0)
20707 return;
20709 if (talentRank >= MAX_TALENT_RANK)
20710 return;
20712 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
20714 if(!talentInfo)
20715 return;
20717 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
20719 if(!talentTabInfo)
20720 return;
20722 // prevent learn talent for different class (cheating)
20723 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
20724 return;
20726 // find current max talent rank
20727 uint32 curtalent_maxrank = 0;
20728 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20730 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20732 curtalent_maxrank = k + 1;
20733 break;
20737 // we already have same or higher talent rank learned
20738 if(curtalent_maxrank >= (talentRank + 1))
20739 return;
20741 // check if we have enough talent points
20742 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20743 return;
20745 // Check if it requires another talent
20746 if (talentInfo->DependsOn > 0)
20748 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20750 bool hasEnoughRank = false;
20751 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20753 if (depTalentInfo->RankID[i] != 0)
20754 if (HasSpell(depTalentInfo->RankID[i]))
20755 hasEnoughRank = true;
20757 if (!hasEnoughRank)
20758 return;
20762 // Find out how many points we have in this field
20763 uint32 spentPoints = 0;
20765 uint32 tTab = talentInfo->TalentTab;
20766 if (talentInfo->Row > 0)
20768 unsigned int numRows = sTalentStore.GetNumRows();
20769 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20771 // Someday, someone needs to revamp
20772 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20773 if (tmpTalent) // the way talents are tracked
20775 if (tmpTalent->TalentTab == tTab)
20777 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20779 if (tmpTalent->RankID[j] != 0)
20781 if (HasSpell(tmpTalent->RankID[j]))
20783 spentPoints += j + 1;
20792 // not have required min points spent in talent tree
20793 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
20794 return;
20796 // spell not set in talent.dbc
20797 uint32 spellid = talentInfo->RankID[talentRank];
20798 if( spellid == 0 )
20800 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20801 return;
20804 // already known
20805 if(HasSpell(spellid))
20806 return;
20808 // learn! (other talent ranks will unlearned at learning)
20809 learnSpell(spellid, false);
20810 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20812 // update free talent points
20813 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20816 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
20818 Pet *pet = GetPet();
20820 if(!pet)
20821 return;
20823 if(petGuid != pet->GetGUID())
20824 return;
20826 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
20828 if(CurTalentPoints == 0)
20829 return;
20831 if (talentRank >= MAX_PET_TALENT_RANK)
20832 return;
20834 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
20836 if(!talentInfo)
20837 return;
20839 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
20841 if(!talentTabInfo)
20842 return;
20844 CreatureInfo const *ci = pet->GetCreatureInfo();
20846 if(!ci)
20847 return;
20849 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20851 if(!pet_family)
20852 return;
20854 if(pet_family->petTalentType < 0) // not hunter pet
20855 return;
20857 // prevent learn talent for different family (cheating)
20858 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20859 return;
20861 // find current max talent rank
20862 int32 curtalent_maxrank = 0;
20863 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20865 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20867 curtalent_maxrank = k + 1;
20868 break;
20872 // we already have same or higher talent rank learned
20873 if(curtalent_maxrank >= int32(talentRank + 1))
20874 return;
20876 // check if we have enough talent points
20877 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20878 return;
20880 // Check if it requires another talent
20881 if (talentInfo->DependsOn > 0)
20883 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20885 bool hasEnoughRank = false;
20886 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20888 if (depTalentInfo->RankID[i] != 0)
20889 if (pet->HasSpell(depTalentInfo->RankID[i]))
20890 hasEnoughRank = true;
20892 if (!hasEnoughRank)
20893 return;
20897 // Find out how many points we have in this field
20898 uint32 spentPoints = 0;
20900 uint32 tTab = talentInfo->TalentTab;
20901 if (talentInfo->Row > 0)
20903 unsigned int numRows = sTalentStore.GetNumRows();
20904 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20906 // Someday, someone needs to revamp
20907 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20908 if (tmpTalent) // the way talents are tracked
20910 if (tmpTalent->TalentTab == tTab)
20912 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20914 if (tmpTalent->RankID[j] != 0)
20916 if (pet->HasSpell(tmpTalent->RankID[j]))
20918 spentPoints += j + 1;
20927 // not have required min points spent in talent tree
20928 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
20929 return;
20931 // spell not set in talent.dbc
20932 uint32 spellid = talentInfo->RankID[talentRank];
20933 if( spellid == 0 )
20935 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20936 return;
20939 // already known
20940 if(pet->HasSpell(spellid))
20941 return;
20943 // learn! (other talent ranks will unlearned at learning)
20944 pet->learnSpell(spellid);
20945 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20947 // update free talent points
20948 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20951 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
20953 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
20955 if(apply)
20956 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
20957 else
20958 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
20962 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
20964 if (m_lastFallTime >= minfo.GetFallTime() || m_lastFallZ <= minfo.GetPos()->z || opcode == MSG_MOVE_FALL_LAND)
20965 SetFallInformation(minfo.GetFallTime(), minfo.GetPos()->z);
20968 void Player::UnsummonPetTemporaryIfAny()
20970 Pet* pet = GetPet();
20971 if(!pet)
20972 return;
20974 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
20976 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
20977 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
20980 RemovePet(pet, PET_SAVE_AS_CURRENT);
20983 void Player::ResummonPetTemporaryUnSummonedIfAny()
20985 if(!m_temporaryUnsummonedPetNumber)
20986 return;
20988 // not resummon in not appropriate state
20989 if(IsPetNeedBeTemporaryUnsummoned())
20990 return;
20992 if(GetPetGUID())
20993 return;
20995 Pet* NewPet = new Pet;
20996 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
20997 delete NewPet;
20999 m_temporaryUnsummonedPetNumber = 0;
21002 bool Player::canSeeSpellClickOn(Creature const *c) const
21004 if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
21005 return false;
21007 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(c->GetEntry());
21008 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
21009 if(itr->second.IsFitToRequirements(this))
21010 return true;
21012 return false;
21015 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
21017 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
21018 *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
21019 *data << uint8(m_activeSpec); // talent group index (0 or 1)
21021 if(m_specsCount)
21023 // loop through all specs (only 1 for now)
21024 for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
21026 uint8 talentIdCount = 0;
21027 size_t pos = data->wpos();
21028 *data << uint8(talentIdCount); // [PH], talentIdCount
21030 // find class talent tabs (all players have 3 talent tabs)
21031 uint32 const* talentTabIds = GetTalentTabPages(getClass());
21033 for(uint32 i = 0; i < 3; ++i)
21035 uint32 talentTabId = talentTabIds[i];
21037 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
21039 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
21040 if(!talentInfo)
21041 continue;
21043 // skip another tab talents
21044 if(talentInfo->TalentTab != talentTabId)
21045 continue;
21047 // find max talent rank
21048 int32 curtalent_maxrank = -1;
21049 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
21051 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
21053 curtalent_maxrank = k;
21054 break;
21058 // not learned talent
21059 if(curtalent_maxrank < 0)
21060 continue;
21062 *data << uint32(talentInfo->TalentID); // Talent.dbc
21063 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
21065 ++talentIdCount;
21069 data->put<uint8>(pos, talentIdCount); // put real count
21071 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
21073 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
21074 *data << uint16(GetGlyph(i)); // GlyphProperties.dbc
21079 void Player::BuildPetTalentsInfoData(WorldPacket *data)
21081 uint32 unspentTalentPoints = 0;
21082 size_t pointsPos = data->wpos();
21083 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
21085 uint8 talentIdCount = 0;
21086 size_t countPos = data->wpos();
21087 *data << uint8(talentIdCount); // [PH], talentIdCount
21089 Pet *pet = GetPet();
21090 if(!pet)
21091 return;
21093 unspentTalentPoints = pet->GetFreeTalentPoints();
21095 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
21097 CreatureInfo const *ci = pet->GetCreatureInfo();
21098 if(!ci)
21099 return;
21101 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
21102 if(!pet_family || pet_family->petTalentType < 0)
21103 return;
21105 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
21107 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
21108 if(!talentTabInfo)
21109 continue;
21111 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
21112 continue;
21114 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
21116 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
21117 if(!talentInfo)
21118 continue;
21120 // skip another tab talents
21121 if(talentInfo->TalentTab != talentTabId)
21122 continue;
21124 // find max talent rank
21125 int32 curtalent_maxrank = -1;
21126 for(int32 k = 4; k > -1; --k)
21128 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
21130 curtalent_maxrank = k;
21131 break;
21135 // not learned talent
21136 if(curtalent_maxrank < 0)
21137 continue;
21139 *data << uint32(talentInfo->TalentID); // Talent.dbc
21140 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
21142 ++talentIdCount;
21145 data->put<uint8>(countPos, talentIdCount); // put real count
21147 break;
21151 void Player::SendTalentsInfoData(bool pet)
21153 WorldPacket data(SMSG_TALENTS_INFO, 50);
21154 data << uint8(pet ? 1 : 0);
21155 if(pet)
21156 BuildPetTalentsInfoData(&data);
21157 else
21158 BuildPlayerTalentsInfoData(&data);
21159 GetSession()->SendPacket(&data);
21162 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
21164 uint32 slotUsedMask = 0;
21165 size_t slotUsedMaskPos = data->wpos();
21166 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
21168 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21170 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
21172 if(!item)
21173 continue;
21175 slotUsedMask |= (1 << i);
21177 *data << uint32(item->GetEntry()); // item entry
21179 uint16 enchantmentMask = 0;
21180 size_t enchantmentMaskPos = data->wpos();
21181 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
21183 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
21185 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
21187 if(!enchId)
21188 continue;
21190 enchantmentMask |= (1 << j);
21192 *data << uint16(enchId); // enchantmentId?
21195 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
21197 *data << uint16(0); // ?
21198 *data << uint8(0); // PGUID!
21199 *data << uint32(0); // seed?
21202 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
21205 void Player::SendEquipmentSetList()
21207 uint32 count = 0;
21208 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
21209 size_t count_pos = data.wpos();
21210 data << uint32(count); // count placeholder
21211 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21213 if(itr->second.state==EQUIPMENT_SET_DELETED)
21214 continue;
21215 data.appendPackGUID(itr->second.Guid);
21216 data << uint32(itr->first);
21217 data << itr->second.Name;
21218 data << itr->second.IconName;
21219 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21220 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
21222 ++count; // client have limit but it checked at loading and set
21224 data.put<uint32>(count_pos, count);
21225 GetSession()->SendPacket(&data);
21228 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
21230 if(eqset.Guid != 0)
21232 bool found = false;
21234 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21236 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
21238 found = true;
21239 break;
21243 if(!found) // something wrong...
21245 sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
21246 return;
21250 EquipmentSet& eqslot = m_EquipmentSets[index];
21252 EquipmentSetUpdateState old_state = eqslot.state;
21254 eqslot = eqset;
21256 if(eqset.Guid == 0)
21258 eqslot.Guid = sObjectMgr.GenerateEquipmentSetGuid();
21260 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
21261 data << uint32(index);
21262 data.appendPackGUID(eqslot.Guid);
21263 GetSession()->SendPacket(&data);
21266 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
21269 void Player::_SaveEquipmentSets()
21271 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
21273 uint32 index = itr->first;
21274 EquipmentSet& eqset = itr->second;
21275 switch(eqset.state)
21277 case EQUIPMENT_SET_UNCHANGED:
21278 ++itr;
21279 break; // nothing do
21280 case EQUIPMENT_SET_CHANGED:
21281 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'",
21282 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],
21283 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);
21284 eqset.state = EQUIPMENT_SET_UNCHANGED;
21285 ++itr;
21286 break;
21287 case EQUIPMENT_SET_NEW:
21288 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')",
21289 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],
21290 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]);
21291 eqset.state = EQUIPMENT_SET_UNCHANGED;
21292 ++itr;
21293 break;
21294 case EQUIPMENT_SET_DELETED:
21295 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
21296 m_EquipmentSets.erase(itr++);
21297 break;
21302 void Player::_SaveBGData()
21304 CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
21305 if (m_bgData.bgInstanceID)
21307 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
21308 CharacterDatabase.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
21309 GetGUIDLow(), m_bgData.bgInstanceID, m_bgData.bgTeam, m_bgData.joinPos.coord_x, m_bgData.joinPos.coord_y, m_bgData.joinPos.coord_z,
21310 m_bgData.joinPos.orientation, m_bgData.joinPos.mapid, m_bgData.taxiPath[0], m_bgData.taxiPath[1], m_bgData.mountSpell);
21314 void Player::DeleteEquipmentSet(uint64 setGuid)
21316 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21318 if(itr->second.Guid == setGuid)
21320 if(itr->second.state == EQUIPMENT_SET_NEW)
21321 m_EquipmentSets.erase(itr);
21322 else
21323 itr->second.state = EQUIPMENT_SET_DELETED;
21324 break;
21329 void Player::ActivateSpec(uint8 specNum)
21331 if(GetActiveSpec() == specNum)
21332 return;
21334 if(specNum >= GetSpecsCount())
21335 return;
21337 // unlearn GetActiveSpec() talents (not learned in specNum);
21338 // learn specNum talents
21340 SetActiveSpec(specNum);
21342 // recheck action buttons (not checked at loading/spec copy)
21343 ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
21344 for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); ++itr)
21345 if (itr->second.uState != ACTIONBUTTON_DELETED)
21346 if (!IsActionButtonDataValid(itr->first,itr->second.GetAction(),itr->second.GetType(), this))
21347 removeActionButton(m_activeSpec,itr->first);
21349 SendInitialActionButtons();
21351 InitTalentForLevel();
21354 void Player::UpdateSpecCount(uint8 count)
21356 uint8 curCount = GetSpecsCount();
21357 if (curCount == count)
21358 return;
21360 // maybe current spec data must be copied to 0 spec?
21361 if (m_activeSpec >= count)
21362 ActivateSpec(0);
21364 // copy spec data from new specs
21365 if (count > curCount)
21367 // copy action buttons from active spec (more easy in this case iterate first by button)
21368 ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
21370 for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); ++itr)
21372 if (itr->second.uState != ACTIONBUTTON_DELETED)
21374 for(uint8 spec = curCount; spec < count; ++spec)
21375 addActionButton(spec,itr->first,itr->second.GetAction(),itr->second.GetType());
21379 // other data copy
21380 // for(uint8 spec = curCount; spec < count; ++spec)
21381 // ...
21383 // delete spec data for removed specs
21384 else if (count < curCount)
21386 // delete action buttons for removed spec
21387 for(uint8 spec = count; spec < curCount; ++spec)
21389 // delete action buttons for removed spec
21390 for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button)
21391 removeActionButton(spec,button);
21393 // other data remove
21397 SetSpecsCount(count);
21399 SendTalentsInfoData(false);
21402 void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
21404 m_atLoginFlags &= ~f;
21406 if(in_db_also)
21407 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
21410 void Player::SendClearCooldown( uint32 spell_id, Unit* target )
21412 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
21413 data << uint32(spell_id);
21414 data << uint64(target->GetGUID());
21415 SendDirectMessage(&data);
21418 void Player::BuildTeleportAckMsg( WorldPacket *data, float x, float y, float z, float ang ) const
21420 data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
21421 data->append(GetPackGUID());
21422 *data << uint32(0); // this value increments every time
21423 *data << uint32(m_movementInfo.GetMovementFlags()); // movement flags
21424 *data << uint16(0); // 2.3.0
21425 *data << uint32(getMSTime()); // time
21426 *data << x;
21427 *data << y;
21428 *data << z;
21429 *data << ang;
21430 *data << uint32(0);
21433 bool Player::HasMovementFlag( MovementFlags f ) const
21435 return m_movementInfo.HasMovementFlag(f);
21438 void Player::SetFarSightGUID( uint64 guid )
21440 if(GetFarSight() == guid)
21441 return;
21443 SetUInt64Value(PLAYER_FARSIGHT, guid);
21445 // need triggering load grids around new view point
21446 UpdateVisibilityForPlayer();
21449 void Player::UpdateVisibilityForPlayer()
21451 WorldObject const* viewPoint = GetViewPoint();
21452 Map* m = GetMap();
21454 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
21455 Cell cell(p);
21457 m->UpdatePlayerVisibility(this, cell, p);
21459 if (this != viewPoint)
21461 CellPair pView(MaNGOS::ComputeCellPair(viewPoint->GetPositionX(), viewPoint->GetPositionY()));
21462 Cell cellView(pView);
21464 m->UpdateObjectsVisibilityFor(this, cellView, pView);
21466 else
21467 m->UpdateObjectsVisibilityFor(this, cell, p);
21470 void Player::SendDuelCountdown(uint32 counter)
21472 WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
21473 data << uint32(counter); // seconds
21474 GetSession()->SendPacket(&data);
21477 bool Player::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
21479 switch(spellInfo->Effect[index])
21481 case SPELL_EFFECT_ATTACK_ME:
21482 return true;
21483 default:
21484 break;
21486 switch(spellInfo->EffectApplyAuraName[index])
21488 case SPELL_AURA_MOD_TAUNT:
21489 return true;
21490 default:
21491 break;
21493 return Unit::IsImmunedToSpellEffect(spellInfo, index);
21496 void Player::SetHomebindToCurrentPos()
21498 m_homebindMapId = GetMapId();
21499 m_homebindZoneId = GetZoneId();
21500 m_homebindX = GetPositionX();
21501 m_homebindY = GetPositionY();
21502 m_homebindZ = GetPositionZ();
21504 // update sql homebind
21505 CharacterDatabase.PExecute("UPDATE character_homebind SET map = '%u', zone = '%u', position_x = '%f', position_y = '%f', position_z = '%f' WHERE guid = '%u'",
21506 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ, GetGUIDLow());