Just a few renames.
[getmangos.git] / src / game / Player.cpp
blob52a4bbd679f895c7bdb4e66254a7349ecb0631ac
1 /*
2 * Copyright (C) 2005-2009 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 "CreatureAI.h"
46 #include "Formulas.h"
47 #include "Group.h"
48 #include "Guild.h"
49 #include "Pet.h"
50 #include "Util.h"
51 #include "Transports.h"
52 #include "Weather.h"
53 #include "BattleGround.h"
54 #include "BattleGroundMgr.h"
55 #include "ArenaTeam.h"
56 #include "Chat.h"
57 #include "Database/DatabaseImpl.h"
58 #include "Spell.h"
59 #include "SocialMgr.h"
60 #include "AchievementMgr.h"
62 #include <cmath>
64 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
78 enum CharacterFlags
80 CHARACTER_FLAG_NONE = 0x00000000,
81 CHARACTER_FLAG_UNK1 = 0x00000001,
82 CHARACTER_FLAG_UNK2 = 0x00000002,
83 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
84 CHARACTER_FLAG_UNK4 = 0x00000008,
85 CHARACTER_FLAG_UNK5 = 0x00000010,
86 CHARACTER_FLAG_UNK6 = 0x00000020,
87 CHARACTER_FLAG_UNK7 = 0x00000040,
88 CHARACTER_FLAG_UNK8 = 0x00000080,
89 CHARACTER_FLAG_UNK9 = 0x00000100,
90 CHARACTER_FLAG_UNK10 = 0x00000200,
91 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
92 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
93 CHARACTER_FLAG_UNK13 = 0x00001000,
94 CHARACTER_FLAG_GHOST = 0x00002000,
95 CHARACTER_FLAG_RENAME = 0x00004000,
96 CHARACTER_FLAG_UNK16 = 0x00008000,
97 CHARACTER_FLAG_UNK17 = 0x00010000,
98 CHARACTER_FLAG_UNK18 = 0x00020000,
99 CHARACTER_FLAG_UNK19 = 0x00040000,
100 CHARACTER_FLAG_UNK20 = 0x00080000,
101 CHARACTER_FLAG_UNK21 = 0x00100000,
102 CHARACTER_FLAG_UNK22 = 0x00200000,
103 CHARACTER_FLAG_UNK23 = 0x00400000,
104 CHARACTER_FLAG_UNK24 = 0x00800000,
105 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
106 CHARACTER_FLAG_DECLINED = 0x02000000,
107 CHARACTER_FLAG_UNK27 = 0x04000000,
108 CHARACTER_FLAG_UNK28 = 0x08000000,
109 CHARACTER_FLAG_UNK29 = 0x10000000,
110 CHARACTER_FLAG_UNK30 = 0x20000000,
111 CHARACTER_FLAG_UNK31 = 0x40000000,
112 CHARACTER_FLAG_UNK32 = 0x80000000
115 // corpse reclaim times
116 #define DEATH_EXPIRE_STEP (5*MINUTE)
117 #define MAX_DEATH_COUNT 3
119 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
121 //== PlayerTaxi ================================================
123 PlayerTaxi::PlayerTaxi()
125 // Taxi nodes
126 memset(m_taximask, 0, sizeof(m_taximask));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
131 // class specific initial known nodes
132 switch(chrClass)
134 case CLASS_DEATH_KNIGHT:
136 for(int i = 0; i < TaxiMaskSize; ++i)
137 m_taximask[i] |= sOldContinentsNodesMask[i];
138 break;
142 // race specific initial known nodes: capital and taxi hub masks
143 switch(race)
145 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
146 case RACE_ORC: SetTaximaskNode(23); break; // Orc
147 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
148 case RACE_NIGHTELF: SetTaximaskNode(26);
149 SetTaximaskNode(27); break; // Night Elf
150 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
151 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
152 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
153 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
154 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
155 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
158 // new continent starting masks (It will be accessible only at new map)
159 switch(Player::TeamForRace(race))
161 case ALLIANCE: SetTaximaskNode(100); break;
162 case HORDE: SetTaximaskNode(99); break;
164 // level dependent taxi hubs
165 if(level>=68)
166 SetTaximaskNode(213); //Shattered Sun Staging Area
169 void PlayerTaxi::LoadTaxiMask(const char* data)
171 Tokens tokens = StrSplit(data, " ");
173 int index;
174 Tokens::iterator iter;
175 for (iter = tokens.begin(), index = 0;
176 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
178 // load and set bits only for existed taxi nodes
179 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
183 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
185 if(all)
187 for (uint8 i=0; i<TaxiMaskSize; ++i)
188 data << uint32(sTaxiNodesMask[i]); // all existed nodes
190 else
192 for (uint8 i=0; i<TaxiMaskSize; ++i)
193 data << uint32(m_taximask[i]); // known nodes
197 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
199 ClearTaxiDestinations();
201 Tokens tokens = StrSplit(values," ");
203 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
205 uint32 node = uint32(atol(iter->c_str()));
206 AddTaxiDestination(node);
209 if(m_TaxiDestinations.empty())
210 return true;
212 // Check integrity
213 if(m_TaxiDestinations.size() < 2)
214 return false;
216 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
218 uint32 cost;
219 uint32 path;
220 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
221 if(!path)
222 return false;
225 // can't load taxi path without mount set (quest taxi path?)
226 if(!objmgr.GetTaxiMount(GetTaxiSource(),team,true))
227 return false;
229 return true;
232 std::string PlayerTaxi::SaveTaxiDestinationsToString()
234 if(m_TaxiDestinations.empty())
235 return "";
237 std::ostringstream ss;
239 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
240 ss << m_TaxiDestinations[i] << " ";
242 return ss.str();
245 uint32 PlayerTaxi::GetCurrentTaxiPath() const
247 if(m_TaxiDestinations.size() < 2)
248 return 0;
250 uint32 path;
251 uint32 cost;
253 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
255 return path;
258 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
260 ss << "'";
261 for(int i = 0; i < TaxiMaskSize; ++i)
262 ss << taxi.m_taximask[i] << " ";
263 ss << "'";
264 return ss;
267 //== Player ====================================================
269 UpdateMask Player::updateVisualBits;
271 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
273 m_transport = 0;
275 m_speakTime = 0;
276 m_speakCount = 0;
278 m_objectType |= TYPEMASK_PLAYER;
279 m_objectTypeId = TYPEID_PLAYER;
281 m_valuesCount = PLAYER_END;
283 m_session = session;
285 m_divider = 0;
287 m_ExtraFlags = 0;
288 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
289 SetAcceptTicket(true);
291 // players always accept
292 if(GetSession()->GetSecurity() == SEC_PLAYER)
293 SetAcceptWhispers(true);
295 m_curSelection = 0;
296 m_lootGuid = 0;
298 m_comboTarget = 0;
299 m_comboPoints = 0;
301 m_usedTalentCount = 0;
302 m_questRewardTalentCount = 0;
304 m_regenTimer = 0;
305 m_weaponChangeTimer = 0;
307 m_zoneUpdateId = 0;
308 m_zoneUpdateTimer = 0;
310 m_areaUpdateId = 0;
312 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
314 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
315 // this must help in case next save after mass player load after server startup
316 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
318 clearResurrectRequestData();
320 m_SpellModRemoveCount = 0;
322 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
324 m_social = NULL;
326 // group is initialized in the reference constructor
327 SetGroupInvite(NULL);
328 m_groupUpdateMask = 0;
329 m_auraUpdateMask = 0;
331 duel = NULL;
333 m_GuildIdInvited = 0;
334 m_ArenaTeamIdInvited = 0;
336 m_atLoginFlags = AT_LOGIN_NONE;
338 mSemaphoreTeleport_Near = false;
339 mSemaphoreTeleport_Far = false;
341 pTrader = 0;
342 ClearTrade();
344 m_cinematic = 0;
346 PlayerTalkClass = new PlayerMenu( GetSession() );
347 m_currentBuybackSlot = BUYBACK_SLOT_START;
349 m_DailyQuestChanged = false;
350 m_lastDailyQuestTime = 0;
352 for (int i=0; i<MAX_TIMERS; ++i)
353 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
355 m_MirrorTimerFlags = UNDERWATER_NONE;
356 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
357 m_isInWater = false;
358 m_drunkTimer = 0;
359 m_drunk = 0;
360 m_restTime = 0;
361 m_deathTimer = 0;
362 m_deathExpireTime = 0;
364 m_swingErrorMsg = 0;
366 m_DetectInvTimer = 1*IN_MILISECONDS;
368 m_bgBattleGroundID = 0;
369 m_bgTypeID = BATTLEGROUND_TYPE_NONE;
370 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
372 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
373 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
375 m_bgTeam = 0;
377 m_logintime = time(NULL);
378 m_Last_tick = m_logintime;
379 m_WeaponProficiency = 0;
380 m_ArmorProficiency = 0;
381 m_canParry = false;
382 m_canBlock = false;
383 m_canDualWield = false;
384 m_canTitanGrip = false;
385 m_ammoDPS = 0.0f;
387 m_temporaryUnsummonedPetNumber = 0;
388 //cache for UNIT_CREATED_BY_SPELL to allow
389 //returning reagents for temporarily removed pets
390 //when dying/logging out
391 m_oldpetspell = 0;
393 ////////////////////Rest System/////////////////////
394 time_inn_enter=0;
395 inn_pos_mapid=0;
396 inn_pos_x=0;
397 inn_pos_y=0;
398 inn_pos_z=0;
399 m_rest_bonus=0;
400 rest_type=REST_TYPE_NO;
401 ////////////////////Rest System/////////////////////
403 m_mailsLoaded = false;
404 m_mailsUpdated = false;
405 unReadMails = 0;
406 m_nextMailDelivereTime = 0;
408 m_resetTalentsCost = 0;
409 m_resetTalentsTime = 0;
410 m_itemUpdateQueueBlocked = false;
412 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
413 m_forced_speed_changes[i] = 0;
415 m_stableSlots = 0;
417 /////////////////// Instance System /////////////////////
419 m_HomebindTimer = 0;
420 m_InstanceValid = true;
421 m_dungeonDifficulty = DIFFICULTY_NORMAL;
423 m_lastPotionId = 0;
425 for (int i = 0; i < BASEMOD_END; ++i)
427 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
428 m_auraBaseMod[i][PCT_MOD] = 1.0f;
431 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
432 m_baseRatingValue[i] = 0;
434 m_baseSpellDamage = 0;
435 m_baseSpellHealing = 0;
436 m_baseFeralAP = 0;
437 m_baseManaRegen = 0;
439 // Honor System
440 m_lastHonorUpdateTime = time(NULL);
442 // Player summoning
443 m_summon_expire = 0;
444 m_summon_mapid = 0;
445 m_summon_x = 0.0f;
446 m_summon_y = 0.0f;
447 m_summon_z = 0.0f;
449 //Default movement to run mode
450 m_unit_movement_flags = 0;
452 m_mover = this;
454 m_miniPet = 0;
455 m_bgAfkReportedTimer = 0;
456 m_contestedPvPTimer = 0;
458 m_declinedname = NULL;
459 m_runes = NULL;
461 m_lastFallTime = 0;
462 m_lastFallZ = 0;
465 Player::~Player ()
467 CleanupsBeforeDelete();
469 // it must be unloaded already in PlayerLogout and accessed only for loggined player
470 //m_social = NULL;
472 // Note: buy back item already deleted from DB when player was saved
473 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
475 if(m_items[i])
476 delete m_items[i];
478 CleanupChannels();
480 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
481 delete itr->second;
483 //all mailed items should be deleted, also all mail should be deallocated
484 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
485 delete *itr;
487 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
488 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
490 delete PlayerTalkClass;
492 if (m_transport)
494 m_transport->RemovePassenger(this);
497 for(size_t x = 0; x < ItemSetEff.size(); x++)
498 if(ItemSetEff[x])
499 delete ItemSetEff[x];
501 // clean up player-instance binds, may unload some instance saves
502 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
503 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
504 itr->second.save->RemovePlayer(this);
506 delete m_declinedname;
507 delete m_runes;
510 void Player::CleanupsBeforeDelete()
512 if(m_uint32Values) // only for fully created Object
514 TradeCancel(false);
515 DuelComplete(DUEL_INTERUPTED);
517 Unit::CleanupsBeforeDelete();
520 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 )
522 //FIXME: outfitId not used in player creating
524 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
526 m_name = name;
528 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
529 if(!info)
531 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
532 return false;
535 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
536 m_items[i] = NULL;
538 m_race = race;
539 m_class = class_;
541 SetMapId(info->mapId);
542 Relocate(info->positionX,info->positionY,info->positionZ);
544 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
545 if(!cEntry)
547 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
548 return false;
551 uint8 powertype = cEntry->powerType;
553 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
554 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
556 switch(gender)
558 case GENDER_FEMALE:
559 SetDisplayId(info->displayId_f );
560 SetNativeDisplayId(info->displayId_f );
561 break;
562 case GENDER_MALE:
563 SetDisplayId(info->displayId_m );
564 SetNativeDisplayId(info->displayId_m );
565 break;
566 default:
567 sLog.outError("Invalid gender %u for player",gender);
568 return false;
569 break;
572 setFactionForRace(m_race);
574 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
576 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
577 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
578 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
579 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
580 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
581 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
583 // -1 is default value
584 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
586 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
587 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
588 SetByteValue(PLAYER_BYTES_3, 0, gender);
590 SetUInt32Value( PLAYER_GUILDID, 0 );
591 SetUInt32Value( PLAYER_GUILDRANK, 0 );
592 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
594 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
595 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
596 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 0 ); // 0=disabled
597 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
598 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
599 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
600 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
601 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
603 // set starting level
604 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
605 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
606 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
608 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
610 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
611 if(gm_level > start_level)
612 start_level = gm_level;
615 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
617 InitRunes();
619 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
620 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
621 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
623 // Played time
624 m_Last_tick = time(NULL);
625 m_Played_time[0] = 0;
626 m_Played_time[1] = 0;
628 // base stats and related field values
629 InitStatsForLevel();
630 InitTaxiNodesForLevel();
631 InitGlyphsForLevel();
632 InitTalentForLevel();
633 InitPrimaryProffesions(); // to max set before any spell added
635 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
636 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
637 SetHealth(GetMaxHealth());
638 if (getPowerType()==POWER_MANA)
640 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
641 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
644 if(getPowerType() == POWER_RUNIC_POWER)
646 SetPower(POWER_RUNE, 8);
647 SetMaxPower(POWER_RUNE, 8);
648 SetPower(POWER_RUNIC_POWER, 0);
649 SetMaxPower(POWER_RUNIC_POWER, 1000);
652 // original spells
653 learnDefaultSpells();
655 // original action bar
656 std::list<uint16>::const_iterator action_itr[4];
657 for(int i=0; i<4; ++i)
658 action_itr[i] = info->action[i].begin();
660 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
662 uint16 taction[4];
663 for(int i=0; i<4 ;++i)
664 taction[i] = (*action_itr[i]);
666 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
668 for(int i=0; i<4 ;++i)
669 ++action_itr[i];
672 // original items
673 CharStartOutfitEntry const* oEntry = NULL;
674 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
676 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
678 if(entry->RaceClassGender == RaceClassGender)
680 oEntry = entry;
681 break;
686 if(oEntry)
688 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
690 if(oEntry->ItemId[j] <= 0)
691 continue;
693 uint32 item_id = oEntry->ItemId[j];
696 // Hack for not existed item id in dbc 3.0.3
697 if(item_id==40582)
698 continue;
700 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
701 if(!iProto)
703 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
704 continue;
707 // max stack by default (mostly 1), 1 for infinity stackable
708 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
710 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
712 switch(iProto->Spells[0].SpellCategory)
714 case 11: // food
715 if(iProto->Stackable > 4)
716 count = 4;
717 break;
718 case 59: // drink
719 if(iProto->Stackable > 2)
720 count = 2;
721 break;
725 StoreNewItemInBestSlots(item_id, count);
729 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
730 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
732 // bags and main-hand weapon must equipped at this moment
733 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
734 // or ammo not equipped in special bag
735 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
737 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
739 uint16 eDest;
740 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
741 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
742 if( msg == EQUIP_ERR_OK )
744 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
745 EquipItem( eDest, pItem, true);
747 // move other items to more appropriate slots (ammo not equipped in special bag)
748 else
750 ItemPosCountVec sDest;
751 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
752 if( msg == EQUIP_ERR_OK )
754 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
755 pItem = StoreItem( sDest, pItem, true);
758 // if this is ammo then use it
759 msg = CanUseAmmo( pItem->GetEntry() );
760 if( msg == EQUIP_ERR_OK )
761 SetAmmo( pItem->GetEntry() );
765 // all item positions resolved
767 return true;
770 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
772 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
774 // attempt equip by one
775 while(titem_amount > 0)
777 uint16 eDest;
778 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
779 if( msg != EQUIP_ERR_OK )
780 break;
782 EquipNewItem( eDest, titem_id, true);
783 AutoUnequipOffhandIfNeed();
784 --titem_amount;
787 if(titem_amount == 0)
788 return true; // equipped
790 // attempt store
791 ItemPosCountVec sDest;
792 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
793 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
794 if( msg == EQUIP_ERR_OK )
796 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
797 return true; // stored
800 // item can't be added
801 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
802 return false;
805 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
807 if (MaxValue == DISABLED_MIRROR_TIMER)
809 if (CurrentValue!=DISABLED_MIRROR_TIMER)
810 StopMirrorTimer(Type);
811 return;
813 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
814 data << (uint32)Type;
815 data << CurrentValue;
816 data << MaxValue;
817 data << Regen;
818 data << (uint8)0;
819 data << (uint32)0; // spell id
820 GetSession()->SendPacket( &data );
823 void Player::StopMirrorTimer(MirrorTimerType Type)
825 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
826 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
827 data << (uint32)Type;
828 GetSession()->SendPacket( &data );
831 void Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
833 if(!isAlive() || isGameMaster())
834 return;
836 // Absorb, resist some environmental damage type
837 uint32 absorb = 0;
838 uint32 resist = 0;
839 if (type == DAMAGE_LAVA)
840 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
841 else if (type == DAMAGE_SLIME)
842 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
844 damage-=absorb+resist;
846 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
847 data << uint64(GetGUID());
848 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
849 data << uint32(damage);
850 data << uint32(absorb);
851 data << uint32(resist);
852 SendMessageToSet(&data, true);
854 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
856 if(!isAlive())
858 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
860 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
861 DurabilityLossAll(0.10f,false);
862 // durability lost message
863 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
864 GetSession()->SendPacket(&data2);
867 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
871 int32 Player::getMaxTimer(MirrorTimerType timer)
873 switch (timer)
875 case FATIGUE_TIMER:
876 return MINUTE*IN_MILISECONDS;
877 case BREATH_TIMER:
879 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
880 return DISABLED_MIRROR_TIMER;
881 int32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS;
882 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
883 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
884 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
885 return UnderWaterTime;
887 case FIRE_TIMER:
889 if (!isAlive())
890 return DISABLED_MIRROR_TIMER;
891 return 1*IN_MILISECONDS;
893 default:
894 return 0;
896 return 0;
899 void Player::UpdateMirrorTimers()
901 // Desync flags for update on next HandleDrowning
902 if (m_MirrorTimerFlags)
903 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
906 void Player::HandleDrowning(uint32 time_diff)
908 if (!m_MirrorTimerFlags)
909 return;
911 // In water
912 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
914 // Breath timer not activated - activate it
915 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
917 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
918 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
920 else // If activated - do tick
922 m_MirrorTimer[BREATH_TIMER]-=time_diff;
923 // Timer limit - need deal damage
924 if (m_MirrorTimer[BREATH_TIMER] < 0)
926 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
927 // Calculate and deal damage
928 // TODO: Check this formula
929 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
930 EnvironmentalDamage(DAMAGE_DROWNING, damage);
932 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
933 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
936 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
938 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
939 // Need breath regen
940 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
941 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
942 StopMirrorTimer(BREATH_TIMER);
943 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
944 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
947 // In dark water
948 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
950 // Fatigue timer not activated - activate it
951 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
953 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
954 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
956 else
958 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
959 // Timer limit - need deal damage or teleport ghost to graveyard
960 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
962 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
963 if (isAlive()) // Calculate and deal damage
965 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
966 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
968 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
969 RepopAtGraveyard();
971 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
972 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
975 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
977 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
978 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
979 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
980 StopMirrorTimer(FATIGUE_TIMER);
981 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
982 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
985 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
987 // Breath timer not activated - activate it
988 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
989 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
990 else
992 m_MirrorTimer[FIRE_TIMER]-=time_diff;
993 if (m_MirrorTimer[FIRE_TIMER] < 0)
995 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
996 // Calculate and deal damage
997 // TODO: Check this formula
998 uint32 damage = urand(600, 700);
999 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
1000 EnvironmentalDamage(DAMAGE_LAVA, damage);
1001 else
1002 EnvironmentalDamage(DAMAGE_SLIME, damage);
1006 else
1007 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
1009 // Recheck timers flag
1010 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1011 for (int i = 0; i< MAX_TIMERS; ++i)
1012 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1014 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1015 break;
1017 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1020 ///The player sobers by 256 every 10 seconds
1021 void Player::HandleSobering()
1023 m_drunkTimer = 0;
1025 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1026 SetDrunkValue(drunk);
1029 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1031 if(value >= 23000)
1032 return DRUNKEN_SMASHED;
1033 if(value >= 12800)
1034 return DRUNKEN_DRUNK;
1035 if(value & 0xFFFE)
1036 return DRUNKEN_TIPSY;
1037 return DRUNKEN_SOBER;
1040 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1042 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1044 m_drunk = newDrunkenValue;
1045 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1047 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1049 // special drunk invisibility detection
1050 if(newDrunkenState >= DRUNKEN_DRUNK)
1051 m_detectInvisibilityMask |= (1<<6);
1052 else
1053 m_detectInvisibilityMask &= ~(1<<6);
1055 if(newDrunkenState == oldDrunkenState)
1056 return;
1058 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1059 data << uint64(GetGUID());
1060 data << uint32(newDrunkenState);
1061 data << uint32(itemId);
1063 SendMessageToSet(&data, true);
1066 void Player::Update( uint32 p_time )
1068 if(!IsInWorld())
1069 return;
1071 // undelivered mail
1072 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1074 SendNewMail();
1075 ++unReadMails;
1077 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1078 m_nextMailDelivereTime = 0;
1081 Unit::Update( p_time );
1083 // update player only attacks
1084 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1086 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1089 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1091 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1094 time_t now = time (NULL);
1096 UpdatePvPFlag(now);
1098 UpdateContestedPvP(p_time);
1100 UpdateDuelFlag(now);
1102 CheckDuelDistance(now);
1104 UpdateAfkReport(now);
1106 // Update items that have just a limited lifetime
1107 if (now>m_Last_tick)
1108 UpdateItemDuration(uint32(now- m_Last_tick));
1110 if (!m_timedquests.empty())
1112 std::set<uint32>::iterator iter = m_timedquests.begin();
1113 while (iter != m_timedquests.end())
1115 QuestStatusData& q_status = mQuestStatus[*iter];
1116 if( q_status.m_timer <= p_time )
1118 uint32 quest_id = *iter;
1119 ++iter; // current iter will be removed in FailTimedQuest
1120 FailTimedQuest( quest_id );
1122 else
1124 q_status.m_timer -= p_time;
1125 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1126 ++iter;
1131 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1133 Unit *pVictim = getVictim();
1134 if (pVictim && !IsNonMeleeSpellCasted(false))
1136 // default combat reach 10
1137 // TODO add weapon,skill check
1139 float pldistance = ATTACK_DISTANCE;
1141 if (isAttackReady(BASE_ATTACK))
1143 if(!IsWithinDistInMap(pVictim, pldistance))
1145 setAttackTimer(BASE_ATTACK,100);
1146 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1148 SendAttackSwingNotInRange();
1149 m_swingErrorMsg = 1;
1152 //120 degrees of radiant range
1153 else if( !HasInArc( 2*M_PI/3, pVictim ))
1155 setAttackTimer(BASE_ATTACK,100);
1156 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1158 SendAttackSwingBadFacingAttack();
1159 m_swingErrorMsg = 2;
1162 else
1164 m_swingErrorMsg = 0; // reset swing error state
1166 // prevent base and off attack in same time, delay attack at 0.2 sec
1167 if(haveOffhandWeapon())
1169 uint32 off_att = getAttackTimer(OFF_ATTACK);
1170 if(off_att < ATTACK_DISPLAY_DELAY)
1171 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1173 AttackerStateUpdate(pVictim, BASE_ATTACK);
1174 resetAttackTimer(BASE_ATTACK);
1178 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1180 if(!IsWithinDistInMap(pVictim, pldistance))
1182 setAttackTimer(OFF_ATTACK,100);
1184 else if( !HasInArc( 2*M_PI/3, pVictim ))
1186 setAttackTimer(OFF_ATTACK,100);
1188 else
1190 // prevent base and off attack in same time, delay attack at 0.2 sec
1191 uint32 base_att = getAttackTimer(BASE_ATTACK);
1192 if(base_att < ATTACK_DISPLAY_DELAY)
1193 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1194 // do attack
1195 AttackerStateUpdate(pVictim, OFF_ATTACK);
1196 resetAttackTimer(OFF_ATTACK);
1200 Unit *owner = pVictim->GetOwner();
1201 Unit *u = owner ? owner : pVictim;
1202 if(u->IsPvP() && (!duel || duel->opponent != u))
1204 UpdatePvP(true);
1205 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1210 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1212 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1214 int time_inn = time(NULL)-GetTimeInnEnter();
1215 if (time_inn >= 10) //freeze update
1217 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1218 //speed collect rest bonus (section/in hour)
1219 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1220 UpdateInnerTime(time(NULL));
1225 if(m_regenTimer > 0)
1227 if(p_time >= m_regenTimer)
1228 m_regenTimer = 0;
1229 else
1230 m_regenTimer -= p_time;
1233 if (m_weaponChangeTimer > 0)
1235 if(p_time >= m_weaponChangeTimer)
1236 m_weaponChangeTimer = 0;
1237 else
1238 m_weaponChangeTimer -= p_time;
1241 if (m_zoneUpdateTimer > 0)
1243 if(p_time >= m_zoneUpdateTimer)
1245 uint32 newzone, newarea;
1246 GetZoneAndAreaId(newzone,newarea);
1248 if( m_zoneUpdateId != newzone )
1249 UpdateZone(newzone,newarea); // also update area
1250 else
1252 // use area updates as well
1253 // needed for free far all arenas for example
1254 if( m_areaUpdateId != newarea )
1255 UpdateArea(newarea);
1257 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1260 else
1261 m_zoneUpdateTimer -= p_time;
1264 if (isAlive())
1266 RegenerateAll();
1269 if (m_deathState == JUST_DIED)
1271 KillPlayer();
1274 if(m_nextSave > 0)
1276 if(p_time >= m_nextSave)
1278 // m_nextSave reseted in SaveToDB call
1279 SaveToDB();
1280 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1282 else
1284 m_nextSave -= p_time;
1288 //Handle Water/drowning
1289 HandleDrowning(p_time);
1291 //Handle detect stealth players
1292 if (m_DetectInvTimer > 0)
1294 if (p_time >= m_DetectInvTimer)
1296 m_DetectInvTimer = 3000;
1297 HandleStealthedUnitsDetection();
1299 else
1300 m_DetectInvTimer -= p_time;
1303 // Played time
1304 if (now > m_Last_tick)
1306 uint32 elapsed = uint32(now - m_Last_tick);
1307 m_Played_time[0] += elapsed; // Total played time
1308 m_Played_time[1] += elapsed; // Level played time
1309 m_Last_tick = now;
1312 if (m_drunk)
1314 m_drunkTimer += p_time;
1316 if (m_drunkTimer > 10*IN_MILISECONDS)
1317 HandleSobering();
1320 // not auto-free ghost from body in instances
1321 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1323 if(p_time >= m_deathTimer)
1325 m_deathTimer = 0;
1326 BuildPlayerRepop();
1327 RepopAtGraveyard();
1329 else
1330 m_deathTimer -= p_time;
1333 UpdateEnchantTime(p_time);
1334 UpdateHomebindTime(p_time);
1336 // group update
1337 SendUpdateToOutOfRangeGroupMembers();
1339 Pet* pet = GetPet();
1340 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1342 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1343 return;
1347 void Player::setDeathState(DeathState s)
1349 uint32 ressSpellId = 0;
1351 bool cur = isAlive();
1353 if(s == JUST_DIED && cur)
1355 // drunken state is cleared on death
1356 SetDrunkValue(0);
1357 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1358 ClearComboPoints();
1360 clearResurrectRequestData();
1362 // remove form before other mods to prevent incorrect stats calculation
1363 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1365 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1366 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1368 // remove uncontrolled pets
1369 RemoveMiniPet();
1370 RemoveGuardians();
1372 // save value before aura remove in Unit::setDeathState
1373 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1375 // passive spell
1376 if(!ressSpellId)
1377 ressSpellId = GetResurrectionSpellId();
1378 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1379 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1380 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1382 Unit::setDeathState(s);
1384 // restore resurrection spell id for player after aura remove
1385 if(s == JUST_DIED && cur && ressSpellId)
1386 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1388 if(isAlive() && !cur)
1390 //clear aura case after resurrection by another way (spells will be applied before next death)
1391 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1393 // restore default warrior stance
1394 if(getClass()== CLASS_WARRIOR)
1395 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1399 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1401 Field *fields = result->Fetch();
1403 *p_data << uint64(GetGUID());
1404 *p_data << m_name;
1406 *p_data << uint8(getRace());
1407 uint8 pClass = getClass();
1408 *p_data << uint8(pClass);
1409 *p_data << uint8(getGender());
1411 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1412 *p_data << uint8(bytes);
1413 *p_data << uint8(bytes >> 8);
1414 *p_data << uint8(bytes >> 16);
1415 *p_data << uint8(bytes >> 24);
1417 bytes = GetUInt32Value(PLAYER_BYTES_2);
1418 *p_data << uint8(bytes);
1420 *p_data << uint8(getLevel()); // player level
1421 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1422 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1423 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1424 *p_data << uint32(zoneId);
1425 *p_data << uint32(GetMapId());
1427 *p_data << GetPositionX();
1428 *p_data << GetPositionY();
1429 *p_data << GetPositionZ();
1431 // guild id
1432 *p_data << (result ? fields[13].GetUInt32() : 0);
1434 uint32 char_flags = 0;
1435 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1436 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1437 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1438 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1439 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1440 char_flags |= CHARACTER_FLAG_GHOST;
1441 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1442 char_flags |= CHARACTER_FLAG_RENAME;
1443 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1444 char_flags |= CHARACTER_FLAG_DECLINED;
1446 *p_data << uint32(char_flags); // character flags
1447 // character customize (flags?)
1448 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1449 *p_data << uint8(1); // unknown
1451 // Pets info
1453 uint32 petDisplayId = 0;
1454 uint32 petLevel = 0;
1455 uint32 petFamily = 0;
1457 // show pet at selection character in character list only for non-ghost character
1458 if (result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1460 uint32 entry = fields[10].GetUInt32();
1461 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1462 if(cInfo)
1464 petDisplayId = fields[11].GetUInt32();
1465 petLevel = fields[12].GetUInt32();
1466 petFamily = cInfo->family;
1470 *p_data << uint32(petDisplayId);
1471 *p_data << uint32(petLevel);
1472 *p_data << uint32(petFamily);
1475 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1477 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1478 uint32 item_id = GetUInt32Value(visualbase);
1479 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1480 SpellItemEnchantmentEntry const *enchant = NULL;
1482 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1484 uint32 enchantId = GetUInt16Value(visualbase + 1, enchantSlot);
1485 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1486 break;
1489 if (proto != NULL)
1491 *p_data << uint32(proto->DisplayInfoID);
1492 *p_data << uint8(proto->InventoryType);
1493 *p_data << uint32(enchant ? enchant->aura_id : 0);
1495 else
1497 *p_data << uint32(0);
1498 *p_data << uint8(0);
1499 *p_data << uint32(0); // enchant?
1502 *p_data << uint32(0); // first bag display id
1503 *p_data << uint8(0); // first bag inventory type
1504 *p_data << uint32(0); // enchant?
1507 bool Player::ToggleAFK()
1509 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1511 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1513 // afk player not allowed in battleground
1514 if(state && InBattleGround())
1515 LeaveBattleground();
1517 return state;
1520 bool Player::ToggleDND()
1522 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1524 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1527 uint8 Player::chatTag() const
1529 // it's bitmask
1530 // 0x8 - ??
1531 // 0x4 - gm
1532 // 0x2 - dnd
1533 // 0x1 - afk
1534 if(isGMChat())
1535 return 4;
1536 else if(isDND())
1537 return 3;
1538 if(isAFK())
1539 return 1;
1540 else
1541 return 0;
1544 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1546 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1548 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1549 return false;
1552 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1553 Pet* pet = GetPet();
1555 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1557 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1558 // don't let gm level > 1 either
1559 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1560 return false;
1562 // client without expansion support
1563 if(GetSession()->Expansion() < mEntry->Expansion())
1565 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1567 if(GetTransport())
1568 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1570 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1572 return false; // normal client can't teleport to this map...
1574 else
1576 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1579 // if we were on a transport, leave
1580 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1582 m_transport->RemovePassenger(this);
1583 m_transport = NULL;
1584 m_movementInfo.t_x = 0.0f;
1585 m_movementInfo.t_y = 0.0f;
1586 m_movementInfo.t_z = 0.0f;
1587 m_movementInfo.t_o = 0.0f;
1588 m_movementInfo.t_time = 0;
1591 // The player was ported to another map and looses the duel immediately.
1592 // We have to perform this check before the teleport, otherwise the
1593 // ObjectAccessor won't find the flag.
1594 if (duel && GetMapId()!=mapid)
1596 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1597 if (obj)
1598 DuelComplete(DUEL_FLED);
1601 // reset movement flags at teleport, because player will continue move with these flags after teleport
1602 m_movementInfo.flags = 0;
1604 if ((GetMapId() == mapid) && (!m_transport))
1606 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1608 //same map, only remove pet if out of range for new position
1609 if(pet && pet->GetDistance(x,y,z) >= OWNER_MAX_DISTANCE)
1610 UnsummonPetTemporaryIfAny();
1613 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1614 CombatStop();
1616 // this will be used instead of the current location in SaveToDB
1617 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1618 SetFallInformation(0, z);
1620 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1621 // at client packet MSG_MOVE_TELEPORT_ACK
1622 SetSemaphoreTeleportNear(true);
1623 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1624 if(!GetSession()->PlayerLogout())
1626 WorldPacket data;
1627 BuildTeleportAckMsg(&data, x, y, z, orientation);
1628 GetSession()->SendPacket(&data);
1631 else
1633 // far teleport to another map
1634 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1635 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1637 // Check enter rights before map getting to avoid creating instance copy for player
1638 // this check not dependent from map instance copy and same for all instance copies of selected map
1639 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1640 return false;
1642 // If the map is not created, assume it is possible to enter it.
1643 // It will be created in the WorldPortAck.
1644 Map *map = MapManager::Instance().FindMap(mapid);
1645 if (!map || map->CanEnter(this))
1647 SetSelection(0);
1649 CombatStop();
1651 ResetContestedPvP();
1653 // remove player from battleground on far teleport (when changing maps)
1654 if(BattleGround const* bg = GetBattleGround())
1656 // Note: at battleground join battleground id set before teleport
1657 // and we already will found "current" battleground
1658 // just need check that this is targeted map or leave
1659 if(bg->GetMapId() != mapid)
1660 LeaveBattleground(false); // don't teleport to entry point
1663 // remove pet on map change
1664 if (pet)
1665 UnsummonPetTemporaryIfAny();
1667 // remove all dyn objects
1668 RemoveAllDynObjects();
1670 // stop spellcasting
1671 // not attempt interrupt teleportation spell at caster teleport
1672 if(!(options & TELE_TO_SPELL))
1673 if(IsNonMeleeSpellCasted(true))
1674 InterruptNonMeleeSpells(true);
1676 if(!GetSession()->PlayerLogout())
1678 // send transfer packets
1679 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1680 data << uint32(mapid);
1681 if (m_transport)
1683 data << m_transport->GetEntry() << GetMapId();
1685 GetSession()->SendPacket(&data);
1687 data.Initialize(SMSG_NEW_WORLD, (20));
1688 if (m_transport)
1690 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1692 else
1694 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1696 GetSession()->SendPacket( &data );
1697 SendSavedInstances();
1699 // remove from old map now
1700 if(oldmap) oldmap->Remove(this, false);
1703 // new final coordinates
1704 float final_x = x;
1705 float final_y = y;
1706 float final_z = z;
1707 float final_o = orientation;
1709 if(m_transport)
1711 final_x += m_movementInfo.t_x;
1712 final_y += m_movementInfo.t_y;
1713 final_z += m_movementInfo.t_z;
1714 final_o += m_movementInfo.t_o;
1717 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1718 SetFallInformation(0, final_z);
1719 // if the player is saved before worldportack (at logout for example)
1720 // this will be used instead of the current location in SaveToDB
1722 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1724 // move packet sent by client always after far teleport
1725 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1726 SetSemaphoreTeleportFar(true);
1728 else
1729 return false;
1731 return true;
1734 void Player::AddToWorld()
1736 ///- Do not add/remove the player from the object storage
1737 ///- It will crash when updating the ObjectAccessor
1738 ///- The player should only be added when logging in
1739 Unit::AddToWorld();
1741 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1743 if(m_items[i])
1744 m_items[i]->AddToWorld();
1748 void Player::RemoveFromWorld()
1750 // cleanup
1751 if(IsInWorld())
1753 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1754 Uncharm();
1755 UnsummonAllTotems();
1756 RemoveMiniPet();
1757 RemoveGuardians();
1760 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1762 if(m_items[i])
1763 m_items[i]->RemoveFromWorld();
1766 ///- Do not add/remove the player from the object storage
1767 ///- It will crash when updating the ObjectAccessor
1768 ///- The player should only be removed when logging out
1769 Unit::RemoveFromWorld();
1772 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1774 float addRage;
1776 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1778 if(attacker)
1780 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1782 // talent who gave more rage on attack
1783 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1785 else
1787 addRage = damage/rageconversion*2.5;
1789 // Berserker Rage effect
1790 if(HasAura(18499,0))
1791 addRage *= 1.3;
1794 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1796 ModifyPower(POWER_RAGE, uint32(addRage*10));
1799 void Player::RegenerateAll()
1801 if (m_regenTimer != 0)
1802 return;
1803 uint32 regenDelay = 2000;
1805 // Not in combat or they have regeneration
1806 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1807 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1809 RegenerateHealth();
1810 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1812 Regenerate(POWER_RAGE);
1813 if(getClass() == CLASS_DEATH_KNIGHT)
1814 Regenerate(POWER_RUNIC_POWER);
1818 Regenerate( POWER_ENERGY );
1820 Regenerate( POWER_MANA );
1822 if(getClass() == CLASS_DEATH_KNIGHT)
1823 Regenerate( POWER_RUNE );
1825 m_regenTimer = regenDelay;
1828 void Player::Regenerate(Powers power)
1830 uint32 curValue = GetPower(power);
1831 uint32 maxValue = GetMaxPower(power);
1833 float addvalue = 0.0f;
1835 switch (power)
1837 case POWER_MANA:
1839 bool recentCast = IsUnderLastManaUseEffect();
1840 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1841 if (recentCast)
1843 // Mangos Updates Mana in intervals of 2s, which is correct
1844 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1846 else
1848 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1850 } break;
1851 case POWER_RAGE: // Regenerate rage
1853 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1854 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1855 } break;
1856 case POWER_ENERGY: // Regenerate energy (rogue)
1857 addvalue = 20;
1858 break;
1859 case POWER_RUNIC_POWER:
1861 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1862 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1863 } break;
1864 case POWER_RUNE:
1866 for(uint32 i = 0; i < MAX_RUNES; ++i)
1867 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1868 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1869 } break;
1870 case POWER_FOCUS:
1871 case POWER_HAPPINESS:
1872 case POWER_HEALTH:
1873 break;
1876 // Mana regen calculated in Player::UpdateManaRegen()
1877 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1878 if(power != POWER_MANA)
1880 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1881 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1882 if ((*i)->GetModifier()->m_miscvalue == power)
1883 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1886 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1888 curValue += uint32(addvalue);
1889 if (curValue > maxValue)
1890 curValue = maxValue;
1892 else
1894 if(curValue <= uint32(addvalue))
1895 curValue = 0;
1896 else
1897 curValue -= uint32(addvalue);
1899 SetPower(power, curValue);
1902 void Player::RegenerateHealth()
1904 uint32 curValue = GetHealth();
1905 uint32 maxValue = GetMaxHealth();
1907 if (curValue >= maxValue) return;
1909 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1911 float addvalue = 0.0f;
1913 // polymorphed case
1914 if ( IsPolymorphed() )
1915 addvalue = GetMaxHealth()/3;
1916 // normal regen case (maybe partly in combat case)
1917 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1919 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1920 if (!isInCombat())
1922 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1923 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1924 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1926 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1927 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1929 if(!IsStandState())
1930 addvalue *= 1.5;
1933 // always regeneration bonus (including combat)
1934 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1936 if(addvalue < 0)
1937 addvalue = 0;
1939 ModifyHealth(int32(addvalue));
1942 bool Player::CanInteractWithNPCs(bool alive) const
1944 if(alive && !isAlive())
1945 return false;
1946 if(isInFlight())
1947 return false;
1949 return true;
1952 Creature*
1953 Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
1955 // unit checks
1956 if (!guid)
1957 return NULL;
1959 if(!IsInWorld())
1960 return NULL;
1962 // exist (we need look pets also for some interaction (quest/etc)
1963 Creature *unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
1964 if (!unit)
1965 return NULL;
1967 // player check
1968 if(!CanInteractWithNPCs(!unit->isSpiritService()))
1969 return NULL;
1971 // appropriate npc type
1972 if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
1973 return NULL;
1975 // alive or spirit healer
1976 if(!unit->isAlive() && (!unit->isSpiritService() || isAlive() ))
1977 return NULL;
1979 // not allow interaction under control, but allow with own pets
1980 if(unit->GetCharmerGUID())
1981 return NULL;
1983 // not enemy
1984 if( unit->IsHostileTo(this))
1985 return NULL;
1987 // not unfriendly
1988 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
1989 if(factionTemplate->faction)
1990 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
1991 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
1992 return NULL;
1994 // not too far
1995 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
1996 return NULL;
1998 return unit;
2001 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
2003 if(GameObject *go = GetMap()->GetGameObject(guid))
2005 if(go->GetGoType() == type)
2007 float maxdist;
2008 switch(type)
2010 // TODO: find out how the client calculates the maximal usage distance to spellless working
2011 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2012 case GAMEOBJECT_TYPE_GUILD_BANK:
2013 case GAMEOBJECT_TYPE_MAILBOX:
2014 maxdist = 10.0f;
2015 break;
2016 case GAMEOBJECT_TYPE_FISHINGHOLE:
2017 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2018 break;
2019 default:
2020 maxdist = INTERACTION_DISTANCE;
2021 break;
2024 if (go->IsWithinDistInMap(this, maxdist))
2025 return go;
2027 sLog.outError("IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go->GetGOInfo()->name,
2028 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2031 return NULL;
2034 bool Player::IsUnderWater() const
2036 return IsInWater() &&
2037 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2040 void Player::SetInWater(bool apply)
2042 if(m_isInWater==apply)
2043 return;
2045 //define player in water by opcodes
2046 //move player's guid into HateOfflineList of those mobs
2047 //which can't swim and move guid back into ThreatList when
2048 //on surface.
2049 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2050 m_isInWater = apply;
2052 // remove auras that need water/land
2053 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2055 getHostilRefManager().updateThreatTables();
2058 void Player::SetGameMaster(bool on)
2060 if(on)
2062 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2063 setFaction(35);
2064 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2066 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2067 ResetContestedPvP();
2069 getHostilRefManager().setOnlineOfflineState(false);
2070 CombatStop();
2072 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2074 else
2076 // restore phase
2077 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2078 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2080 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2081 setFactionForRace(getRace());
2082 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2084 // restore FFA PvP Server state
2085 if(sWorld.IsFFAPvPRealm())
2086 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2088 // restore FFA PvP area state, remove not allowed for GM mounts
2089 UpdateArea(m_areaUpdateId);
2091 getHostilRefManager().setOnlineOfflineState(true);
2094 ObjectAccessor::UpdateVisibilityForPlayer(this);
2097 void Player::SetGMVisible(bool on)
2099 if(on)
2101 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2103 // Reapply stealth/invisibility if active or show if not any
2104 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2105 SetVisibility(VISIBILITY_GROUP_STEALTH);
2106 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2107 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2108 else
2109 SetVisibility(VISIBILITY_ON);
2111 else
2113 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2115 SetAcceptWhispers(false);
2116 SetGameMaster(true);
2118 SetVisibility(VISIBILITY_OFF);
2122 bool Player::IsGroupVisibleFor(Player* p) const
2124 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2126 default: return IsInSameGroupWith(p);
2127 case 1: return IsInSameRaidWith(p);
2128 case 2: return GetTeam()==p->GetTeam();
2132 bool Player::IsInSameGroupWith(Player const* p) const
2134 return p==this || GetGroup() != NULL &&
2135 GetGroup() == p->GetGroup() &&
2136 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2139 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2140 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2141 void Player::UninviteFromGroup()
2143 Group* group = GetGroupInvite();
2144 if(!group)
2145 return;
2147 group->RemoveInvite(this);
2149 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2151 if(group->IsCreated())
2153 group->Disband(true);
2154 objmgr.RemoveGroup(group);
2156 else
2157 group->RemoveAllInvites();
2159 delete group;
2163 void Player::RemoveFromGroup(Group* group, uint64 guid)
2165 if(group)
2167 if (group->RemoveMember(guid, 0) <= 1)
2169 // group->Disband(); already disbanded in RemoveMember
2170 objmgr.RemoveGroup(group);
2171 delete group;
2172 // removemember sets the player's group pointer to NULL
2177 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2179 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2180 data << uint64(victim ? victim->GetGUID() : 0); // guid
2181 data << uint32(GivenXP+RestXP); // given experience
2182 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2183 if(victim)
2185 data << uint32(GivenXP); // experience without rested bonus
2186 data << float(1); // 1 - none 0 - 100% group bonus output
2188 data << uint8(0); // new 2.4.0
2189 GetSession()->SendPacket(&data);
2192 void Player::GiveXP(uint32 xp, Unit* victim)
2194 if ( xp < 1 )
2195 return;
2197 if(!isAlive())
2198 return;
2200 uint32 level = getLevel();
2202 // XP to money conversion processed in Player::RewardQuest
2203 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2204 return;
2206 // handle SPELL_AURA_MOD_XP_PCT auras
2207 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2208 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2209 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2211 // XP resting bonus for kill
2212 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2214 SendLogXPGain(xp,victim,rested_bonus_xp);
2216 uint32 curXP = GetUInt32Value(PLAYER_XP);
2217 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2218 uint32 newXP = curXP + xp + rested_bonus_xp;
2220 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2222 newXP -= nextLvlXP;
2224 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2225 GiveLevel(level + 1);
2227 level = getLevel();
2228 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2231 SetUInt32Value(PLAYER_XP, newXP);
2234 // Update player to next level
2235 // Current player experience not update (must be update by caller)
2236 void Player::GiveLevel(uint32 level)
2238 if ( level == getLevel() )
2239 return;
2241 PlayerLevelInfo info;
2242 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2244 PlayerClassLevelInfo classInfo;
2245 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2247 // send levelup info to client
2248 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2249 data << uint32(level);
2250 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2251 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2252 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2253 data << uint32(0);
2254 data << uint32(0);
2255 data << uint32(0);
2256 data << uint32(0);
2257 data << uint32(0);
2258 data << uint32(0);
2259 // end for
2260 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2261 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2263 GetSession()->SendPacket(&data);
2265 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2267 //update level, max level of skills
2268 if(getLevel()!= level)
2269 m_Played_time[1] = 0; // Level Played Time reset
2270 SetLevel(level);
2271 UpdateSkillsForLevel ();
2273 // save base values (bonuses already included in stored stats
2274 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2275 SetCreateStat(Stats(i), info.stats[i]);
2277 SetCreateHealth(classInfo.basehealth);
2278 SetCreateMana(classInfo.basemana);
2280 InitTalentForLevel();
2281 InitTaxiNodesForLevel();
2282 InitGlyphsForLevel();
2284 UpdateAllStats();
2286 // set current level health and mana/energy to maximum after applying all mods.
2287 SetHealth(GetMaxHealth());
2288 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2289 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2290 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2291 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2292 SetPower(POWER_FOCUS, 0);
2293 SetPower(POWER_HAPPINESS, 0);
2295 // give level to summoned pet
2296 Pet* pet = GetPet();
2297 if(pet && pet->getPetType()==SUMMON_PET)
2298 pet->GivePetLevel(level);
2299 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2302 void Player::InitTalentForLevel()
2304 uint32 level = getLevel();
2305 // talents base at level diff ( talents = level - 9 but some can be used already)
2306 if(level < 10)
2308 // Remove all talent points
2309 if(m_usedTalentCount > 0) // Free any used talents
2311 resetTalents(true);
2312 SetFreeTalentPoints(0);
2315 else
2317 uint32 talentPointsForLevel = CalculateTalentsPoints();
2319 // if used more that have then reset
2320 if(m_usedTalentCount > talentPointsForLevel)
2322 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2323 resetTalents(true);
2324 else
2325 SetFreeTalentPoints(0);
2327 // else update amount of free points
2328 else
2329 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2332 SendTalentsInfoData(false); // update at client
2335 void Player::InitStatsForLevel(bool reapplyMods)
2337 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2338 _RemoveAllStatBonuses();
2340 PlayerClassLevelInfo classInfo;
2341 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2343 PlayerLevelInfo info;
2344 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2346 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2347 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2349 UpdateSkillsForLevel ();
2351 // set default cast time multiplier
2352 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2354 // reset size before reapply auras
2355 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2357 // save base values (bonuses already included in stored stats
2358 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2359 SetCreateStat(Stats(i), info.stats[i]);
2361 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2362 SetStat(Stats(i), info.stats[i]);
2364 SetCreateHealth(classInfo.basehealth);
2366 //set create powers
2367 SetCreateMana(classInfo.basemana);
2369 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2371 InitStatBuffMods();
2373 //reset rating fields values
2374 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2375 SetUInt32Value(index, 0);
2377 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2378 for (int i = 0; i < 7; ++i)
2380 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2381 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2382 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2385 //reset attack power, damage and attack speed fields
2386 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2387 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2388 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2390 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2391 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2392 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2393 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2394 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2395 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2397 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2398 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2399 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2400 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2401 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2402 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2404 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2405 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2406 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2407 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2409 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2410 for (uint8 i = 0; i < 7; ++i)
2411 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2413 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2414 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2415 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2417 // Dodge percentage
2418 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2420 // set armor (resistance 0) to original value (create_agility*2)
2421 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2422 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2423 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2424 // set other resistance to original value (0)
2425 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2427 SetResistance(SpellSchools(i), 0);
2428 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2429 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2432 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2433 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2434 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2436 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2437 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2439 // Reset no reagent cost field
2440 for(int i = 0; i < 3; ++i)
2441 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2442 // Init data for form but skip reapply item mods for form
2443 InitDataForForm(reapplyMods);
2445 // save new stats
2446 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2447 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2449 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2451 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2452 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2454 // cleanup unit flags (will be re-applied if need at aura load).
2455 RemoveFlag( UNIT_FIELD_FLAGS,
2456 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2457 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2458 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2459 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2460 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2461 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2463 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2465 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2466 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2468 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2469 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2471 // restore if need some important flags
2472 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2474 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2475 _ApplyAllStatBonuses();
2477 // set current level health and mana/energy to maximum after applying all mods.
2478 SetHealth(GetMaxHealth());
2479 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2480 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2481 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2482 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2483 SetPower(POWER_FOCUS, 0);
2484 SetPower(POWER_HAPPINESS, 0);
2485 SetPower(POWER_RUNIC_POWER, 0);
2488 void Player::SendInitialSpells()
2490 time_t curTime = time(NULL);
2491 time_t infTime = curTime + MONTH/2;
2493 uint16 spellCount = 0;
2495 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2496 data << uint8(0);
2498 size_t countPos = data.wpos();
2499 data << uint16(spellCount); // spell count placeholder
2501 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2503 if(itr->second->state == PLAYERSPELL_REMOVED)
2504 continue;
2506 if(!itr->second->active || itr->second->disabled)
2507 continue;
2509 data << uint32(itr->first);
2510 data << uint16(0); // it's not slot id
2512 spellCount +=1;
2515 data.put<uint16>(countPos,spellCount); // write real count value
2517 uint16 spellCooldowns = m_spellCooldowns.size();
2518 data << uint16(spellCooldowns);
2519 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2521 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2522 if(!sEntry)
2523 continue;
2525 // not send infinity cooldown
2526 if(itr->second.end > infTime)
2527 continue;
2529 data << uint32(itr->first);
2531 time_t cooldown = 0;
2532 if(itr->second.end > curTime)
2533 cooldown = (itr->second.end-curTime)*IN_MILISECONDS;
2535 data << uint16(itr->second.itemid); // cast item id
2536 data << uint16(sEntry->Category); // spell category
2537 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2539 data << uint32(0); // cooldown
2540 data << uint32(cooldown); // category cooldown
2542 else
2544 data << uint32(cooldown); // cooldown
2545 data << uint32(0); // category cooldown
2549 GetSession()->SendPacket(&data);
2551 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2554 void Player::RemoveMail(uint32 id)
2556 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2558 if ((*itr)->messageID == id)
2560 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2561 m_mail.erase(itr);
2562 return;
2567 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2569 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2570 data << (uint32) mailId;
2571 data << (uint32) mailAction;
2572 data << (uint32) mailError;
2573 if ( mailError == MAIL_ERR_BAG_FULL )
2574 data << (uint32) equipError;
2575 else if( mailAction == MAIL_ITEM_TAKEN )
2577 data << (uint32) item_guid; // item guid low?
2578 data << (uint32) item_count; // item count?
2580 GetSession()->SendPacket(&data);
2583 void Player::SendNewMail()
2585 // deliver undelivered mail
2586 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2587 data << (uint32) 0;
2588 GetSession()->SendPacket(&data);
2591 void Player::UpdateNextMailTimeAndUnreads()
2593 // calculate next delivery time (min. from non-delivered mails
2594 // and recalculate unReadMail
2595 time_t cTime = time(NULL);
2596 m_nextMailDelivereTime = 0;
2597 unReadMails = 0;
2598 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2600 if((*itr)->deliver_time > cTime)
2602 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2603 m_nextMailDelivereTime = (*itr)->deliver_time;
2605 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2606 ++unReadMails;
2610 void Player::AddNewMailDeliverTime(time_t deliver_time)
2612 if(deliver_time <= time(NULL)) // ready now
2614 ++unReadMails;
2615 SendNewMail();
2617 else // not ready and no have ready mails
2619 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2620 m_nextMailDelivereTime = deliver_time;
2624 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2626 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2627 if (!spellInfo)
2629 // do character spell book cleanup (all characters)
2630 if(!IsInWorld() && !learning) // spell load case
2632 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2633 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2635 else
2636 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2638 return false;
2641 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2643 // do character spell book cleanup (all characters)
2644 if(!IsInWorld() && !learning) // spell load case
2646 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2647 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2649 else
2650 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2652 return false;
2655 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2657 bool dependent_set = false;
2658 bool disabled_case = false;
2659 bool superceded_old = false;
2661 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2662 if (itr != m_spells.end())
2664 uint32 next_active_spell_id = 0;
2665 // fix activate state for non-stackable low rank (and find next spell for !active case)
2666 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2668 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2669 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2671 if(HasSpell(next_itr->second))
2673 // high rank already known so this must !active
2674 active = false;
2675 next_active_spell_id = next_itr->second;
2676 break;
2681 // not do anything if already known in expected state
2682 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2683 itr->second->dependent == dependent && itr->second->disabled == disabled)
2685 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2686 itr->second->state = PLAYERSPELL_UNCHANGED;
2688 return false;
2691 // dependent spell known as not dependent, overwrite state
2692 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2694 itr->second->dependent = dependent;
2695 if (itr->second->state != PLAYERSPELL_NEW)
2696 itr->second->state = PLAYERSPELL_CHANGED;
2697 dependent_set = true;
2700 // update active state for known spell
2701 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2703 itr->second->active = active;
2705 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2706 itr->second->state = PLAYERSPELL_UNCHANGED;
2707 else if(itr->second->state != PLAYERSPELL_NEW)
2708 itr->second->state = PLAYERSPELL_CHANGED;
2710 if(active)
2712 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2713 CastSpell (this,spell_id,true);
2715 else if(IsInWorld())
2717 if(next_active_spell_id)
2719 // update spell ranks in spellbook and action bar
2720 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2721 data << uint32(spell_id);
2722 data << uint32(next_active_spell_id);
2723 GetSession()->SendPacket( &data );
2725 else
2727 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2728 data << uint32(spell_id);
2729 GetSession()->SendPacket(&data);
2733 return active; // learn (show in spell book if active now)
2736 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2738 if(itr->second->state != PLAYERSPELL_NEW)
2739 itr->second->state = PLAYERSPELL_CHANGED;
2740 itr->second->disabled = disabled;
2742 if(disabled)
2743 return false;
2745 disabled_case = true;
2747 else switch(itr->second->state)
2749 case PLAYERSPELL_UNCHANGED: // known saved spell
2750 return false;
2751 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2753 delete itr->second;
2754 m_spells.erase(itr);
2755 state = PLAYERSPELL_CHANGED;
2756 break; // need re-add
2758 default: // known not saved yet spell (new or modified)
2760 // can be in case spell loading but learned at some previous spell loading
2761 if(!IsInWorld() && !learning && !dependent_set)
2762 itr->second->state = PLAYERSPELL_UNCHANGED;
2764 return false;
2769 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2771 // talent: unlearn all other talent ranks (high and low)
2772 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2774 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2776 for(int i=0; i < MAX_TALENT_RANK; ++i)
2778 // skip learning spell and no rank spell case
2779 uint32 rankSpellId = talentInfo->RankID[i];
2780 if(!rankSpellId || rankSpellId==spell_id)
2781 continue;
2783 removeSpell(rankSpellId);
2787 // non talent spell: learn low ranks (recursive call)
2788 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2790 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2791 addSpell(prev_spell,active,true,true,disabled);
2792 else // at normal learning
2793 learnSpell(prev_spell,true);
2796 PlayerSpell *newspell = new PlayerSpell;
2797 newspell->state = state;
2798 newspell->active = active;
2799 newspell->dependent = dependent;
2800 newspell->disabled = disabled;
2802 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2803 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2805 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
2807 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
2808 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
2809 if(!i_spellInfo) continue;
2811 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
2813 if(itr2->second->active)
2815 if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
2817 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2819 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2820 data << uint32(itr2->first);
2821 data << uint32(spell_id);
2822 GetSession()->SendPacket( &data );
2825 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2826 itr2->second->active = false;
2827 if(itr2->second->state != PLAYERSPELL_NEW)
2828 itr2->second->state = PLAYERSPELL_CHANGED;
2829 superceded_old = true; // new spell replace old in action bars and spell book.
2831 else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
2833 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2835 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2836 data << uint32(spell_id);
2837 data << uint32(itr2->first);
2838 GetSession()->SendPacket( &data );
2841 // mark new spell as disable (not learned yet for client and will not learned)
2842 newspell->active = false;
2843 if(newspell->state != PLAYERSPELL_NEW)
2844 newspell->state = PLAYERSPELL_CHANGED;
2851 m_spells[spell_id] = newspell;
2853 // return false if spell disabled
2854 if (newspell->disabled)
2855 return false;
2858 uint32 talentCost = GetTalentSpellCost(spell_id);
2860 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2861 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2862 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2864 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2865 CastSpell(this, spell_id, true);
2867 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2868 else if (IsPassiveSpell(spell_id))
2870 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2871 CastSpell(this, spell_id, true);
2873 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2875 CastSpell(this, spell_id, true);
2876 return false;
2879 // update used talent points count
2880 m_usedTalentCount += talentCost;
2882 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2883 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2885 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2886 SetFreePrimaryProffesions(freeProfs-1);
2889 // add dependent skills
2890 uint16 maxskill = GetMaxSkillValueForLevel();
2892 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2894 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2895 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2897 if(spellLearnSkill)
2899 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2900 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2902 if(skill_value < spellLearnSkill->value)
2903 skill_value = spellLearnSkill->value;
2905 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2907 if(skill_max_value < new_skill_max_value)
2908 skill_max_value = new_skill_max_value;
2910 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2912 else
2914 // not ranked skills
2915 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2917 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2918 if(!pSkill)
2919 continue;
2921 if(HasSkill(pSkill->id))
2922 continue;
2924 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2925 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2926 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
2928 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2930 case SKILL_RANGE_LANGUAGE:
2931 SetSkill(pSkill->id, 300, 300 );
2932 break;
2933 case SKILL_RANGE_LEVEL:
2934 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2935 break;
2936 case SKILL_RANGE_MONO:
2937 SetSkill(pSkill->id, 1, 1 );
2938 break;
2939 default:
2940 break;
2946 // learn dependent spells
2947 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2948 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2950 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2952 if(!itr2->second.autoLearned)
2954 if(!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
2955 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
2956 else // at normal learning
2957 learnSpell(itr2->second.spell,true);
2961 if(!GetSession()->PlayerLoading())
2963 // not ranked skills
2964 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2966 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
2967 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
2970 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
2973 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2974 return active && !disabled && !superceded_old;
2977 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
2979 bool need_cast = false;
2981 switch(spellInfo->Id)
2983 // some spells not have stance data expacted cast at form change or present
2984 case 5420: need_cast = (m_form == FORM_TREE); break;
2985 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
2986 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
2987 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
2988 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
2989 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
2990 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
2991 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
2992 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2993 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2994 // another spells have proper stance data
2995 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
2998 //Check CasterAuraStates
2999 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3002 void Player::learnSpell(uint32 spell_id, bool dependent)
3004 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3006 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3007 bool active = disabled ? itr->second->active : true;
3009 bool learning = addSpell(spell_id,active,true,dependent,false);
3011 // learn all disabled higher ranks (recursive)
3012 if(disabled)
3014 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3015 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3017 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3018 if (iter != m_spells.end() && iter->second->disabled)
3019 learnSpell(i->second,false);
3023 // prevent duplicated entires in spell book, also not send if not in world (loading)
3024 if(!learning || !IsInWorld ())
3025 return;
3027 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3028 data << uint32(spell_id);
3029 GetSession()->SendPacket(&data);
3032 void Player::removeSpell(uint32 spell_id, bool disabled, bool update_action_bar_for_low_rank)
3034 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3035 if (itr == m_spells.end())
3036 return;
3038 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
3039 return;
3041 // unlearn non talent higher ranks (recursive)
3042 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3043 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3044 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3045 removeSpell(itr2->second,disabled);
3047 bool cur_active = itr->second->active;
3048 bool cur_dependent = itr->second->dependent;
3050 if (disabled)
3052 itr->second->disabled = disabled;
3053 if(itr->second->state != PLAYERSPELL_NEW)
3054 itr->second->state = PLAYERSPELL_CHANGED;
3056 else
3058 if(itr->second->state == PLAYERSPELL_NEW)
3060 delete itr->second;
3061 m_spells.erase(itr);
3063 else
3064 itr->second->state = PLAYERSPELL_REMOVED;
3067 RemoveAurasDueToSpell(spell_id);
3069 // remove pet auras
3070 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
3071 RemovePetAura(petSpell);
3073 // free talent points
3074 uint32 talentCosts = GetTalentSpellCost(spell_id);
3075 if(talentCosts > 0)
3077 if(talentCosts < m_usedTalentCount)
3078 m_usedTalentCount -= talentCosts;
3079 else
3080 m_usedTalentCount = 0;
3083 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3084 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3086 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
3087 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3088 SetFreePrimaryProffesions(freeProfs);
3091 // remove dependent skill
3092 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3093 if(spellLearnSkill)
3095 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3096 if(!prev_spell) // first rank, remove skill
3097 SetSkill(spellLearnSkill->skill,0,0);
3098 else
3100 // search prev. skill setting by spell ranks chain
3101 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3102 while(!prevSkill && prev_spell)
3104 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3105 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3108 if(!prevSkill) // not found prev skill setting, remove skill
3109 SetSkill(spellLearnSkill->skill,0,0);
3110 else // set to prev. skill setting values
3112 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3113 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3115 if(skill_value > prevSkill->value)
3116 skill_value = prevSkill->value;
3118 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3120 if(skill_max_value > new_skill_max_value)
3121 skill_max_value = new_skill_max_value;
3123 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3128 else
3130 // not ranked skills
3131 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3132 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3134 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3136 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3137 if(!pSkill)
3138 continue;
3140 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3141 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3142 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
3144 // not reset skills for professions and racial abilities
3145 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3146 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3147 continue;
3149 SetSkill(pSkill->id, 0, 0 );
3154 // remove dependent spells
3155 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3156 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3158 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3159 removeSpell(itr2->second.spell, disabled);
3161 // activate lesser rank in spellbook/action bar, and cast it if need
3162 bool prev_activate = false;
3164 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3166 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3168 // if talent then lesser rank also talent and need learn
3169 if(talentCosts)
3170 learnSpell (prev_id,false);
3171 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3172 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3174 // need manually update dependence state (learn spell ignore like attempts)
3175 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3176 if (prev_itr != m_spells.end())
3178 if(prev_itr->second->dependent != cur_dependent)
3180 prev_itr->second->dependent = cur_dependent;
3181 if(prev_itr->second->state != PLAYERSPELL_NEW)
3182 prev_itr->second->state = PLAYERSPELL_CHANGED;
3185 // now re-learn if need re-activate
3186 if(cur_active && !prev_itr->second->active)
3188 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3190 if(update_action_bar_for_low_rank)
3192 // downgrade spell ranks in spellbook and action bar
3193 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
3194 data << uint32(spell_id);
3195 data << uint32(prev_id);
3196 GetSession()->SendPacket( &data );
3197 prev_activate = true;
3205 // remove from spell book if not replaced by lesser rank
3206 if(!prev_activate)
3208 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3209 data << uint32(spell_id);
3210 GetSession()->SendPacket(&data);
3214 void Player::RemoveArenaSpellCooldowns()
3216 // remove cooldowns on spells that has < 15 min CD
3217 SpellCooldowns::iterator itr, next;
3218 // iterate spell cooldowns
3219 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3221 next = itr;
3222 ++next;
3223 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3224 // check if spellentry is present and if the cooldown is less than 15 mins
3225 if( entry &&
3226 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3227 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3229 // notify player
3230 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3231 data << uint32(itr->first);
3232 data << uint64(GetGUID());
3233 GetSession()->SendPacket(&data);
3234 // remove cooldown
3235 m_spellCooldowns.erase(itr);
3240 void Player::RemoveAllSpellCooldown()
3242 if(!m_spellCooldowns.empty())
3244 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3246 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3247 data << uint32(itr->first);
3248 data << uint64(GetGUID());
3249 GetSession()->SendPacket(&data);
3251 m_spellCooldowns.clear();
3255 void Player::_LoadSpellCooldowns(QueryResult *result)
3257 // some cooldowns can be already set at aura loading...
3259 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3261 if(result)
3263 time_t curTime = time(NULL);
3267 Field *fields = result->Fetch();
3269 uint32 spell_id = fields[0].GetUInt32();
3270 uint32 item_id = fields[1].GetUInt32();
3271 time_t db_time = (time_t)fields[2].GetUInt64();
3273 if(!sSpellStore.LookupEntry(spell_id))
3275 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3276 continue;
3279 // skip outdated cooldown
3280 if(db_time <= curTime)
3281 continue;
3283 AddSpellCooldown(spell_id, item_id, db_time);
3285 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3287 while( result->NextRow() );
3289 delete result;
3293 void Player::_SaveSpellCooldowns()
3295 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3297 time_t curTime = time(NULL);
3298 time_t infTime = curTime + MONTH/2;
3300 // remove outdated and save active
3301 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3303 if(itr->second.end <= curTime)
3304 m_spellCooldowns.erase(itr++);
3305 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3307 CharacterDatabase.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" I64FMTD "')", GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
3308 ++itr;
3310 else
3311 ++itr;
3315 uint32 Player::resetTalentsCost() const
3317 // The first time reset costs 1 gold
3318 if(m_resetTalentsCost < 1*GOLD)
3319 return 1*GOLD;
3320 // then 5 gold
3321 else if(m_resetTalentsCost < 5*GOLD)
3322 return 5*GOLD;
3323 // After that it increases in increments of 5 gold
3324 else if(m_resetTalentsCost < 10*GOLD)
3325 return 10*GOLD;
3326 else
3328 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3329 if(months > 0)
3331 // This cost will be reduced by a rate of 5 gold per month
3332 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3333 // to a minimum of 10 gold.
3334 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3336 else
3338 // After that it increases in increments of 5 gold
3339 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3340 // until it hits a cap of 50 gold.
3341 if(new_cost > 50*GOLD)
3342 new_cost = 50*GOLD;
3343 return new_cost;
3348 bool Player::resetTalents(bool no_cost)
3350 // not need after this call
3351 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3353 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3354 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3357 uint32 talentPointsForLevel = CalculateTalentsPoints();
3359 if (m_usedTalentCount == 0)
3361 SetFreeTalentPoints(talentPointsForLevel);
3362 return false;
3365 uint32 cost = 0;
3367 if(!no_cost)
3369 cost = resetTalentsCost();
3371 if (GetMoney() < cost)
3373 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3374 return false;
3378 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3380 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3382 if (!talentInfo) continue;
3384 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3386 if(!talentTabInfo)
3387 continue;
3389 // unlearn only talents for character class
3390 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3391 // to prevent unexpected lost normal learned spell skip another class talents
3392 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3393 continue;
3395 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3397 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3399 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3401 ++itr;
3402 continue;
3405 // remove learned spells (all ranks)
3406 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3408 // unlearn if first rank is talent or learned by talent
3409 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3411 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3412 itr = GetSpellMap().begin();
3413 continue;
3415 else
3416 ++itr;
3421 SetFreeTalentPoints(talentPointsForLevel);
3423 if(!no_cost)
3425 ModifyMoney(-(int32)cost);
3426 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3427 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3429 m_resetTalentsCost = cost;
3430 m_resetTalentsTime = time(NULL);
3433 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3434 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3436 if(m_canTitanGrip)
3438 m_canTitanGrip = false;
3439 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3440 AutoUnequipOffhandIfNeed();
3443 return true;
3446 Mail* Player::GetMail(uint32 id)
3448 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3450 if ((*itr)->messageID == id)
3452 return (*itr);
3455 return NULL;
3458 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3460 if(target == this)
3462 Object::_SetCreateBits(updateMask, target);
3464 else
3466 for(uint16 index = 0; index < m_valuesCount; index++)
3468 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3469 updateMask->SetBit(index);
3474 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3476 if(target == this)
3478 Object::_SetUpdateBits(updateMask, target);
3480 else
3482 Object::_SetUpdateBits(updateMask, target);
3483 *updateMask &= updateVisualBits;
3487 void Player::InitVisibleBits()
3489 updateVisualBits.SetCount(PLAYER_END);
3491 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3492 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3493 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3494 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3495 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3496 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3497 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3498 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3499 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3500 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3501 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3502 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3503 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3504 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3505 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3506 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3507 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3508 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3509 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3510 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3511 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3512 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3513 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3514 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3515 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3516 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3517 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3518 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3519 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3520 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3521 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3522 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3523 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3524 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3525 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3526 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3527 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3528 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3529 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3530 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3531 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3532 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3533 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3534 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3535 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3536 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3537 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3538 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3539 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3540 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3541 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3542 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3543 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3544 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3545 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3547 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3548 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3549 updateVisualBits.SetBit(PLAYER_FLAGS);
3550 updateVisualBits.SetBit(PLAYER_GUILDID);
3551 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3552 updateVisualBits.SetBit(PLAYER_BYTES);
3553 updateVisualBits.SetBit(PLAYER_BYTES_2);
3554 updateVisualBits.SetBit(PLAYER_BYTES_3);
3555 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3556 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3558 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3559 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3560 updateVisualBits.SetBit(i);
3562 // Players visible items are not inventory stuff
3563 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3565 uint32 offset = i * 2;
3567 // item entry
3568 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3569 // enchant
3570 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3573 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3576 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3578 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3580 if(m_items[i] == NULL)
3581 continue;
3583 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3586 if(target == this)
3588 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3590 if(m_items[i] == NULL)
3591 continue;
3593 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3595 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3597 if(m_items[i] == NULL)
3598 continue;
3600 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3604 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3607 void Player::DestroyForPlayer( Player *target ) const
3609 Unit::DestroyForPlayer( target );
3611 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3613 if(m_items[i] == NULL)
3614 continue;
3616 m_items[i]->DestroyForPlayer( target );
3619 if(target == this)
3621 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3623 if(m_items[i] == NULL)
3624 continue;
3626 m_items[i]->DestroyForPlayer( target );
3628 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3630 if(m_items[i] == NULL)
3631 continue;
3633 m_items[i]->DestroyForPlayer( target );
3638 bool Player::HasSpell(uint32 spell) const
3640 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3641 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3642 !itr->second->disabled);
3645 bool Player::HasActiveSpell(uint32 spell) const
3647 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3648 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3649 itr->second->active && !itr->second->disabled);
3652 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3654 if (!trainer_spell)
3655 return TRAINER_SPELL_RED;
3657 if (!trainer_spell->learnedSpell)
3658 return TRAINER_SPELL_RED;
3660 // known spell
3661 if(HasSpell(trainer_spell->learnedSpell))
3662 return TRAINER_SPELL_GRAY;
3664 // check race/class requirement
3665 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3666 return TRAINER_SPELL_RED;
3668 // check level requirement
3669 if(getLevel() < trainer_spell->reqLevel)
3670 return TRAINER_SPELL_RED;
3672 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3674 // check prev.rank requirement
3675 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3676 return TRAINER_SPELL_RED;
3678 // check additional spell requirement
3679 if(spell_chain->req && !HasSpell(spell_chain->req))
3680 return TRAINER_SPELL_RED;
3683 // check skill requirement
3684 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3685 return TRAINER_SPELL_RED;
3687 // exist, already checked at loading
3688 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3690 // secondary prof. or not prof. spell
3691 uint32 skill = spell->EffectMiscValue[1];
3693 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3694 return TRAINER_SPELL_GREEN;
3696 // check primary prof. limit
3697 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3698 return TRAINER_SPELL_GREEN_DISABLED;
3700 return TRAINER_SPELL_GREEN;
3703 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3705 uint32 guid = GUID_LOPART(playerguid);
3707 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3708 // bones will be deleted by corpse/bones deleting thread shortly
3709 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3711 // remove from guild
3712 uint32 guildId = GetGuildIdFromDB(playerguid);
3713 if(guildId != 0)
3715 Guild* guild = objmgr.GetGuildById(guildId);
3716 if(guild)
3717 guild->DelMember(guid);
3720 // remove from arena teams
3721 LeaveAllArenaTeams(playerguid);
3723 // the player was uninvited already on logout so just remove from group
3724 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3725 if(resultGroup)
3727 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3728 delete resultGroup;
3729 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3730 if(group)
3732 RemoveFromGroup(group, playerguid);
3736 // remove signs from petitions (also remove petitions if owner);
3737 RemovePetitionsAndSigns(playerguid, 10);
3739 // return back all mails with COD and Item 0 1 2 3 4 5 6
3740 QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,mailTemplateId,sender,subject,itemTextId,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid);
3741 if(resultMail)
3745 Field *fields = resultMail->Fetch();
3747 uint32 mail_id = fields[0].GetUInt32();
3748 uint16 mailTemplateId= fields[1].GetUInt16();
3749 uint32 sender = fields[2].GetUInt32();
3750 std::string subject = fields[3].GetCppString();
3751 uint32 itemTextId = fields[4].GetUInt32();
3752 uint32 money = fields[5].GetUInt32();
3753 bool has_items = fields[6].GetBool();
3755 //we can return mail now
3756 //so firstly delete the old one
3757 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3759 MailItemsInfo mi;
3760 if(has_items)
3762 // data needs to be at first place for Item::LoadFromDB
3763 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);
3764 if(resultItems)
3768 Field *fields2 = resultItems->Fetch();
3770 uint32 item_guidlow = fields2[1].GetUInt32();
3771 uint32 item_template = fields2[2].GetUInt32();
3773 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3774 if(!itemProto)
3776 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3777 continue;
3780 Item *pItem = NewItemOrBag(itemProto);
3781 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3783 pItem->FSetState(ITEM_REMOVED);
3784 pItem->SaveToDB(); // it also deletes item object !
3785 continue;
3788 mi.AddItem(item_guidlow, item_template, pItem);
3790 while (resultItems->NextRow());
3792 delete resultItems;
3796 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3798 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3800 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3802 while (resultMail->NextRow());
3804 delete resultMail;
3807 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3808 // Get guids of character's pets, will deleted in transaction
3809 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3811 // NOW we can finally clear other DB data related to character
3812 CharacterDatabase.BeginTransaction();
3813 if (resultPets)
3817 Field *fields3 = resultPets->Fetch();
3818 uint32 petguidlow = fields3[0].GetUInt32();
3819 Pet::DeleteFromDB(petguidlow);
3820 } while (resultPets->NextRow());
3821 delete resultPets;
3824 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3825 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3826 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3827 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3828 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3829 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3830 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3831 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3832 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3833 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3834 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3835 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3836 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3837 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3838 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3839 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3840 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3841 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3842 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3843 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3844 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3845 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3846 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
3847 CharacterDatabase.CommitTransaction();
3849 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3850 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3853 void Player::SetMovement(PlayerMovementType pType)
3855 WorldPacket data;
3856 switch(pType)
3858 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3859 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3860 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3861 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3862 default:
3863 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3864 return;
3866 data.append(GetPackGUID());
3867 data << uint32(0);
3868 GetSession()->SendPacket( &data );
3871 /* Preconditions:
3872 - a resurrectable corpse must not be loaded for the player (only bones)
3873 - the player must be in world
3875 void Player::BuildPlayerRepop()
3877 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3878 data.append(GetPackGUID());
3879 GetSession()->SendPacket(&data);
3881 if(getRace() == RACE_NIGHTELF)
3882 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)
3883 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3885 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3886 // there must be SMSG.STOP_MIRROR_TIMER
3887 // there we must send 888 opcode
3889 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3890 if(GetCorpse())
3892 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3893 assert(false);
3896 // create a corpse and place it at the player's location
3897 CreateCorpse();
3898 Corpse *corpse = GetCorpse();
3899 if(!corpse)
3901 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3902 return;
3904 GetMap()->Add(corpse);
3906 // convert player body to ghost
3907 SetHealth( 1 );
3909 SetMovement(MOVE_WATER_WALK);
3910 if(!GetSession()->isLogingOut())
3911 SetMovement(MOVE_UNROOT);
3913 // BG - remove insignia related
3914 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3916 SendCorpseReclaimDelay();
3918 // to prevent cheating
3919 corpse->ResetGhostTime();
3921 StopMirrorTimers(); //disable timers(bars)
3923 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3925 // set and clear other
3926 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
3929 void Player::SendDelayResponse(const uint32 ml_seconds)
3931 //FIXME: is this delay time arg really need? 50msec by default in code
3932 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3933 data << (uint32)time(NULL);
3934 data << (uint32)0;
3935 GetSession()->SendPacket( &data );
3938 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3940 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3941 data << uint32(-1);
3942 data << float(0);
3943 data << float(0);
3944 data << float(0);
3945 GetSession()->SendPacket(&data);
3947 // speed change, land walk
3949 // remove death flag + set aura
3950 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3951 if(getRace() == RACE_NIGHTELF)
3952 RemoveAurasDueToSpell(20584); // speed bonuses
3953 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3955 setDeathState(ALIVE);
3957 SetMovement(MOVE_LAND_WALK);
3958 SetMovement(MOVE_UNROOT);
3960 m_deathTimer = 0;
3962 // set health/powers (0- will be set in caller)
3963 if(restore_percent>0.0f)
3965 SetHealth(uint32(GetMaxHealth()*restore_percent));
3966 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3967 SetPower(POWER_RAGE, 0);
3968 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3971 // trigger update zone for alive state zone updates
3972 uint32 newzone, newarea;
3973 GetZoneAndAreaId(newzone,newarea);
3974 UpdateZone(newzone,newarea);
3976 // update visibility
3977 ObjectAccessor::UpdateVisibilityForPlayer(this);
3979 if(!applySickness)
3980 return;
3982 //Characters from level 1-10 are not affected by resurrection sickness.
3983 //Characters from level 11-19 will suffer from one minute of sickness
3984 //for each level they are above 10.
3985 //Characters level 20 and up suffer from ten minutes of sickness.
3986 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3988 if(int32(getLevel()) >= startLevel)
3990 // set resurrection sickness
3991 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3993 // not full duration
3994 if(int32(getLevel()) < startLevel+9)
3996 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3998 for(int i =0; i < 3; ++i)
4000 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4002 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4003 Aur->SendAuraUpdate(false);
4010 void Player::KillPlayer()
4012 SetMovement(MOVE_ROOT);
4014 StopMirrorTimers(); //disable timers(bars)
4016 setDeathState(CORPSE);
4017 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4019 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4020 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4022 // 6 minutes until repop at graveyard
4023 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4025 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4027 // don't create corpse at this moment, player might be falling
4029 // update visibility
4030 ObjectAccessor::UpdateObjectVisibility(this);
4033 void Player::CreateCorpse()
4035 // prevent existence 2 corpse for player
4036 SpawnCorpseBones();
4038 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4040 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4041 SetPvPDeath(false);
4043 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4045 delete corpse;
4046 return;
4049 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4050 _pb = GetUInt32Value(PLAYER_BYTES);
4051 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4053 uint8 race = (uint8)(_uf);
4054 uint8 skin = (uint8)(_pb);
4055 uint8 face = (uint8)(_pb >> 8);
4056 uint8 hairstyle = (uint8)(_pb >> 16);
4057 uint8 haircolor = (uint8)(_pb >> 24);
4058 uint8 facialhair = (uint8)(_pb2);
4060 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4061 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4063 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4064 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4066 uint32 flags = CORPSE_FLAG_UNK2;
4067 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4068 flags |= CORPSE_FLAG_HIDE_HELM;
4069 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4070 flags |= CORPSE_FLAG_HIDE_CLOAK;
4071 if(InBattleGround() && !InArena())
4072 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4073 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4075 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4077 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4079 uint32 iDisplayID;
4080 uint16 iIventoryType;
4081 uint32 _cfi;
4082 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4084 if(m_items[i])
4086 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4087 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4089 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4090 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4094 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4095 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4096 assert(entry);
4097 if(entry->map_type != MAP_BATTLEGROUND)
4098 corpse->SaveToDB();
4100 // register for player, but not show
4101 ObjectAccessor::Instance().AddCorpse(corpse);
4104 void Player::SpawnCorpseBones()
4106 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4107 SaveToDB(); // prevent loading as ghost without corpse
4110 Corpse* Player::GetCorpse() const
4112 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4115 void Player::DurabilityLossAll(double percent, bool inventory)
4117 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4118 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4119 DurabilityLoss(pItem,percent);
4121 if(inventory)
4123 // bags not have durability
4124 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4126 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4127 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4128 DurabilityLoss(pItem,percent);
4130 // keys not have durability
4131 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4133 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4134 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4135 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4136 if(Item* pItem = GetItemByPos( i, j ))
4137 DurabilityLoss(pItem,percent);
4141 void Player::DurabilityLoss(Item* item, double percent)
4143 if(!item )
4144 return;
4146 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4148 if(!pMaxDurability)
4149 return;
4151 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4153 if(pDurabilityLoss < 1 )
4154 pDurabilityLoss = 1;
4156 DurabilityPointsLoss(item,pDurabilityLoss);
4159 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4161 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4162 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4163 DurabilityPointsLoss(pItem,points);
4165 if(inventory)
4167 // bags not have durability
4168 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4170 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4171 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4172 DurabilityPointsLoss(pItem,points);
4174 // keys not have durability
4175 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4177 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4178 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4179 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4180 if(Item* pItem = GetItemByPos( i, j ))
4181 DurabilityPointsLoss(pItem,points);
4185 void Player::DurabilityPointsLoss(Item* item, int32 points)
4187 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4188 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4189 int32 pNewDurability = pOldDurability - points;
4191 if (pNewDurability < 0)
4192 pNewDurability = 0;
4193 else if (pNewDurability > pMaxDurability)
4194 pNewDurability = pMaxDurability;
4196 if (pOldDurability != pNewDurability)
4198 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4199 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4200 _ApplyItemMods(item,item->GetSlot(), false);
4202 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4204 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4205 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4206 _ApplyItemMods(item,item->GetSlot(), true);
4208 item->SetState(ITEM_CHANGED, this);
4212 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4214 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4215 DurabilityPointsLoss(pItem,1);
4218 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4220 uint32 TotalCost = 0;
4221 // equipped, backpack, bags itself
4222 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4223 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4225 // bank, buyback and keys not repaired
4227 // items in inventory bags
4228 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4229 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4230 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4231 return TotalCost;
4234 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4236 Item* item = GetItemByPos(pos);
4238 uint32 TotalCost = 0;
4239 if(!item)
4240 return TotalCost;
4242 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4243 if(!maxDurability)
4244 return TotalCost;
4246 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4248 if(cost)
4250 uint32 LostDurability = maxDurability - curDurability;
4251 if(LostDurability>0)
4253 ItemPrototype const *ditemProto = item->GetProto();
4255 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4256 if(!dcost)
4258 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4259 return TotalCost;
4262 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4263 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4264 if(!dQualitymodEntry)
4266 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4267 return TotalCost;
4270 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4271 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4273 costs = uint32(costs * discountMod);
4275 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4276 costs = 1;
4278 if (guildBank)
4280 if (GetGuildId()==0)
4282 DEBUG_LOG("You are not member of a guild");
4283 return TotalCost;
4286 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4287 if (!pGuild)
4288 return TotalCost;
4290 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4292 DEBUG_LOG("You do not have rights to withdraw for repairs");
4293 return TotalCost;
4296 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4298 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4299 return TotalCost;
4302 if (pGuild->GetGuildBankMoney() < costs)
4304 DEBUG_LOG("There is not enough money in bank");
4305 return TotalCost;
4308 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4309 TotalCost = costs;
4311 else if (GetMoney() < costs)
4313 DEBUG_LOG("You do not have enough money");
4314 return TotalCost;
4316 else
4317 ModifyMoney( -int32(costs) );
4321 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4322 item->SetState(ITEM_CHANGED, this);
4324 // reapply mods for total broken and repaired item if equipped
4325 if(IsEquipmentPos(pos) && !curDurability)
4326 _ApplyItemMods(item,pos & 255, true);
4327 return TotalCost;
4330 void Player::RepopAtGraveyard()
4332 // note: this can be called also when the player is alive
4333 // for example from WorldSession::HandleMovementOpcodes
4335 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4337 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4338 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4340 ResurrectPlayer(0.5f);
4341 SpawnCorpseBones();
4344 WorldSafeLocsEntry const *ClosestGrave = NULL;
4346 // Special handle for battleground maps
4347 if( BattleGround *bg = GetBattleGround() )
4348 ClosestGrave = bg->GetClosestGraveYard(this);
4349 else
4350 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4352 // stop countdown until repop
4353 m_deathTimer = 0;
4355 // if no grave found, stay at the current location
4356 // and don't show spirit healer location
4357 if(ClosestGrave)
4359 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4360 if(isDead()) // not send if alive, because it used in TeleportTo()
4362 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4363 data << ClosestGrave->map_id;
4364 data << ClosestGrave->x;
4365 data << ClosestGrave->y;
4366 data << ClosestGrave->z;
4367 GetSession()->SendPacket(&data);
4372 void Player::JoinedChannel(Channel *c)
4374 m_channels.push_back(c);
4377 void Player::LeftChannel(Channel *c)
4379 m_channels.remove(c);
4382 void Player::CleanupChannels()
4384 while(!m_channels.empty())
4386 Channel* ch = *m_channels.begin();
4387 m_channels.erase(m_channels.begin()); // remove from player's channel list
4388 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4389 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4390 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4393 sLog.outDebug("Player: channels cleaned up!");
4396 void Player::UpdateLocalChannels(uint32 newZone )
4398 if(m_channels.empty())
4399 return;
4401 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4402 if(!current_zone)
4403 return;
4405 ChannelMgr* cMgr = channelMgr(GetTeam());
4406 if(!cMgr)
4407 return;
4409 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4411 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4413 next = i; ++next;
4415 // skip non built-in channels
4416 if(!(*i)->IsConstant())
4417 continue;
4419 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4420 if(!ch)
4421 continue;
4423 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4424 continue;
4426 // new channel
4427 char new_channel_name_buf[100];
4428 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4429 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4431 if((*i)!=new_channel)
4433 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4435 // leave old channel
4436 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4437 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4438 LeftChannel(*i); // remove from player's channel list
4439 cMgr->LeftChannel(name); // delete if empty
4442 sLog.outDebug("Player: channels cleaned up!");
4445 void Player::LeaveLFGChannel()
4447 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4449 if((*i)->IsLFG())
4451 (*i)->Leave(GetGUID());
4452 break;
4457 void Player::UpdateDefense()
4459 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4461 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4463 // update dependent from defense skill part
4464 UpdateDefenseBonusesMod();
4468 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4470 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4472 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4473 return;
4476 float val = 1.0f;
4478 switch(modType)
4480 case FLAT_MOD:
4481 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4482 break;
4483 case PCT_MOD:
4484 if(amount <= -100.0f)
4485 amount = -200.0f;
4487 val = (100.0f + amount) / 100.0f;
4488 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4489 break;
4492 if(!CanModifyStats())
4493 return;
4495 switch(modGroup)
4497 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4498 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4499 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4500 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4501 default: break;
4505 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4507 if(modGroup >= BASEMOD_END || modType > MOD_END)
4509 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4510 return 0.0f;
4513 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4514 return 0.0f;
4516 return m_auraBaseMod[modGroup][modType];
4519 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4521 if(modGroup >= BASEMOD_END)
4523 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4524 return 0.0f;
4527 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4528 return 0.0f;
4530 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4533 uint32 Player::GetShieldBlockValue() const
4535 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4537 value = (value < 0) ? 0 : value;
4539 return uint32(value);
4542 float Player::GetMeleeCritFromAgility()
4544 uint32 level = getLevel();
4545 uint32 pclass = getClass();
4547 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4549 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4550 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4551 if (critBase==NULL || critRatio==NULL)
4552 return 0.0f;
4554 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4555 return crit*100.0f;
4558 float Player::GetDodgeFromAgility()
4560 // Table for base dodge values
4561 float dodge_base[MAX_CLASSES] = {
4562 0.0075f, // Warrior
4563 0.00652f, // Paladin
4564 -0.0545f, // Hunter
4565 -0.0059f, // Rogue
4566 0.03183f, // Priest
4567 0.0114f, // DK
4568 0.0167f, // Shaman
4569 0.034575f, // Mage
4570 0.02011f, // Warlock
4571 0.0f, // ??
4572 -0.0187f // Druid
4574 // Crit/agility to dodge/agility coefficient multipliers
4575 float crit_to_dodge[MAX_CLASSES] = {
4576 1.1f, // Warrior
4577 1.0f, // Paladin
4578 1.6f, // Hunter
4579 2.0f, // Rogue
4580 1.0f, // Priest
4581 1.0f, // DK?
4582 1.0f, // Shaman
4583 1.0f, // Mage
4584 1.0f, // Warlock
4585 0.0f, // ??
4586 1.7f // Druid
4589 uint32 level = getLevel();
4590 uint32 pclass = getClass();
4592 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4594 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4595 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4596 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4597 return 0.0f;
4599 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4600 return dodge*100.0f;
4603 float Player::GetSpellCritFromIntellect()
4605 uint32 level = getLevel();
4606 uint32 pclass = getClass();
4608 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4610 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4611 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4612 if (critBase==NULL || critRatio==NULL)
4613 return 0.0f;
4615 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4616 return crit*100.0f;
4619 float Player::GetRatingCoefficient(CombatRating cr) const
4621 uint32 level = getLevel();
4623 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4625 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4626 if (Rating == NULL)
4627 return 1.0f; // By default use minimum coefficient (not must be called)
4629 return Rating->ratio;
4632 float Player::GetRatingBonusValue(CombatRating cr) const
4634 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4637 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4639 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f;
4640 if (melee>33.0f) melee = 33.0f;
4641 return uint32 (melee * damage /100.0f);
4644 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4646 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f;
4647 if (ranged>33.0f) ranged=33.0f;
4648 return uint32 (ranged * damage /100.0f);
4651 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4653 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f;
4654 // In wow script resilience limited to 33%
4655 if (spell>33.0f)
4656 spell = 33.0f;
4657 return uint32 (spell * damage / 100.0f);
4660 uint32 Player::GetDotDamageReduction(uint32 damage) const
4662 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4663 // Dot resilience not limited (limit it by 100%)
4664 if (spellDot > 100.0f)
4665 spellDot = 100.0f;
4666 return uint32 (spellDot * damage / 100.0f);
4669 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4671 switch (attType)
4673 case BASE_ATTACK:
4674 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4675 case OFF_ATTACK:
4676 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4677 default:
4678 break;
4680 return 0.0f;
4683 float Player::OCTRegenHPPerSpirit()
4685 uint32 level = getLevel();
4686 uint32 pclass = getClass();
4688 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4690 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4691 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4692 if (baseRatio==NULL || moreRatio==NULL)
4693 return 0.0f;
4695 // Formula from PaperDollFrame script
4696 float spirit = GetStat(STAT_SPIRIT);
4697 float baseSpirit = spirit;
4698 if (baseSpirit>50) baseSpirit = 50;
4699 float moreSpirit = spirit - baseSpirit;
4700 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4701 return regen;
4704 float Player::OCTRegenMPPerSpirit()
4706 uint32 level = getLevel();
4707 uint32 pclass = getClass();
4709 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4711 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4712 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4713 if (moreRatio==NULL)
4714 return 0.0f;
4716 // Formula get from PaperDollFrame script
4717 float spirit = GetStat(STAT_SPIRIT);
4718 float regen = spirit * moreRatio->ratio;
4719 return regen;
4722 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4724 m_baseRatingValue[cr]+=(apply ? value : -value);
4726 int32 amount = uint32(m_baseRatingValue[cr]);
4727 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4728 // stat used stored in miscValueB for this aura
4729 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4730 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4731 if ((*i)->GetMiscValue() & (1<<cr))
4732 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4733 if (amount < 0)
4734 amount = 0;
4735 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4737 float RatingCoeffecient = GetRatingCoefficient(cr);
4738 float RatingChange = 0.0f;
4740 bool affectStats = CanModifyStats();
4742 switch (cr)
4744 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4745 case CR_DEFENSE_SKILL:
4746 UpdateDefenseBonusesMod();
4747 break;
4748 case CR_DODGE:
4749 UpdateDodgePercentage();
4750 break;
4751 case CR_PARRY:
4752 UpdateParryPercentage();
4753 break;
4754 case CR_BLOCK:
4755 UpdateBlockPercentage();
4756 break;
4757 case CR_HIT_MELEE:
4758 UpdateMeleeHitChances();
4759 break;
4760 case CR_HIT_RANGED:
4761 UpdateRangedHitChances();
4762 break;
4763 case CR_HIT_SPELL:
4764 UpdateSpellHitChances();
4765 break;
4766 case CR_CRIT_MELEE:
4767 if(affectStats)
4769 UpdateCritPercentage(BASE_ATTACK);
4770 UpdateCritPercentage(OFF_ATTACK);
4772 break;
4773 case CR_CRIT_RANGED:
4774 if(affectStats)
4775 UpdateCritPercentage(RANGED_ATTACK);
4776 break;
4777 case CR_CRIT_SPELL:
4778 if(affectStats)
4779 UpdateAllSpellCritChances();
4780 break;
4781 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4782 case CR_HIT_TAKEN_RANGED:
4783 break;
4784 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4785 break;
4786 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4787 case CR_CRIT_TAKEN_RANGED:
4788 break;
4789 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4790 break;
4791 case CR_HASTE_MELEE:
4792 RatingChange = value / RatingCoeffecient;
4793 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4794 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4795 break;
4796 case CR_HASTE_RANGED:
4797 RatingChange = value / RatingCoeffecient;
4798 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4799 break;
4800 case CR_HASTE_SPELL:
4801 RatingChange = value / RatingCoeffecient;
4802 ApplyCastTimePercentMod(RatingChange,apply);
4803 break;
4804 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4805 case CR_WEAPON_SKILL_OFFHAND:
4806 case CR_WEAPON_SKILL_RANGED:
4807 break;
4808 case CR_EXPERTISE:
4809 if(affectStats)
4811 UpdateExpertise(BASE_ATTACK);
4812 UpdateExpertise(OFF_ATTACK);
4814 break;
4815 case CR_ARMOR_PENETRATION:
4816 break;
4820 void Player::SetRegularAttackTime()
4822 for(int i = 0; i < MAX_ATTACK; ++i)
4824 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4825 if(tmpitem && !tmpitem->IsBroken())
4827 ItemPrototype const *proto = tmpitem->GetProto();
4828 if(proto->Delay)
4829 SetAttackTime(WeaponAttackType(i), proto->Delay);
4830 else
4831 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4836 //skill+step, checking for max value
4837 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4839 if(!skill_id)
4840 return false;
4842 uint16 i=0;
4843 for (; i < PLAYER_MAX_SKILLS; ++i)
4844 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4845 break;
4847 if(i>=PLAYER_MAX_SKILLS)
4848 return false;
4850 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4851 uint32 value = SKILL_VALUE(data);
4852 uint32 max = SKILL_MAX(data);
4854 if ((!max) || (!value) || (value >= max))
4855 return false;
4857 if (value*512 < max*urand(0,512))
4859 uint32 new_value = value+step;
4860 if(new_value > max)
4861 new_value = max;
4863 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4864 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
4865 return true;
4868 return false;
4871 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4873 if ( SkillValue >= GrayLevel )
4874 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4875 if ( SkillValue >= GreenLevel )
4876 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4877 if ( SkillValue >= YellowLevel )
4878 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4879 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4882 bool Player::UpdateCraftSkill(uint32 spellid)
4884 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4886 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4887 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4889 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4891 if(_spell_idx->second->skillId)
4893 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4895 // Alchemy Discoveries here
4896 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4897 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4899 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4900 learnSpell(discoveredSpell,false);
4903 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4905 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4906 _spell_idx->second->max_value,
4907 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4908 _spell_idx->second->min_value),
4909 craft_skill_gain);
4912 return false;
4915 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4917 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4919 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4921 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4922 switch (SkillId)
4924 case SKILL_HERBALISM:
4925 case SKILL_LOCKPICKING:
4926 case SKILL_JEWELCRAFTING:
4927 case SKILL_INSCRIPTION:
4928 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4929 case SKILL_SKINNING:
4930 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4931 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4932 else
4933 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4934 case SKILL_MINING:
4935 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4936 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4937 else
4938 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4940 return false;
4943 bool Player::UpdateFishingSkill()
4945 sLog.outDebug("UpdateFishingSkill");
4947 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4949 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4951 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4953 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4956 // levels sync. with spell requirement for skill levels to learn
4957 // bonus abilities in sSkillLineAbilityStore
4958 // Used only to avoid scan DBC at each skill grow
4959 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
4961 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4963 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4964 if ( !SkillId )
4965 return false;
4967 if(Chance <= 0) // speedup in 0 chance case
4969 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4970 return false;
4973 uint16 i=0;
4974 for (; i < PLAYER_MAX_SKILLS; ++i)
4975 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4976 if ( i >= PLAYER_MAX_SKILLS )
4977 return false;
4979 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4980 uint16 SkillValue = SKILL_VALUE(data);
4981 uint16 MaxValue = SKILL_MAX(data);
4983 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4984 return false;
4986 int32 Roll = irand(1,1000);
4988 if ( Roll <= Chance )
4990 uint32 new_value = SkillValue+step;
4991 if(new_value > MaxValue)
4992 new_value = MaxValue;
4994 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4995 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
4997 if((SkillValue < *bsl && new_value >= *bsl))
4999 learnSkillRewardedSpells( SkillId, new_value);
5000 break;
5003 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5004 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5005 return true;
5008 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5009 return false;
5012 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5014 // no skill gain in pvp
5015 Unit *pVictim = getVictim();
5016 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5017 return;
5019 if(IsInFeralForm())
5020 return; // always maximized SKILL_FERAL_COMBAT in fact
5022 if(m_form == FORM_TREE)
5023 return; // use weapon but not skill up
5025 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5027 switch(attType)
5029 case BASE_ATTACK:
5031 Item *tmpitem = GetWeaponForAttack(attType,true);
5033 if (!tmpitem)
5034 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5035 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5036 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5037 break;
5039 case OFF_ATTACK:
5040 case RANGED_ATTACK:
5042 Item *tmpitem = GetWeaponForAttack(attType,true);
5043 if (tmpitem)
5044 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5045 break;
5048 UpdateAllCritPercentages();
5051 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5053 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5054 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5055 uint32 moblevel = pVictim->getLevelForTarget(this);
5056 if(moblevel < greylevel)
5057 return;
5059 if (moblevel > plevel + 5)
5060 moblevel = plevel + 5;
5062 uint32 lvldif = moblevel - greylevel;
5063 if(lvldif < 3)
5064 lvldif = 3;
5066 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5067 if(skilldif <= 0)
5068 return;
5070 float chance = float(3 * lvldif * skilldif) / plevel;
5071 if(!defence)
5073 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5074 chance *= 0.1f * GetStat(STAT_INTELLECT);
5077 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5079 if(roll_chance_f(chance))
5081 if(defence)
5082 UpdateDefense();
5083 else
5084 UpdateWeaponSkill(attType);
5086 else
5087 return;
5090 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5092 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5093 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5095 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5096 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5097 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5099 if(talent) // permanent bonus stored in high part
5100 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5101 else // temporary/item bonus stored in low part
5102 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5103 return;
5107 void Player::UpdateSkillsForLevel()
5109 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5110 uint32 maxSkill = GetMaxSkillValueForLevel();
5112 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5114 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5115 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5117 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5119 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5120 if(!pSkill)
5121 continue;
5123 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5124 continue;
5126 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5127 uint32 max = SKILL_MAX(data);
5128 uint32 val = SKILL_VALUE(data);
5130 /// update only level dependent max skill values
5131 if(max!=1)
5133 /// miximize skill always
5134 if(alwaysMaxSkill)
5135 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5136 /// update max skill value if current max skill not maximized
5137 else if(max != maxconfskill)
5138 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5143 void Player::UpdateSkillsToMaxSkillsForLevel()
5145 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5146 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5148 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5149 if( IsProfessionOrRidingSkill(pskill))
5150 continue;
5151 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5153 uint32 max = SKILL_MAX(data);
5155 if(max > 1)
5156 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5158 if(pskill == SKILL_DEFENSE)
5159 UpdateDefenseBonusesMod();
5163 // This functions sets a skill line value (and adds if doesn't exist yet)
5164 // To "remove" a skill line, set it's values to zero
5165 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5167 if(!id)
5168 return;
5170 uint16 i=0;
5171 for (; i < PLAYER_MAX_SKILLS; ++i)
5172 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5174 if(i<PLAYER_MAX_SKILLS) //has skill
5176 if(currVal)
5178 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5179 learnSkillRewardedSpells(id, currVal);
5180 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5181 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5183 else //remove
5185 // clear skill fields
5186 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5187 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5188 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5190 // remove all spells that related to this skill
5191 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5192 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5193 if (pAbility->skillId==id)
5194 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5197 else if(currVal) //add
5199 for (i=0; i < PLAYER_MAX_SKILLS; ++i)
5200 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5202 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5203 if(!pSkill)
5205 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5206 return;
5208 // enable unlearn button for primary professions only
5209 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5210 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5211 else
5212 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5213 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5214 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5215 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5217 // apply skill bonuses
5218 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5220 // temporary bonuses
5221 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5222 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5223 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5224 (*j)->ApplyModifier(true);
5226 // permanent bonuses
5227 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5228 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5229 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5230 (*j)->ApplyModifier(true);
5232 // Learn all spells for skill
5233 learnSkillRewardedSpells(id, currVal);
5234 return;
5239 bool Player::HasSkill(uint32 skill) const
5241 if(!skill)return false;
5242 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5244 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5246 return true;
5249 return false;
5252 uint16 Player::GetSkillValue(uint32 skill) const
5254 if(!skill)
5255 return 0;
5257 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5259 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5261 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5263 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5264 result += SKILL_TEMP_BONUS(bonus);
5265 result += SKILL_PERM_BONUS(bonus);
5266 return result < 0 ? 0 : result;
5269 return 0;
5272 uint16 Player::GetMaxSkillValue(uint32 skill) const
5274 if(!skill)return 0;
5275 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5277 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5279 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5281 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5282 result += SKILL_TEMP_BONUS(bonus);
5283 result += SKILL_PERM_BONUS(bonus);
5284 return result < 0 ? 0 : result;
5287 return 0;
5290 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5292 if(!skill)return 0;
5293 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5295 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5297 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5300 return 0;
5303 uint16 Player::GetBaseSkillValue(uint32 skill) const
5305 if(!skill)return 0;
5306 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5308 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5310 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5311 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5312 return result < 0 ? 0 : result;
5315 return 0;
5318 uint16 Player::GetPureSkillValue(uint32 skill) const
5320 if(!skill)return 0;
5321 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5323 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5325 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5328 return 0;
5331 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5333 if(!skill)
5334 return 0;
5336 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5338 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5340 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5344 return 0;
5347 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5349 if(!skill)
5350 return 0;
5352 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5354 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5356 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5360 return 0;
5363 void Player::SendInitialActionButtons() const
5365 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5367 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5368 data << uint8(0); // can be 0, 1, 2
5369 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5371 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5372 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5374 data << uint16(itr->second.action);
5375 data << uint8(itr->second.misc);
5376 data << uint8(itr->second.type);
5378 else
5380 data << uint32(0);
5384 GetSession()->SendPacket( &data );
5385 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5388 bool Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5390 if(button >= MAX_ACTION_BUTTONS)
5392 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5393 return false;
5396 // check cheating with adding non-known spells to action bar
5397 if(type==ACTION_BUTTON_SPELL)
5399 if(!sSpellStore.LookupEntry(action))
5401 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5402 return false;
5405 if(!HasSpell(action))
5407 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5408 return false;
5412 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5414 if (buttonItr==m_actionButtons.end())
5415 { // just add new button
5416 m_actionButtons[button] = ActionButton(action,type,misc);
5418 else
5419 { // change state of current button
5420 ActionButtonUpdateState uState = buttonItr->second.uState;
5421 buttonItr->second = ActionButton(action,type,misc);
5422 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5425 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5426 return true;
5429 void Player::removeActionButton(uint8 button)
5431 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5432 if (buttonItr==m_actionButtons.end())
5433 return;
5435 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5436 m_actionButtons.erase(buttonItr); // new and not saved
5437 else
5438 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5440 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5443 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5445 // prevent crash when a bad coord is sent by the client
5446 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5448 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5449 return false;
5452 Map *m = GetMap();
5454 const float old_x = GetPositionX();
5455 const float old_y = GetPositionY();
5456 const float old_z = GetPositionZ();
5457 const float old_r = GetOrientation();
5459 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5461 if (teleport || old_x != x || old_y != y || old_z != z)
5462 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5463 else
5464 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5466 // move and update visible state if need
5467 m->PlayerRelocation(this, x, y, z, orientation);
5469 // reread after Map::Relocation
5470 m = GetMap();
5471 x = GetPositionX();
5472 y = GetPositionY();
5473 z = GetPositionZ();
5475 // group update
5476 if(GetGroup() && (old_x != x || old_y != y))
5477 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5480 // code block for underwater state update
5481 UpdateUnderwaterState(m, x, y, z);
5483 CheckExploreSystem();
5485 return true;
5488 void Player::SaveRecallPosition()
5490 m_recallMap = GetMapId();
5491 m_recallX = GetPositionX();
5492 m_recallY = GetPositionY();
5493 m_recallZ = GetPositionZ();
5494 m_recallO = GetOrientation();
5497 void Player::SendMessageToSet(WorldPacket *data, bool self)
5499 GetMap()->MessageBroadcast(this, data, self);
5502 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5504 GetMap()->MessageDistBroadcast(this, data, dist, self);
5507 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5509 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5512 void Player::SendDirectMessage(WorldPacket *data)
5514 GetSession()->SendPacket(data);
5517 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5519 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5520 data << uint32(CinematicSequenceId);
5521 SendDirectMessage(&data);
5524 void Player::SendMovieStart(uint32 MovieId)
5526 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5527 data << uint32(MovieId);
5528 SendDirectMessage(&data);
5531 void Player::CheckExploreSystem()
5533 if (!isAlive())
5534 return;
5536 if (isInFlight())
5537 return;
5539 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5540 if(areaFlag==0xffff)
5541 return;
5542 int offset = areaFlag / 32;
5544 if(offset >= 128)
5546 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);
5547 return;
5550 uint32 val = (uint32)(1 << (areaFlag % 32));
5551 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5553 if( !(currFields & val) )
5555 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5557 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5559 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5560 if(!p)
5562 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5564 else if(p->area_level > 0)
5566 uint32 area = p->ID;
5567 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5569 SendExplorationExperience(area,0);
5571 else
5573 int32 diff = int32(getLevel()) - p->area_level;
5574 uint32 XP = 0;
5575 if (diff < -5)
5577 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5579 else if (diff > 5)
5581 int32 exploration_percent = (100-((diff-5)*5));
5582 if (exploration_percent > 100)
5583 exploration_percent = 100;
5584 else if (exploration_percent < 0)
5585 exploration_percent = 0;
5587 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5589 else
5591 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5594 GiveXP( XP, NULL );
5595 SendExplorationExperience(area,XP);
5597 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5602 uint32 Player::TeamForRace(uint8 race)
5604 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5605 if(!rEntry)
5607 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5608 return ALLIANCE;
5611 switch(rEntry->TeamID)
5613 case 7: return ALLIANCE;
5614 case 1: return HORDE;
5617 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5618 return ALLIANCE;
5621 uint32 Player::getFactionForRace(uint8 race)
5623 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5624 if(!rEntry)
5626 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5627 return 0;
5630 return rEntry->FactionID;
5633 void Player::setFactionForRace(uint8 race)
5635 m_team = TeamForRace(race);
5636 setFaction( getFactionForRace(race) );
5639 ReputationRank Player::GetReputationRank(uint32 faction) const
5641 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5642 return GetReputationMgr().GetRank(factionEntry);
5645 //Calculate total reputation percent player gain with quest/creature level
5646 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5648 float percent = 100.0f;
5650 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5652 if(rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5653 percent *= rate;
5655 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5657 percent += rep > 0 ? repMod : -repMod;
5659 if(percent <= 0.0f)
5660 return 0;
5662 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5665 //Calculates how many reputation points player gains in victim's enemy factions
5666 void Player::RewardReputation(Unit *pVictim, float rate)
5668 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5669 return;
5671 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5673 if(!Rep)
5674 return;
5676 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5678 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5679 donerep1 = int32(donerep1*rate);
5680 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5681 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5682 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5683 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5685 // Wiki: Team factions value divided by 2
5686 if (factionEntry1 && Rep->is_teamaward1)
5688 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5689 if(team1_factionEntry)
5690 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5694 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5696 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5697 donerep2 = int32(donerep2*rate);
5698 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5699 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5700 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5701 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5703 // Wiki: Team factions value divided by 2
5704 if (factionEntry2 && Rep->is_teamaward2)
5706 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5707 if(team2_factionEntry)
5708 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5713 //Calculate how many reputation points player gain with the quest
5714 void Player::RewardReputation(Quest const *pQuest)
5716 // quest reputation reward/loss
5717 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5719 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5721 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest),pQuest->RewRepValue[i],true);
5722 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5723 if(factionEntry)
5724 GetReputationMgr().ModifyReputation(factionEntry, rep);
5728 // TODO: implement reputation spillover
5731 void Player::UpdateArenaFields(void)
5733 /* arena calcs go here */
5736 void Player::UpdateHonorFields()
5738 /// called when rewarding honor and at each save
5739 uint64 now = time(NULL);
5740 uint64 today = uint64(time(NULL) / DAY) * DAY;
5742 if(m_lastHonorUpdateTime < today)
5744 uint64 yesterday = today - DAY;
5746 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5748 // update yesterday's contribution
5749 if(m_lastHonorUpdateTime >= yesterday )
5751 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5753 // this is the first update today, reset today's contribution
5754 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5755 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5757 else
5759 // no honor/kills yesterday or today, reset
5760 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5761 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5765 m_lastHonorUpdateTime = now;
5768 ///Calculate the amount of honor gained based on the victim
5769 ///and the size of the group for which the honor is divided
5770 ///An exact honor value can also be given (overriding the calcs)
5771 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5773 // do not reward honor in arenas, but enable onkill spellproc
5774 if(InArena())
5776 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5777 return false;
5779 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5780 return false;
5782 return true;
5785 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5786 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5787 return false;
5789 uint64 victim_guid = 0;
5790 uint32 victim_rank = 0;
5792 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5793 UpdateHonorFields();
5795 if(honor <= 0)
5797 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5798 return false;
5800 victim_guid = uVictim->GetGUID();
5802 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5804 Player *pVictim = (Player *)uVictim;
5806 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5807 return false;
5809 float f = 1; //need for total kills (?? need more info)
5810 uint32 k_grey = 0;
5811 uint32 k_level = getLevel();
5812 uint32 v_level = pVictim->getLevel();
5815 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5816 // [0] Just name
5817 // [1..14] Alliance honor titles and player name
5818 // [15..28] Horde honor titles and player name
5819 // [29..38] Other title and player name
5820 // [39+] Nothing
5821 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5822 // Get Killer titles, CharTitlesEntry::bit_index
5823 // Ranks:
5824 // title[1..14] -> rank[5..18]
5825 // title[15..28] -> rank[5..18]
5826 // title[other] -> 0
5827 if (victim_title == 0)
5828 victim_guid = 0; // Don't show HK: <rank> message, only log.
5829 else if (victim_title < 15)
5830 victim_rank = victim_title + 4;
5831 else if (victim_title < 29)
5832 victim_rank = victim_title - 14 + 4;
5833 else
5834 victim_guid = 0; // Don't show HK: <rank> message, only log.
5837 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
5839 if(v_level<=k_grey)
5840 return false;
5842 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5844 int32 v_rank =1; //need more info
5846 honor = ((f * diff_level * (190 + v_rank*10))/6);
5847 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5849 // count the number of playerkills in one day
5850 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5851 // and those in a lifetime
5852 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5853 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
5854 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
5855 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
5857 else
5859 Creature *cVictim = (Creature *)uVictim;
5861 if (!cVictim->isRacialLeader())
5862 return false;
5864 honor = 100; // ??? need more info
5865 victim_rank = 19; // HK: Leader
5869 if (uVictim != NULL)
5871 honor *= sWorld.getRate(RATE_HONOR);
5873 if(groupsize > 1)
5874 honor /= groupsize;
5876 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5879 // honor - for show honor points in log
5880 // victim_guid - for show victim name in log
5881 // victim_rank [1..4] HK: <dishonored rank>
5882 // victim_rank [5..19] HK: <alliance\horde rank>
5883 // victim_rank [0,20+] HK: <>
5884 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5885 data << (uint32) honor;
5886 data << (uint64) victim_guid;
5887 data << (uint32) victim_rank;
5889 GetSession()->SendPacket(&data);
5891 // add honor points
5892 ModifyHonorPoints(int32(honor));
5894 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5895 return true;
5898 void Player::ModifyHonorPoints( int32 value )
5900 if(value < 0)
5902 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5903 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
5904 else
5905 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
5907 else
5908 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
5911 void Player::ModifyArenaPoints( int32 value )
5913 if(value < 0)
5915 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
5916 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
5917 else
5918 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
5920 else
5921 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
5924 uint32 Player::GetGuildIdFromDB(uint64 guid)
5926 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
5927 if(!result)
5928 return 0;
5930 uint32 id = result->Fetch()[0].GetUInt32();
5931 delete result;
5932 return id;
5935 uint32 Player::GetRankFromDB(uint64 guid)
5937 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
5938 if( result )
5940 uint32 v = result->Fetch()[0].GetUInt32();
5941 delete result;
5942 return v;
5944 else
5945 return 0;
5948 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
5950 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);
5951 if(!result)
5952 return 0;
5954 uint32 id = (*result)[0].GetUInt32();
5955 delete result;
5956 return id;
5959 uint32 Player::GetZoneIdFromDB(uint64 guid)
5961 uint32 guidLow = GUID_LOPART(guid);
5962 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
5963 if (!result)
5964 return 0;
5965 Field* fields = result->Fetch();
5966 uint32 zone = fields[0].GetUInt32();
5967 delete result;
5969 if (!zone)
5971 // stored zone is zero, use generic and slow zone detection
5972 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
5973 if( !result )
5974 return 0;
5975 fields = result->Fetch();
5976 uint32 map = fields[0].GetUInt32();
5977 float posx = fields[1].GetFloat();
5978 float posy = fields[2].GetFloat();
5979 float posz = fields[3].GetFloat();
5980 delete result;
5982 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
5984 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
5987 return zone;
5990 void Player::UpdateArea(uint32 newArea)
5992 // FFA_PVP flags are area and not zone id dependent
5993 // so apply them accordingly
5994 m_areaUpdateId = newArea;
5996 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
5998 if(area && (area->flags & AREA_FLAG_ARENA))
6000 if(!isGameMaster())
6001 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6003 else
6005 // remove ffa flag only if not ffapvp realm
6006 // removal in sanctuaries and capitals is handled in zone update
6007 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6008 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6011 UpdateAreaDependentAuras(newArea);
6014 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6016 if(m_zoneUpdateId != newZone)
6017 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6019 m_zoneUpdateId = newZone;
6020 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6022 // zone changed, so area changed as well, update it
6023 UpdateArea(newArea);
6025 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6026 if(!zone)
6027 return;
6029 if (sWorld.getConfig(CONFIG_WEATHER))
6031 Weather *wth = sWorld.FindWeather(zone->ID);
6032 if(wth)
6034 wth->SendWeatherUpdateToPlayer(this);
6036 else
6038 if(!sWorld.AddWeather(zone->ID))
6040 // send fine weather packet to remove old zone's weather
6041 Weather::SendFineWeatherUpdateToPlayer(this);
6046 // in PvP, any not controlled zone (except zone->team == 6, default case)
6047 // in PvE, only opposition team capital
6048 switch(zone->team)
6050 case AREATEAM_ALLY:
6051 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6052 break;
6053 case AREATEAM_HORDE:
6054 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6055 break;
6056 case AREATEAM_NONE:
6057 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6058 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6059 break;
6060 default: // 6 in fact
6061 pvpInfo.inHostileArea = false;
6062 break;
6065 if(pvpInfo.inHostileArea) // in hostile area
6067 if(!IsPvP() || pvpInfo.endTimer != 0)
6068 UpdatePvP(true, true);
6070 else // in friendly area
6072 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6073 pvpInfo.endTimer = time(0); // start toggle-off
6076 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6078 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6079 if(sWorld.IsFFAPvPRealm())
6080 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6082 else
6084 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6087 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6089 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6090 SetRestType(REST_TYPE_IN_CITY);
6091 InnEnter(time(0),GetMapId(),0,0,0);
6093 if(sWorld.IsFFAPvPRealm())
6094 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6096 else // anywhere else
6098 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6100 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6102 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6104 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6105 SetRestType(REST_TYPE_NO);
6107 if(sWorld.IsFFAPvPRealm())
6108 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6111 else // not in tavern (leave city then)
6113 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6114 SetRestType(REST_TYPE_NO);
6116 // Set player to FFA PVP when not in rested environment.
6117 if(sWorld.IsFFAPvPRealm())
6118 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6123 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6124 // if player resurrected at teleport this will be applied in resurrect code
6125 if(isAlive())
6126 DestroyZoneLimitedItem( true, newZone );
6128 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6129 AutoUnequipOffhandIfNeed();
6131 // recent client version not send leave/join channel packets for built-in local channels
6132 UpdateLocalChannels( newZone );
6134 // group update
6135 if(GetGroup())
6136 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6138 UpdateZoneDependentAuras(newZone);
6141 //If players are too far way of duel flag... then player loose the duel
6142 void Player::CheckDuelDistance(time_t currTime)
6144 if(!duel)
6145 return;
6147 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6148 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6149 if(!obj)
6150 return;
6152 if(duel->outOfBound == 0)
6154 if(!IsWithinDistInMap(obj, 50))
6156 duel->outOfBound = currTime;
6158 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6159 GetSession()->SendPacket(&data);
6162 else
6164 if(IsWithinDistInMap(obj, 40))
6166 duel->outOfBound = 0;
6168 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6169 GetSession()->SendPacket(&data);
6171 else if(currTime >= (duel->outOfBound+10))
6173 DuelComplete(DUEL_FLED);
6178 void Player::DuelComplete(DuelCompleteType type)
6180 // duel not requested
6181 if(!duel)
6182 return;
6184 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6185 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6186 GetSession()->SendPacket(&data);
6187 duel->opponent->GetSession()->SendPacket(&data);
6189 if(type != DUEL_INTERUPTED)
6191 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6192 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6193 data << duel->opponent->GetName();
6194 data << GetName();
6195 SendMessageToSet(&data,true);
6198 if (type == DUEL_WON)
6200 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6201 if (duel->opponent)
6202 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6205 // cool-down duel spell
6206 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6208 data<<GetGUID();
6209 data<<uint8(0x0);
6211 data<<(uint32)7266;
6212 data<<uint32(0x0);
6213 GetSession()->SendPacket(&data);
6214 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6215 data<<duel->opponent->GetGUID();
6216 data<<uint8(0x0);
6217 data<<(uint32)7266;
6218 data<<uint32(0x0);
6219 duel->opponent->GetSession()->SendPacket(&data);*/
6221 //Remove Duel Flag object
6222 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6223 if(obj)
6224 duel->initiator->RemoveGameObject(obj,true);
6226 /* remove auras */
6227 std::vector<uint32> auras2remove;
6228 AuraMap const& vAuras = duel->opponent->GetAuras();
6229 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6231 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6232 auras2remove.push_back(i->second->GetId());
6235 for(size_t i=0; i<auras2remove.size(); ++i)
6236 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6238 auras2remove.clear();
6239 AuraMap const& auras = GetAuras();
6240 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6242 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6243 auras2remove.push_back(i->second->GetId());
6245 for(size_t i=0; i<auras2remove.size(); ++i)
6246 RemoveAurasDueToSpell(auras2remove[i]);
6248 // cleanup combo points
6249 if(GetComboTarget()==duel->opponent->GetGUID())
6250 ClearComboPoints();
6251 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6252 ClearComboPoints();
6254 if(duel->opponent->GetComboTarget()==GetGUID())
6255 duel->opponent->ClearComboPoints();
6256 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6257 duel->opponent->ClearComboPoints();
6259 //cleanups
6260 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6261 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6262 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6263 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6265 delete duel->opponent->duel;
6266 duel->opponent->duel = NULL;
6267 delete duel;
6268 duel = NULL;
6271 //---------------------------------------------------------//
6273 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6275 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6276 return;
6278 // not apply/remove mods for broken item
6279 if(item->IsBroken())
6280 return;
6282 ItemPrototype const *proto = item->GetProto();
6284 if(!proto)
6285 return;
6287 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6289 uint32 attacktype = Player::GetAttackBySlot(slot);
6290 if(attacktype < MAX_ATTACK)
6291 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6293 _ApplyItemBonuses(proto,slot,apply);
6295 if( slot==EQUIPMENT_SLOT_RANGED )
6296 _ApplyAmmoBonuses();
6298 ApplyItemEquipSpell(item,apply);
6299 ApplyEnchantment(item, apply);
6301 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6302 CorrectMetaGemEnchants(slot, apply);
6304 sLog.outDebug("_ApplyItemMods complete.");
6307 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6309 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6310 return;
6312 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6314 uint32 statType = 0;
6315 int32 val = 0;
6317 if(proto->ScalingStatDistribution)
6319 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6321 statType = ssd->StatMod[i];
6323 if(uint32 modifier = ssd->Modifier[i])
6325 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6326 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6328 uint32 multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6329 val = (multiplier * modifier) / 10000;
6334 else
6336 statType = proto->ItemStat[i].ItemStatType;
6337 val = proto->ItemStat[i].ItemStatValue;
6340 if(val == 0)
6341 continue;
6343 switch (statType)
6345 case ITEM_MOD_MANA:
6346 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6347 break;
6348 case ITEM_MOD_HEALTH: // modify HP
6349 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6350 break;
6351 case ITEM_MOD_AGILITY: // modify agility
6352 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6353 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6354 break;
6355 case ITEM_MOD_STRENGTH: //modify strength
6356 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6357 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6358 break;
6359 case ITEM_MOD_INTELLECT: //modify intellect
6360 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6361 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6362 break;
6363 case ITEM_MOD_SPIRIT: //modify spirit
6364 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6365 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6366 break;
6367 case ITEM_MOD_STAMINA: //modify stamina
6368 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6369 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6370 break;
6371 case ITEM_MOD_DEFENSE_SKILL_RATING:
6372 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6373 break;
6374 case ITEM_MOD_DODGE_RATING:
6375 ApplyRatingMod(CR_DODGE, int32(val), apply);
6376 break;
6377 case ITEM_MOD_PARRY_RATING:
6378 ApplyRatingMod(CR_PARRY, int32(val), apply);
6379 break;
6380 case ITEM_MOD_BLOCK_RATING:
6381 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6382 break;
6383 case ITEM_MOD_HIT_MELEE_RATING:
6384 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6385 break;
6386 case ITEM_MOD_HIT_RANGED_RATING:
6387 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6388 break;
6389 case ITEM_MOD_HIT_SPELL_RATING:
6390 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6391 break;
6392 case ITEM_MOD_CRIT_MELEE_RATING:
6393 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6394 break;
6395 case ITEM_MOD_CRIT_RANGED_RATING:
6396 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6397 break;
6398 case ITEM_MOD_CRIT_SPELL_RATING:
6399 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6400 break;
6401 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6402 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6403 break;
6404 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6405 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6406 break;
6407 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6408 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6409 break;
6410 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6411 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6412 break;
6413 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6414 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6415 break;
6416 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6417 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6418 break;
6419 case ITEM_MOD_HASTE_MELEE_RATING:
6420 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6421 break;
6422 case ITEM_MOD_HASTE_RANGED_RATING:
6423 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6424 break;
6425 case ITEM_MOD_HASTE_SPELL_RATING:
6426 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6427 break;
6428 case ITEM_MOD_HIT_RATING:
6429 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6430 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6431 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6432 break;
6433 case ITEM_MOD_CRIT_RATING:
6434 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6435 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6436 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6437 break;
6438 case ITEM_MOD_HIT_TAKEN_RATING:
6439 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6440 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6441 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6442 break;
6443 case ITEM_MOD_CRIT_TAKEN_RATING:
6444 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6445 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6446 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6447 break;
6448 case ITEM_MOD_RESILIENCE_RATING:
6449 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6450 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6451 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6452 break;
6453 case ITEM_MOD_HASTE_RATING:
6454 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6455 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6456 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6457 break;
6458 case ITEM_MOD_EXPERTISE_RATING:
6459 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6460 break;
6461 case ITEM_MOD_ATTACK_POWER:
6462 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6463 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6464 break;
6465 case ITEM_MOD_RANGED_ATTACK_POWER:
6466 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6467 break;
6468 case ITEM_MOD_FERAL_ATTACK_POWER:
6469 ApplyFeralAPBonus(int32(val), apply);
6470 break;
6471 case ITEM_MOD_SPELL_HEALING_DONE:
6472 ApplySpellHealingBonus(int32(val), apply);
6473 break;
6474 case ITEM_MOD_SPELL_DAMAGE_DONE:
6475 ApplySpellDamageBonus(int32(val), apply);
6476 break;
6477 case ITEM_MOD_MANA_REGENERATION:
6478 ApplyManaRegenBonus(int32(val), apply);
6479 break;
6480 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6481 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6482 break;
6483 case ITEM_MOD_SPELL_POWER:
6484 ApplySpellHealingBonus(int32(val), apply);
6485 ApplySpellDamageBonus(int32(val), apply);
6486 break;
6490 if (proto->Armor)
6491 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6493 if (proto->Block)
6494 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6496 if (proto->HolyRes)
6497 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6499 if (proto->FireRes)
6500 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6502 if (proto->NatureRes)
6503 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6505 if (proto->FrostRes)
6506 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6508 if (proto->ShadowRes)
6509 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6511 if (proto->ArcaneRes)
6512 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6514 WeaponAttackType attType = BASE_ATTACK;
6515 float damage = 0.0f;
6517 if( slot == EQUIPMENT_SLOT_RANGED && (
6518 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6519 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6521 attType = RANGED_ATTACK;
6523 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6525 attType = OFF_ATTACK;
6528 if (proto->Damage[0].DamageMin > 0 )
6530 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6531 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6532 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6535 if (proto->Damage[0].DamageMax > 0 )
6537 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6538 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6541 // Druids get feral AP bonus from weapon dps
6542 if(getClass() == CLASS_DRUID)
6544 int32 feral_bonus = proto->getFeralBonus();
6545 if (feral_bonus > 0)
6546 ApplyFeralAPBonus(feral_bonus, apply);
6549 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6550 return;
6552 if (proto->Delay)
6554 if(slot == EQUIPMENT_SLOT_RANGED)
6555 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6556 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6557 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6558 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6559 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6562 if(CanModifyStats() && (damage || proto->Delay))
6563 UpdateDamagePhysical(attType);
6566 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6568 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6569 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6570 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6572 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6573 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6574 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6576 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6577 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6578 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6581 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6583 // generic not weapon specific case processes in aura code
6584 if(aura->GetSpellProto()->EquippedItemClass == -1)
6585 return;
6587 BaseModGroup mod = BASEMOD_END;
6588 switch(attackType)
6590 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6591 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6592 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6593 default: return;
6596 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6598 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6602 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6604 // ignore spell mods for not wands
6605 Modifier const* modifier = aura->GetModifier();
6606 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6607 return;
6609 // generic not weapon specific case processes in aura code
6610 if(aura->GetSpellProto()->EquippedItemClass == -1)
6611 return;
6613 UnitMods unitMod = UNIT_MOD_END;
6614 switch(attackType)
6616 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6617 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6618 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6619 default: return;
6622 UnitModifierType unitModType = TOTAL_VALUE;
6623 switch(modifier->m_auraname)
6625 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6626 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6627 default: return;
6630 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6632 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6636 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6638 if(!item)
6639 return;
6641 ItemPrototype const *proto = item->GetProto();
6642 if(!proto)
6643 return;
6645 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6647 _Spell const& spellData = proto->Spells[i];
6649 // no spell
6650 if(!spellData.SpellId )
6651 continue;
6653 // wrong triggering type
6654 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6655 continue;
6657 // check if it is valid spell
6658 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6659 if(!spellproto)
6660 continue;
6662 ApplyEquipSpell(spellproto,item,apply,form_change);
6666 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6668 if(apply)
6670 // Cannot be used in this stance/form
6671 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6672 return;
6674 if(form_change) // check aura active state from other form
6676 bool found = false;
6677 for (int k=0; k < 3; ++k)
6679 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6680 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6682 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6684 found = true;
6685 break;
6688 if(found)
6689 break;
6692 if(found) // and skip re-cast already active aura at form change
6693 return;
6696 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6698 CastSpell(this,spellInfo,true,item);
6700 else
6702 if(form_change) // check aura compatibility
6704 // Cannot be used in this stance/form
6705 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6706 return; // and remove only not compatible at form change
6709 if(item)
6710 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6711 else
6712 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6716 void Player::UpdateEquipSpellsAtFormChange()
6718 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6720 if(m_items[i] && !m_items[i]->IsBroken())
6722 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6723 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6727 // item set bonuses not dependent from item broken state
6728 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6730 ItemSetEffect* eff = ItemSetEff[setindex];
6731 if(!eff)
6732 continue;
6734 for(uint32 y=0;y<8; ++y)
6736 SpellEntry const* spellInfo = eff->spells[y];
6737 if(!spellInfo)
6738 continue;
6740 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6741 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6746 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6748 if(!item || item->IsBroken())
6749 return;
6751 ItemPrototype const *proto = item->GetProto();
6752 if(!proto)
6753 return;
6755 if (!Target || Target == this )
6756 return;
6758 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6760 _Spell const& spellData = proto->Spells[i];
6762 // no spell
6763 if(!spellData.SpellId )
6764 continue;
6766 // wrong triggering type
6767 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6768 continue;
6770 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6771 if(!spellInfo)
6773 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6774 continue;
6777 // not allow proc extra attack spell at extra attack
6778 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6779 return;
6781 float chance = spellInfo->procChance;
6783 if(spellData.SpellPPMRate)
6785 uint32 WeaponSpeed = GetAttackTime(attType);
6786 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6788 else if(chance > 100.0f)
6790 chance = GetWeaponProcChance();
6793 if (roll_chance_f(chance))
6794 CastSpell(Target, spellInfo->Id, true, item);
6797 // item combat enchantments
6798 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6800 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6801 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6802 if(!pEnchant) continue;
6803 for (int s=0;s<3;s++)
6805 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6806 continue;
6808 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6809 if (!spellInfo)
6811 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6812 continue;
6815 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6816 if (roll_chance_f(chance))
6818 if(IsPositiveSpell(pEnchant->spellid[s]))
6819 CastSpell(this, pEnchant->spellid[s], true, item);
6820 else
6821 CastSpell(Target, pEnchant->spellid[s], true, item);
6827 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
6829 ItemPrototype const* proto = item->GetProto();
6830 // special learning case
6831 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
6833 uint32 learn_spell_id = proto->Spells[0].SpellId;
6834 uint32 learning_spell_id = proto->Spells[1].SpellId;
6836 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
6837 if(!spellInfo)
6839 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
6840 SendEquipError(EQUIP_ERR_NONE,item,NULL);
6841 return;
6844 Spell *spell = new Spell(this, spellInfo, false);
6845 spell->m_CastItem = item;
6846 spell->m_cast_count = cast_count; //set count of casts
6847 spell->m_currentBasePoints[0] = learning_spell_id;
6848 spell->prepare(&targets);
6849 return;
6852 // use triggered flag only for items with many spell casts and for not first cast
6853 int count = 0;
6855 // item spells casted at use
6856 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6858 _Spell const& spellData = proto->Spells[i];
6860 // no spell
6861 if(!spellData.SpellId)
6862 continue;
6864 // wrong triggering type
6865 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
6866 continue;
6868 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6869 if(!spellInfo)
6871 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
6872 continue;
6875 Spell *spell = new Spell(this, spellInfo, (count > 0));
6876 spell->m_CastItem = item;
6877 spell->m_cast_count = cast_count; // set count of casts
6878 spell->m_glyphIndex = glyphIndex; // glyph index
6879 spell->prepare(&targets);
6881 ++count;
6884 // Item enchantments spells casted at use
6885 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6887 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6888 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6889 if(!pEnchant) continue;
6890 for (int s=0;s<3;s++)
6892 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
6893 continue;
6895 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6896 if (!spellInfo)
6898 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6899 continue;
6902 Spell *spell = new Spell(this, spellInfo, (count > 0));
6903 spell->m_CastItem = item;
6904 spell->m_cast_count = cast_count; // set count of casts
6905 spell->m_glyphIndex = glyphIndex; // glyph index
6906 spell->prepare(&targets);
6908 ++count;
6913 void Player::_RemoveAllItemMods()
6915 sLog.outDebug("_RemoveAllItemMods start.");
6917 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6919 if(m_items[i])
6921 ItemPrototype const *proto = m_items[i]->GetProto();
6922 if(!proto)
6923 continue;
6925 // item set bonuses not dependent from item broken state
6926 if(proto->ItemSet)
6927 RemoveItemsSetItem(this,proto);
6929 if(m_items[i]->IsBroken())
6930 continue;
6932 ApplyItemEquipSpell(m_items[i],false);
6933 ApplyEnchantment(m_items[i], false);
6937 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6939 if(m_items[i])
6941 if(m_items[i]->IsBroken())
6942 continue;
6943 ItemPrototype const *proto = m_items[i]->GetProto();
6944 if(!proto)
6945 continue;
6947 uint32 attacktype = Player::GetAttackBySlot(i);
6948 if(attacktype < MAX_ATTACK)
6949 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6951 _ApplyItemBonuses(proto,i, false);
6953 if( i == EQUIPMENT_SLOT_RANGED )
6954 _ApplyAmmoBonuses();
6958 sLog.outDebug("_RemoveAllItemMods complete.");
6961 void Player::_ApplyAllItemMods()
6963 sLog.outDebug("_ApplyAllItemMods start.");
6965 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6967 if(m_items[i])
6969 if(m_items[i]->IsBroken())
6970 continue;
6972 ItemPrototype const *proto = m_items[i]->GetProto();
6973 if(!proto)
6974 continue;
6976 uint32 attacktype = Player::GetAttackBySlot(i);
6977 if(attacktype < MAX_ATTACK)
6978 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
6980 _ApplyItemBonuses(proto,i, true);
6982 if( i == EQUIPMENT_SLOT_RANGED )
6983 _ApplyAmmoBonuses();
6987 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6989 if(m_items[i])
6991 ItemPrototype const *proto = m_items[i]->GetProto();
6992 if(!proto)
6993 continue;
6995 // item set bonuses not dependent from item broken state
6996 if(proto->ItemSet)
6997 AddItemsSetItem(this,m_items[i]);
6999 if(m_items[i]->IsBroken())
7000 continue;
7002 ApplyItemEquipSpell(m_items[i],true);
7003 ApplyEnchantment(m_items[i], true);
7007 sLog.outDebug("_ApplyAllItemMods complete.");
7010 void Player::_ApplyAmmoBonuses()
7012 // check ammo
7013 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7014 if(!ammo_id)
7015 return;
7017 float currentAmmoDPS;
7019 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7020 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7021 currentAmmoDPS = 0.0f;
7022 else
7023 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7025 if(currentAmmoDPS == GetAmmoDPS())
7026 return;
7028 m_ammoDPS = currentAmmoDPS;
7030 if(CanModifyStats())
7031 UpdateDamagePhysical(RANGED_ATTACK);
7034 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7036 if(!ammo_proto)
7037 return false;
7039 // check ranged weapon
7040 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7041 if(!weapon || weapon->IsBroken() )
7042 return false;
7044 ItemPrototype const* weapon_proto = weapon->GetProto();
7045 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7046 return false;
7048 // check ammo ws. weapon compatibility
7049 switch(weapon_proto->SubClass)
7051 case ITEM_SUBCLASS_WEAPON_BOW:
7052 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7053 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7054 return false;
7055 break;
7056 case ITEM_SUBCLASS_WEAPON_GUN:
7057 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7058 return false;
7059 break;
7060 default:
7061 return false;
7064 return true;
7067 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7068 Called by remove insignia spell effect */
7069 void Player::RemovedInsignia(Player* looterPlr)
7071 if (!GetBattleGroundId())
7072 return;
7074 // If not released spirit, do it !
7075 if(m_deathTimer > 0)
7077 m_deathTimer = 0;
7078 BuildPlayerRepop();
7079 RepopAtGraveyard();
7082 Corpse *corpse = GetCorpse();
7083 if (!corpse)
7084 return;
7086 // We have to convert player corpse to bones, not to be able to resurrect there
7087 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7088 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7089 if (!bones)
7090 return;
7092 // Now we must make bones lootable, and send player loot
7093 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7095 // We store the level of our player in the gold field
7096 // We retrieve this information at Player::SendLoot()
7097 bones->loot.gold = getLevel();
7098 bones->lootRecipient = looterPlr;
7099 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7102 void Player::SendLootRelease( uint64 guid )
7104 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7105 data << uint64(guid) << uint8(1);
7106 SendDirectMessage( &data );
7109 void Player::SendLoot(uint64 guid, LootType loot_type)
7111 if (uint64 lguid = GetLootGUID())
7112 m_session->DoLootRelease(lguid);
7114 Loot *loot = 0;
7115 PermissionTypes permission = ALL_PERMISSION;
7117 sLog.outDebug("Player::SendLoot");
7118 if (IS_GAMEOBJECT_GUID(guid))
7120 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7121 GameObject *go = GetMap()->GetGameObject(guid);
7123 // not check distance for GO in case owned GO (fishing bobber case, for example)
7124 // And permit out of range GO with no owner in case fishing hole
7125 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7127 SendLootRelease(guid);
7128 return;
7131 loot = &go->loot;
7133 if (go->getLootState() == GO_READY)
7135 uint32 lootid = go->GetLootId();
7137 if (lootid)
7139 sLog.outDebug(" if(lootid)");
7140 loot->clear();
7141 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7144 if (loot_type == LOOT_FISHING)
7145 go->getFishLoot(loot,this);
7147 go->SetLootState(GO_ACTIVATED);
7150 else if (IS_ITEM_GUID(guid))
7152 Item *item = GetItemByGuid( guid );
7154 if (!item)
7156 SendLootRelease(guid);
7157 return;
7160 loot = &item->loot;
7162 if (!item->m_lootGenerated)
7164 item->m_lootGenerated = true;
7165 loot->clear();
7167 switch(loot_type)
7169 case LOOT_DISENCHANTING:
7170 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7171 break;
7172 case LOOT_PROSPECTING:
7173 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7174 break;
7175 case LOOT_MILLING:
7176 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7177 break;
7178 default:
7179 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7180 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7181 break;
7185 else if (IS_CORPSE_GUID(guid)) // remove insignia
7187 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7189 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7191 SendLootRelease(guid);
7192 return;
7195 loot = &bones->loot;
7197 if (!bones->lootForBody)
7199 bones->lootForBody = true;
7200 uint32 pLevel = bones->loot.gold;
7201 bones->loot.clear();
7202 // It may need a better formula
7203 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7204 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7207 if (bones->lootRecipient != this)
7208 permission = NONE_PERMISSION;
7210 else
7212 Creature *creature = GetMap()->GetCreature(guid);
7214 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7215 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7217 SendLootRelease(guid);
7218 return;
7221 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7223 SendLootRelease(guid);
7224 return;
7227 loot = &creature->loot;
7229 if (loot_type == LOOT_PICKPOCKETING)
7231 if (!creature->lootForPickPocketed)
7233 creature->lootForPickPocketed = true;
7234 loot->clear();
7236 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7237 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7239 // Generate extra money for pick pocket loot
7240 const uint32 a = urand(0, creature->getLevel()/2);
7241 const uint32 b = urand(0, getLevel()/2);
7242 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7245 else
7247 // the player whose group may loot the corpse
7248 Player *recipient = creature->GetLootRecipient();
7249 if (!recipient)
7251 creature->SetLootRecipient(this);
7252 recipient = this;
7255 if (creature->lootForPickPocketed)
7257 creature->lootForPickPocketed = false;
7258 loot->clear();
7261 if (!creature->lootForBody)
7263 creature->lootForBody = true;
7264 loot->clear();
7266 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7267 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7269 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7271 if (Group* group = recipient->GetGroup())
7273 group->UpdateLooterGuid(creature,true);
7275 switch (group->GetLootMethod())
7277 case GROUP_LOOT:
7278 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7279 group->GroupLoot(recipient->GetGUID(), loot, creature);
7280 break;
7281 case NEED_BEFORE_GREED:
7282 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7283 break;
7284 case MASTER_LOOT:
7285 group->MasterLoot(recipient->GetGUID(), loot, creature);
7286 break;
7287 default:
7288 break;
7293 // possible only if creature->lootForBody && loot->empty() at spell cast check
7294 if (loot_type == LOOT_SKINNING)
7296 loot->clear();
7297 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7299 // set group rights only for loot_type != LOOT_SKINNING
7300 else
7302 if(Group* group = GetGroup())
7304 if (group == recipient->GetGroup())
7306 if (group->GetLootMethod() == FREE_FOR_ALL)
7307 permission = ALL_PERMISSION;
7308 else if (group->GetLooterGuid() == GetGUID())
7310 if (group->GetLootMethod() == MASTER_LOOT)
7311 permission = MASTER_PERMISSION;
7312 else
7313 permission = ALL_PERMISSION;
7315 else
7316 permission = GROUP_PERMISSION;
7318 else
7319 permission = NONE_PERMISSION;
7321 else if (recipient == this)
7322 permission = ALL_PERMISSION;
7323 else
7324 permission = NONE_PERMISSION;
7329 SetLootGUID(guid);
7331 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7332 switch(loot_type)
7334 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7335 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7336 default: break;
7339 // need know merged fishing/corpse loot type for achievements
7340 loot->loot_type = loot_type;
7342 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7344 data << uint64(guid);
7345 data << uint8(loot_type);
7346 data << LootView(*loot, this, permission);
7348 SendDirectMessage(&data);
7350 // add 'this' player as one of the players that are looting 'loot'
7351 if (permission != NONE_PERMISSION)
7352 loot->AddLooter(GetGUID());
7354 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7355 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7358 void Player::SendNotifyLootMoneyRemoved()
7360 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7361 GetSession()->SendPacket( &data );
7364 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7366 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7367 data << uint8(lootSlot);
7368 GetSession()->SendPacket( &data );
7371 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7373 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7374 data << Field;
7375 data << Value;
7376 GetSession()->SendPacket(&data);
7379 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7381 // data depends on zoneid/mapid...
7382 BattleGround* bg = GetBattleGround();
7383 uint16 NumberOfFields = 0;
7384 uint32 mapid = GetMapId();
7386 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7388 // may be exist better way to do this...
7389 switch(zoneid)
7391 case 0:
7392 case 1:
7393 case 4:
7394 case 8:
7395 case 10:
7396 case 11:
7397 case 12:
7398 case 36:
7399 case 38:
7400 case 40:
7401 case 41:
7402 case 51:
7403 case 267:
7404 case 1519:
7405 case 1537:
7406 case 2257:
7407 case 2918:
7408 NumberOfFields = 8;
7409 break;
7410 case 139:
7411 NumberOfFields = 41;
7412 break;
7413 case 1377:
7414 NumberOfFields = 15;
7415 break;
7416 case 2597:
7417 NumberOfFields = 83;
7418 break;
7419 case 3277:
7420 NumberOfFields = 16;
7421 break;
7422 case 3358:
7423 case 3820:
7424 NumberOfFields = 40;
7425 break;
7426 case 3483:
7427 NumberOfFields = 27;
7428 break;
7429 case 3518:
7430 NumberOfFields = 39;
7431 break;
7432 case 3519:
7433 NumberOfFields = 38;
7434 break;
7435 case 3521:
7436 NumberOfFields = 37;
7437 break;
7438 case 3698:
7439 case 3702:
7440 case 3968:
7441 NumberOfFields = 11;
7442 break;
7443 case 3703:
7444 NumberOfFields = 11;
7445 break;
7446 default:
7447 NumberOfFields = 12;
7448 break;
7451 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7452 data << uint32(mapid); // mapid
7453 data << uint32(zoneid); // zone id
7454 data << uint32(areaid); // area id, new 2.1.0
7455 data << uint16(NumberOfFields); // count of uint64 blocks
7456 data << uint32(0x8d8) << uint32(0x0); // 1
7457 data << uint32(0x8d7) << uint32(0x0); // 2
7458 data << uint32(0x8d6) << uint32(0x0); // 3
7459 data << uint32(0x8d5) << uint32(0x0); // 4
7460 data << uint32(0x8d4) << uint32(0x0); // 5
7461 data << uint32(0x8d3) << uint32(0x0); // 6
7462 // 7 1 - Arena season in progress, 0 - end of season
7463 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7464 // 8 Arena season id
7465 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7466 if(mapid == 530) // Outland
7468 data << uint32(0x9bf) << uint32(0x0); // 7
7469 data << uint32(0x9bd) << uint32(0xF); // 8
7470 data << uint32(0x9bb) << uint32(0xF); // 9
7472 switch(zoneid)
7474 case 1:
7475 case 11:
7476 case 12:
7477 case 38:
7478 case 40:
7479 case 51:
7480 case 1519:
7481 case 1537:
7482 case 2257:
7483 break;
7484 case 2597: // AV
7485 data << uint32(0x7ae) << uint32(0x1); // 7
7486 data << uint32(0x532) << uint32(0x1); // 8
7487 data << uint32(0x531) << uint32(0x0); // 9
7488 data << uint32(0x52e) << uint32(0x0); // 10
7489 data << uint32(0x571) << uint32(0x0); // 11
7490 data << uint32(0x570) << uint32(0x0); // 12
7491 data << uint32(0x567) << uint32(0x1); // 13
7492 data << uint32(0x566) << uint32(0x1); // 14
7493 data << uint32(0x550) << uint32(0x1); // 15
7494 data << uint32(0x544) << uint32(0x0); // 16
7495 data << uint32(0x536) << uint32(0x0); // 17
7496 data << uint32(0x535) << uint32(0x1); // 18
7497 data << uint32(0x518) << uint32(0x0); // 19
7498 data << uint32(0x517) << uint32(0x0); // 20
7499 data << uint32(0x574) << uint32(0x0); // 21
7500 data << uint32(0x573) << uint32(0x0); // 22
7501 data << uint32(0x572) << uint32(0x0); // 23
7502 data << uint32(0x56f) << uint32(0x0); // 24
7503 data << uint32(0x56e) << uint32(0x0); // 25
7504 data << uint32(0x56d) << uint32(0x0); // 26
7505 data << uint32(0x56c) << uint32(0x0); // 27
7506 data << uint32(0x56b) << uint32(0x0); // 28
7507 data << uint32(0x56a) << uint32(0x1); // 29
7508 data << uint32(0x569) << uint32(0x1); // 30
7509 data << uint32(0x568) << uint32(0x1); // 13
7510 data << uint32(0x565) << uint32(0x0); // 32
7511 data << uint32(0x564) << uint32(0x0); // 33
7512 data << uint32(0x563) << uint32(0x0); // 34
7513 data << uint32(0x562) << uint32(0x0); // 35
7514 data << uint32(0x561) << uint32(0x0); // 36
7515 data << uint32(0x560) << uint32(0x0); // 37
7516 data << uint32(0x55f) << uint32(0x0); // 38
7517 data << uint32(0x55e) << uint32(0x0); // 39
7518 data << uint32(0x55d) << uint32(0x0); // 40
7519 data << uint32(0x3c6) << uint32(0x4); // 41
7520 data << uint32(0x3c4) << uint32(0x6); // 42
7521 data << uint32(0x3c2) << uint32(0x4); // 43
7522 data << uint32(0x516) << uint32(0x1); // 44
7523 data << uint32(0x515) << uint32(0x0); // 45
7524 data << uint32(0x3b6) << uint32(0x6); // 46
7525 data << uint32(0x55c) << uint32(0x0); // 47
7526 data << uint32(0x55b) << uint32(0x0); // 48
7527 data << uint32(0x55a) << uint32(0x0); // 49
7528 data << uint32(0x559) << uint32(0x0); // 50
7529 data << uint32(0x558) << uint32(0x0); // 51
7530 data << uint32(0x557) << uint32(0x0); // 52
7531 data << uint32(0x556) << uint32(0x0); // 53
7532 data << uint32(0x555) << uint32(0x0); // 54
7533 data << uint32(0x554) << uint32(0x1); // 55
7534 data << uint32(0x553) << uint32(0x1); // 56
7535 data << uint32(0x552) << uint32(0x1); // 57
7536 data << uint32(0x551) << uint32(0x1); // 58
7537 data << uint32(0x54f) << uint32(0x0); // 59
7538 data << uint32(0x54e) << uint32(0x0); // 60
7539 data << uint32(0x54d) << uint32(0x1); // 61
7540 data << uint32(0x54c) << uint32(0x0); // 62
7541 data << uint32(0x54b) << uint32(0x0); // 63
7542 data << uint32(0x545) << uint32(0x0); // 64
7543 data << uint32(0x543) << uint32(0x1); // 65
7544 data << uint32(0x542) << uint32(0x0); // 66
7545 data << uint32(0x540) << uint32(0x0); // 67
7546 data << uint32(0x53f) << uint32(0x0); // 68
7547 data << uint32(0x53e) << uint32(0x0); // 69
7548 data << uint32(0x53d) << uint32(0x0); // 70
7549 data << uint32(0x53c) << uint32(0x0); // 71
7550 data << uint32(0x53b) << uint32(0x0); // 72
7551 data << uint32(0x53a) << uint32(0x1); // 73
7552 data << uint32(0x539) << uint32(0x0); // 74
7553 data << uint32(0x538) << uint32(0x0); // 75
7554 data << uint32(0x537) << uint32(0x0); // 76
7555 data << uint32(0x534) << uint32(0x0); // 77
7556 data << uint32(0x533) << uint32(0x0); // 78
7557 data << uint32(0x530) << uint32(0x0); // 79
7558 data << uint32(0x52f) << uint32(0x0); // 80
7559 data << uint32(0x52d) << uint32(0x1); // 81
7560 break;
7561 case 3277: // WS
7562 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7563 bg->FillInitialWorldStates(data);
7564 else
7566 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7567 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7568 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7569 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7570 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7571 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7572 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7573 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7575 break;
7576 case 3358: // AB
7577 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7578 bg->FillInitialWorldStates(data);
7579 else
7581 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7582 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7583 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7584 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7585 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7586 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7587 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7588 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7589 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7590 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7591 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7592 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7593 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7594 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7595 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7596 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7597 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7598 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7599 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7600 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7601 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7602 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7603 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7604 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7605 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7606 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7607 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7608 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7609 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7610 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7611 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7612 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7614 break;
7615 case 3820: // EY
7616 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7617 bg->FillInitialWorldStates(data);
7618 else
7620 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7621 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7622 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7623 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7624 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7625 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7626 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7627 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7628 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7629 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7630 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7631 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7632 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7633 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7634 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7635 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7636 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7637 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7638 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7639 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7640 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7641 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7642 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7643 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7644 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7645 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7646 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7647 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7648 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7649 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7650 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7651 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7652 // and some more ... unknown
7654 break;
7655 case 3483: // Hellfire Peninsula
7656 data << uint32(0x9ba) << uint32(0x1); // 10
7657 data << uint32(0x9b9) << uint32(0x1); // 11
7658 data << uint32(0x9b5) << uint32(0x0); // 12
7659 data << uint32(0x9b4) << uint32(0x1); // 13
7660 data << uint32(0x9b3) << uint32(0x0); // 14
7661 data << uint32(0x9b2) << uint32(0x0); // 15
7662 data << uint32(0x9b1) << uint32(0x1); // 16
7663 data << uint32(0x9b0) << uint32(0x0); // 17
7664 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7665 data << uint32(0x9ac) << uint32(0x0); // 19
7666 data << uint32(0x9a8) << uint32(0x0); // 20
7667 data << uint32(0x9a7) << uint32(0x0); // 21
7668 data << uint32(0x9a6) << uint32(0x1); // 22
7669 break;
7670 case 3519: // Terokkar Forest
7671 data << uint32(0xa41) << uint32(0x0); // 10
7672 data << uint32(0xa40) << uint32(0x14); // 11
7673 data << uint32(0xa3f) << uint32(0x0); // 12
7674 data << uint32(0xa3e) << uint32(0x0); // 13
7675 data << uint32(0xa3d) << uint32(0x5); // 14
7676 data << uint32(0xa3c) << uint32(0x0); // 15
7677 data << uint32(0xa87) << uint32(0x0); // 16
7678 data << uint32(0xa86) << uint32(0x0); // 17
7679 data << uint32(0xa85) << uint32(0x0); // 18
7680 data << uint32(0xa84) << uint32(0x0); // 19
7681 data << uint32(0xa83) << uint32(0x0); // 20
7682 data << uint32(0xa82) << uint32(0x0); // 21
7683 data << uint32(0xa81) << uint32(0x0); // 22
7684 data << uint32(0xa80) << uint32(0x0); // 23
7685 data << uint32(0xa7e) << uint32(0x0); // 24
7686 data << uint32(0xa7d) << uint32(0x0); // 25
7687 data << uint32(0xa7c) << uint32(0x0); // 26
7688 data << uint32(0xa7b) << uint32(0x0); // 27
7689 data << uint32(0xa7a) << uint32(0x0); // 28
7690 data << uint32(0xa79) << uint32(0x0); // 29
7691 data << uint32(0x9d0) << uint32(0x5); // 30
7692 data << uint32(0x9ce) << uint32(0x0); // 31
7693 data << uint32(0x9cd) << uint32(0x0); // 32
7694 data << uint32(0x9cc) << uint32(0x0); // 33
7695 data << uint32(0xa88) << uint32(0x0); // 34
7696 data << uint32(0xad0) << uint32(0x0); // 35
7697 data << uint32(0xacf) << uint32(0x1); // 36
7698 break;
7699 case 3521: // Zangarmarsh
7700 data << uint32(0x9e1) << uint32(0x0); // 10
7701 data << uint32(0x9e0) << uint32(0x0); // 11
7702 data << uint32(0x9df) << uint32(0x0); // 12
7703 data << uint32(0xa5d) << uint32(0x1); // 13
7704 data << uint32(0xa5c) << uint32(0x0); // 14
7705 data << uint32(0xa5b) << uint32(0x1); // 15
7706 data << uint32(0xa5a) << uint32(0x0); // 16
7707 data << uint32(0xa59) << uint32(0x1); // 17
7708 data << uint32(0xa58) << uint32(0x0); // 18
7709 data << uint32(0xa57) << uint32(0x0); // 19
7710 data << uint32(0xa56) << uint32(0x0); // 20
7711 data << uint32(0xa55) << uint32(0x1); // 21
7712 data << uint32(0xa54) << uint32(0x0); // 22
7713 data << uint32(0x9e7) << uint32(0x0); // 23
7714 data << uint32(0x9e6) << uint32(0x0); // 24
7715 data << uint32(0x9e5) << uint32(0x0); // 25
7716 data << uint32(0xa00) << uint32(0x0); // 26
7717 data << uint32(0x9ff) << uint32(0x1); // 27
7718 data << uint32(0x9fe) << uint32(0x0); // 28
7719 data << uint32(0x9fd) << uint32(0x0); // 29
7720 data << uint32(0x9fc) << uint32(0x1); // 30
7721 data << uint32(0x9fb) << uint32(0x0); // 31
7722 data << uint32(0xa62) << uint32(0x0); // 32
7723 data << uint32(0xa61) << uint32(0x1); // 33
7724 data << uint32(0xa60) << uint32(0x1); // 34
7725 data << uint32(0xa5f) << uint32(0x0); // 35
7726 break;
7727 case 3698: // Nagrand Arena
7728 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7729 bg->FillInitialWorldStates(data);
7730 else
7732 data << uint32(0xa0f) << uint32(0x0); // 7
7733 data << uint32(0xa10) << uint32(0x0); // 8
7734 data << uint32(0xa11) << uint32(0x0); // 9 show
7736 break;
7737 case 3702: // Blade's Edge Arena
7738 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7739 bg->FillInitialWorldStates(data);
7740 else
7742 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7743 data << uint32(0x9f1) << uint32(0x0); // 8 green
7744 data << uint32(0x9f3) << uint32(0x0); // 9 show
7746 break;
7747 case 3968: // Ruins of Lordaeron
7748 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7749 bg->FillInitialWorldStates(data);
7750 else
7752 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7753 data << uint32(0xbb9) << uint32(0x0); // 8 green
7754 data << uint32(0xbba) << uint32(0x0); // 9 show
7756 break;
7757 case 3703: // Shattrath City
7758 break;
7759 default:
7760 data << uint32(0x914) << uint32(0x0); // 7
7761 data << uint32(0x913) << uint32(0x0); // 8
7762 data << uint32(0x912) << uint32(0x0); // 9
7763 data << uint32(0x915) << uint32(0x0); // 10
7764 break;
7766 GetSession()->SendPacket(&data);
7769 uint32 Player::GetXPRestBonus(uint32 xp)
7771 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7773 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7774 rested_bonus = xp;
7776 SetRestBonus( GetRestBonus() - rested_bonus);
7778 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7779 return rested_bonus;
7782 void Player::SetBindPoint(uint64 guid)
7784 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7785 data << uint64(guid);
7786 GetSession()->SendPacket( &data );
7789 void Player::SendTalentWipeConfirm(uint64 guid)
7791 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7792 data << uint64(guid);
7793 data << uint32(resetTalentsCost());
7794 GetSession()->SendPacket( &data );
7797 void Player::SendPetSkillWipeConfirm()
7799 Pet* pet = GetPet();
7800 if(!pet)
7801 return;
7802 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7803 data << pet->GetGUID();
7804 data << uint32(pet->resetTalentsCost());
7805 GetSession()->SendPacket( &data );
7808 /*********************************************************/
7809 /*** STORAGE SYSTEM ***/
7810 /*********************************************************/
7812 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7814 assert(i < 3);
7815 if(i < 2 && item)
7817 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7818 return;
7819 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7820 if(charges == 0)
7821 return;
7822 if(charges > 1)
7823 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7824 else if(charges <= 1)
7826 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7827 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7832 void Player::SetSheath( uint32 sheathed )
7834 switch (sheathed)
7836 case SHEATH_STATE_UNARMED: // no prepared weapon
7837 SetVirtualItemSlot(0,NULL);
7838 SetVirtualItemSlot(1,NULL);
7839 SetVirtualItemSlot(2,NULL);
7840 break;
7841 case SHEATH_STATE_MELEE: // prepared melee weapon
7843 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7844 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7845 SetVirtualItemSlot(2,NULL);
7846 }; break;
7847 case SHEATH_STATE_RANGED: // prepared ranged weapon
7848 SetVirtualItemSlot(0,NULL);
7849 SetVirtualItemSlot(1,NULL);
7850 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7851 break;
7852 default:
7853 SetVirtualItemSlot(0,NULL);
7854 SetVirtualItemSlot(1,NULL);
7855 SetVirtualItemSlot(2,NULL);
7856 break;
7858 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7861 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7863 uint8 pClass = getClass();
7865 uint8 slots[4];
7866 slots[0] = NULL_SLOT;
7867 slots[1] = NULL_SLOT;
7868 slots[2] = NULL_SLOT;
7869 slots[3] = NULL_SLOT;
7870 switch( proto->InventoryType )
7872 case INVTYPE_HEAD:
7873 slots[0] = EQUIPMENT_SLOT_HEAD;
7874 break;
7875 case INVTYPE_NECK:
7876 slots[0] = EQUIPMENT_SLOT_NECK;
7877 break;
7878 case INVTYPE_SHOULDERS:
7879 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7880 break;
7881 case INVTYPE_BODY:
7882 slots[0] = EQUIPMENT_SLOT_BODY;
7883 break;
7884 case INVTYPE_CHEST:
7885 slots[0] = EQUIPMENT_SLOT_CHEST;
7886 break;
7887 case INVTYPE_ROBE:
7888 slots[0] = EQUIPMENT_SLOT_CHEST;
7889 break;
7890 case INVTYPE_WAIST:
7891 slots[0] = EQUIPMENT_SLOT_WAIST;
7892 break;
7893 case INVTYPE_LEGS:
7894 slots[0] = EQUIPMENT_SLOT_LEGS;
7895 break;
7896 case INVTYPE_FEET:
7897 slots[0] = EQUIPMENT_SLOT_FEET;
7898 break;
7899 case INVTYPE_WRISTS:
7900 slots[0] = EQUIPMENT_SLOT_WRISTS;
7901 break;
7902 case INVTYPE_HANDS:
7903 slots[0] = EQUIPMENT_SLOT_HANDS;
7904 break;
7905 case INVTYPE_FINGER:
7906 slots[0] = EQUIPMENT_SLOT_FINGER1;
7907 slots[1] = EQUIPMENT_SLOT_FINGER2;
7908 break;
7909 case INVTYPE_TRINKET:
7910 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7911 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7912 break;
7913 case INVTYPE_CLOAK:
7914 slots[0] = EQUIPMENT_SLOT_BACK;
7915 break;
7916 case INVTYPE_WEAPON:
7918 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7920 // suggest offhand slot only if know dual wielding
7921 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7922 if(CanDualWield())
7923 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7924 break;
7926 case INVTYPE_SHIELD:
7927 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7928 break;
7929 case INVTYPE_RANGED:
7930 slots[0] = EQUIPMENT_SLOT_RANGED;
7931 break;
7932 case INVTYPE_2HWEAPON:
7933 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7934 if (CanDualWield() && CanTitanGrip())
7935 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7936 break;
7937 case INVTYPE_TABARD:
7938 slots[0] = EQUIPMENT_SLOT_TABARD;
7939 break;
7940 case INVTYPE_WEAPONMAINHAND:
7941 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7942 break;
7943 case INVTYPE_WEAPONOFFHAND:
7944 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7945 break;
7946 case INVTYPE_HOLDABLE:
7947 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7948 break;
7949 case INVTYPE_THROWN:
7950 slots[0] = EQUIPMENT_SLOT_RANGED;
7951 break;
7952 case INVTYPE_RANGEDRIGHT:
7953 slots[0] = EQUIPMENT_SLOT_RANGED;
7954 break;
7955 case INVTYPE_BAG:
7956 slots[0] = INVENTORY_SLOT_BAG_START + 0;
7957 slots[1] = INVENTORY_SLOT_BAG_START + 1;
7958 slots[2] = INVENTORY_SLOT_BAG_START + 2;
7959 slots[3] = INVENTORY_SLOT_BAG_START + 3;
7960 break;
7961 case INVTYPE_RELIC:
7963 switch(proto->SubClass)
7965 case ITEM_SUBCLASS_ARMOR_LIBRAM:
7966 if (pClass == CLASS_PALADIN)
7967 slots[0] = EQUIPMENT_SLOT_RANGED;
7968 break;
7969 case ITEM_SUBCLASS_ARMOR_IDOL:
7970 if (pClass == CLASS_DRUID)
7971 slots[0] = EQUIPMENT_SLOT_RANGED;
7972 break;
7973 case ITEM_SUBCLASS_ARMOR_TOTEM:
7974 if (pClass == CLASS_SHAMAN)
7975 slots[0] = EQUIPMENT_SLOT_RANGED;
7976 break;
7977 case ITEM_SUBCLASS_ARMOR_MISC:
7978 if (pClass == CLASS_WARLOCK)
7979 slots[0] = EQUIPMENT_SLOT_RANGED;
7980 break;
7981 case ITEM_SUBCLASS_ARMOR_SIGIL:
7982 if (pClass == CLASS_DEATH_KNIGHT)
7983 slots[0] = EQUIPMENT_SLOT_RANGED;
7984 break;
7986 break;
7988 default :
7989 return NULL_SLOT;
7992 if( slot != NULL_SLOT )
7994 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
7996 for (int i = 0; i < 4; ++i)
7998 if ( slots[i] == slot )
7999 return slot;
8003 else
8005 // search free slot at first
8006 for (int i = 0; i < 4; ++i)
8008 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8010 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8011 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8012 return slots[i];
8016 // if not found free and can swap return first appropriate from used
8017 for (int i = 0; i < 4; ++i)
8019 if ( slots[i] != NULL_SLOT && swap )
8020 return slots[i];
8024 // no free position
8025 return NULL_SLOT;
8028 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8030 Item *pItem;
8031 uint32 tempcount = 0;
8033 uint8 res = EQUIP_ERR_OK;
8035 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8037 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8038 if( pItem && pItem->GetEntry() == item )
8040 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8041 if(ires==EQUIP_ERR_OK)
8043 tempcount += pItem->GetCount();
8044 if( tempcount >= count )
8045 return EQUIP_ERR_OK;
8047 else
8048 res = ires;
8051 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8053 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8054 if( pItem && pItem->GetEntry() == item )
8056 tempcount += pItem->GetCount();
8057 if( tempcount >= count )
8058 return EQUIP_ERR_OK;
8061 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8063 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8064 if( pItem && pItem->GetEntry() == item )
8066 tempcount += pItem->GetCount();
8067 if( tempcount >= count )
8068 return EQUIP_ERR_OK;
8071 Bag *pBag;
8072 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8074 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8075 if( pBag )
8077 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8079 pItem = GetItemByPos( i, j );
8080 if( pItem && pItem->GetEntry() == item )
8082 tempcount += pItem->GetCount();
8083 if( tempcount >= count )
8084 return EQUIP_ERR_OK;
8090 // not found req. item count and have unequippable items
8091 return res;
8094 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8096 uint32 count = 0;
8097 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8099 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8100 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8101 count += pItem->GetCount();
8103 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8105 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8106 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8107 count += pItem->GetCount();
8109 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8111 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8112 if( pBag )
8113 count += pBag->GetItemCount(item,skipItem);
8116 if(skipItem && skipItem->GetProto()->GemProperties)
8118 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8120 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8121 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8122 count += pItem->GetGemCountWithID(item);
8126 if(inBankAlso)
8128 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8130 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8131 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8132 count += pItem->GetCount();
8134 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8136 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8137 if( pBag )
8138 count += pBag->GetItemCount(item,skipItem);
8141 if(skipItem && skipItem->GetProto()->GemProperties)
8143 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8145 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8146 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8147 count += pItem->GetGemCountWithID(item);
8152 return count;
8155 Item* Player::GetItemByGuid( uint64 guid ) const
8157 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8159 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8160 if( pItem && pItem->GetGUID() == guid )
8161 return pItem;
8163 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8165 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8166 if( pItem && pItem->GetGUID() == guid )
8167 return pItem;
8170 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8172 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8173 if( pBag )
8175 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8177 Item* pItem = pBag->GetItemByPos( j );
8178 if( pItem && pItem->GetGUID() == guid )
8179 return pItem;
8183 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8185 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8186 if( pBag )
8188 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8190 Item* pItem = pBag->GetItemByPos( j );
8191 if( pItem && pItem->GetGUID() == guid )
8192 return pItem;
8197 return NULL;
8200 Item* Player::GetItemByPos( uint16 pos ) const
8202 uint8 bag = pos >> 8;
8203 uint8 slot = pos & 255;
8204 return GetItemByPos( bag, slot );
8207 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8209 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8210 return m_items[slot];
8211 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8212 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8214 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8215 if ( pBag )
8216 return pBag->GetItemByPos(slot);
8218 return NULL;
8221 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8223 uint16 slot;
8224 switch (attackType)
8226 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8227 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8228 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8229 default: return NULL;
8232 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8233 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8234 return NULL;
8236 if(!useable)
8237 return item;
8239 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8240 return NULL;
8242 return item;
8245 Item* Player::GetShield(bool useable) const
8247 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8248 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8249 return NULL;
8251 if(!useable)
8252 return item;
8254 if( item->IsBroken())
8255 return NULL;
8257 return item;
8260 uint32 Player::GetAttackBySlot( uint8 slot )
8262 switch(slot)
8264 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8265 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8266 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8267 default: return MAX_ATTACK;
8271 bool Player::HasBankBagSlot( uint8 slot ) const
8273 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8274 if( slot < maxslot )
8275 return true;
8276 return false;
8279 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8281 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8282 return true;
8283 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8284 return true;
8285 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8286 return true;
8287 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8288 return true;
8289 return false;
8292 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8294 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8295 return true;
8296 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8297 return true;
8298 return false;
8301 bool Player::IsBankPos( uint8 bag, uint8 slot )
8303 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8304 return true;
8305 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8306 return true;
8307 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8308 return true;
8309 return false;
8312 bool Player::IsBagPos( uint16 pos )
8314 uint8 bag = pos >> 8;
8315 uint8 slot = pos & 255;
8316 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8317 return true;
8318 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8319 return true;
8320 return false;
8323 bool Player::IsValidPos( uint8 bag, uint8 slot )
8325 // post selected
8326 if(bag == NULL_BAG)
8327 return true;
8329 if (bag == INVENTORY_SLOT_BAG_0)
8331 // any post selected
8332 if (slot == NULL_SLOT)
8333 return true;
8335 // equipment
8336 if (slot < EQUIPMENT_SLOT_END)
8337 return true;
8339 // bag equip slots
8340 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8341 return true;
8343 // backpack slots
8344 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8345 return true;
8347 // keyring slots
8348 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8349 return true;
8351 // bank main slots
8352 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8353 return true;
8355 // bank bag slots
8356 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8357 return true;
8359 return false;
8362 // bag content slots
8363 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8365 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8366 if(!pBag)
8367 return false;
8369 // any post selected
8370 if (slot == NULL_SLOT)
8371 return true;
8373 return slot < pBag->GetBagSize();
8376 // bank bag content slots
8377 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8379 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8380 if(!pBag)
8381 return false;
8383 // any post selected
8384 if (slot == NULL_SLOT)
8385 return true;
8387 return slot < pBag->GetBagSize();
8390 // where this?
8391 return false;
8395 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8397 uint32 tempcount = 0;
8398 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8400 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8401 if( pItem && pItem->GetEntry() == item )
8403 tempcount += pItem->GetCount();
8404 if( tempcount >= count )
8405 return true;
8408 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8410 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8411 if( pItem && pItem->GetEntry() == item )
8413 tempcount += pItem->GetCount();
8414 if( tempcount >= count )
8415 return true;
8418 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8420 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8422 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8424 Item* pItem = GetItemByPos( i, j );
8425 if( pItem && pItem->GetEntry() == item )
8427 tempcount += pItem->GetCount();
8428 if( tempcount >= count )
8429 return true;
8435 if(inBankAlso)
8437 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8439 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8440 if( pItem && pItem->GetEntry() == item )
8442 tempcount += pItem->GetCount();
8443 if( tempcount >= count )
8444 return true;
8447 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8449 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8451 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8453 Item* pItem = GetItemByPos( i, j );
8454 if( pItem && pItem->GetEntry() == item )
8456 tempcount += pItem->GetCount();
8457 if( tempcount >= count )
8458 return true;
8465 return false;
8468 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8470 uint32 tempcount = 0;
8471 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8473 if(i==int(except_slot))
8474 continue;
8476 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8477 if( pItem && pItem->GetEntry() == item)
8479 tempcount += pItem->GetCount();
8480 if( tempcount >= count )
8481 return true;
8485 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8486 if (pProto && pProto->GemProperties)
8488 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8490 if(i==int(except_slot))
8491 continue;
8493 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8494 if( pItem && pItem->GetProto()->Socket[0].Color)
8496 tempcount += pItem->GetGemCountWithID(item);
8497 if( tempcount >= count )
8498 return true;
8503 return false;
8506 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8508 uint32 tempcount = 0;
8509 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8511 if(i==int(except_slot))
8512 continue;
8514 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8515 if (!pItem)
8516 continue;
8518 ItemPrototype const *pProto = pItem->GetProto();
8519 if (!pProto)
8520 continue;
8522 if (pProto->ItemLimitCategory == limitCategory)
8524 tempcount += pItem->GetCount();
8525 if( tempcount >= count )
8526 return true;
8529 if( pProto->Socket[0].Color)
8531 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8532 if( tempcount >= count )
8533 return true;
8537 return false;
8540 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8542 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8543 if( !pProto )
8545 if(no_space_count)
8546 *no_space_count = count;
8547 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8550 // no maximum
8551 if(pProto->MaxCount <= 0)
8552 return EQUIP_ERR_OK;
8554 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8556 if (curcount + count > uint32(pProto->MaxCount))
8558 if(no_space_count)
8559 *no_space_count = count +curcount - pProto->MaxCount;
8560 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8563 return EQUIP_ERR_OK;
8566 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8568 Item *pItem;
8569 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8571 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8572 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8573 return true;
8575 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8577 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8578 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8579 return true;
8581 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8583 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8585 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8587 pItem = GetItemByPos( i, j );
8588 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8589 return true;
8593 return false;
8596 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8598 Item* pItem2 = GetItemByPos( bag, slot );
8600 // ignore move item (this slot will be empty at move)
8601 if(pItem2==pSrcItem)
8602 pItem2 = NULL;
8604 uint32 need_space;
8606 // empty specific slot - check item fit to slot
8607 if( !pItem2 || swap )
8609 if( bag == INVENTORY_SLOT_BAG_0 )
8611 // keyring case
8612 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8613 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8615 // currencytoken case (disabled until proper implement)
8616 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8617 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8619 // prevent cheating
8620 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8621 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8623 else
8625 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8626 if( !pBag )
8627 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8629 ItemPrototype const* pBagProto = pBag->GetProto();
8630 if( !pBagProto )
8631 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8633 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8634 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8637 // non empty stack with space
8638 need_space = pProto->GetMaxStackSize();
8640 // non empty slot, check item type
8641 else
8643 // check item type
8644 if(pItem2->GetEntry() != pProto->ItemId)
8645 return EQUIP_ERR_ITEM_CANT_STACK;
8647 // check free space
8648 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8649 return EQUIP_ERR_ITEM_CANT_STACK;
8651 // free stack space or infinity
8652 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8655 if(need_space > count)
8656 need_space = count;
8658 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8659 if(!newPosition.isContainedIn(dest))
8661 dest.push_back(newPosition);
8662 count -= need_space;
8664 return EQUIP_ERR_OK;
8667 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
8669 // skip specific bag already processed in first called _CanStoreItem_InBag
8670 if(bag==skip_bag)
8671 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8673 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8674 if( !pBag )
8675 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8677 ItemPrototype const* pBagProto = pBag->GetProto();
8678 if( !pBagProto )
8679 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8681 // specialized bag mode or non-specilized
8682 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8683 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8685 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8686 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8688 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8690 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8691 if(j==skip_slot)
8692 continue;
8694 Item* pItem2 = GetItemByPos( bag, j );
8696 // ignore move item (this slot will be empty at move)
8697 if(pItem2==pSrcItem)
8698 pItem2 = NULL;
8700 // if merge skip empty, if !merge skip non-empty
8701 if((pItem2!=NULL)!=merge)
8702 continue;
8704 if( pItem2 )
8706 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8708 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8709 if(need_space > count)
8710 need_space = count;
8712 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8713 if(!newPosition.isContainedIn(dest))
8715 dest.push_back(newPosition);
8716 count -= need_space;
8718 if(count==0)
8719 return EQUIP_ERR_OK;
8723 else
8725 uint32 need_space = pProto->GetMaxStackSize();
8726 if(need_space > count)
8727 need_space = count;
8729 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8730 if(!newPosition.isContainedIn(dest))
8732 dest.push_back(newPosition);
8733 count -= need_space;
8735 if(count==0)
8736 return EQUIP_ERR_OK;
8740 return EQUIP_ERR_OK;
8743 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
8745 for(uint32 j = slot_begin; j < slot_end; ++j)
8747 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8748 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8749 continue;
8751 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8753 // ignore move item (this slot will be empty at move)
8754 if(pItem2==pSrcItem)
8755 pItem2 = NULL;
8757 // if merge skip empty, if !merge skip non-empty
8758 if((pItem2!=NULL)!=merge)
8759 continue;
8761 if( pItem2 )
8763 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8765 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8766 if(need_space > count)
8767 need_space = count;
8768 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8769 if(!newPosition.isContainedIn(dest))
8771 dest.push_back(newPosition);
8772 count -= need_space;
8774 if(count==0)
8775 return EQUIP_ERR_OK;
8779 else
8781 uint32 need_space = pProto->GetMaxStackSize();
8782 if(need_space > count)
8783 need_space = count;
8785 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8786 if(!newPosition.isContainedIn(dest))
8788 dest.push_back(newPosition);
8789 count -= need_space;
8791 if(count==0)
8792 return EQUIP_ERR_OK;
8796 return EQUIP_ERR_OK;
8799 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8801 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8803 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8804 if( !pProto )
8806 if(no_space_count)
8807 *no_space_count = count;
8808 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8811 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8813 if(no_space_count)
8814 *no_space_count = count;
8815 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8818 // check count of items (skip for auto move for same player from bank)
8819 uint32 no_similar_count = 0; // can't store this amount similar items
8820 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8821 if(res!=EQUIP_ERR_OK)
8823 if(count==no_similar_count)
8825 if(no_space_count)
8826 *no_space_count = no_similar_count;
8827 return res;
8829 count -= no_similar_count;
8832 // in specific slot
8833 if( bag != NULL_BAG && slot != NULL_SLOT )
8835 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8836 if(res!=EQUIP_ERR_OK)
8838 if(no_space_count)
8839 *no_space_count = count + no_similar_count;
8840 return res;
8843 if(count==0)
8845 if(no_similar_count==0)
8846 return EQUIP_ERR_OK;
8848 if(no_space_count)
8849 *no_space_count = count + no_similar_count;
8850 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8854 // not specific slot or have space for partly store only in specific slot
8856 // in specific bag
8857 if( bag != NULL_BAG )
8859 // search stack in bag for merge to
8860 if( pProto->Stackable != 1 )
8862 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8864 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8865 if(res!=EQUIP_ERR_OK)
8867 if(no_space_count)
8868 *no_space_count = count + no_similar_count;
8869 return res;
8872 if(count==0)
8874 if(no_similar_count==0)
8875 return EQUIP_ERR_OK;
8877 if(no_space_count)
8878 *no_space_count = count + no_similar_count;
8879 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8882 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8883 if(res!=EQUIP_ERR_OK)
8885 if(no_space_count)
8886 *no_space_count = count + no_similar_count;
8887 return res;
8890 if(count==0)
8892 if(no_similar_count==0)
8893 return EQUIP_ERR_OK;
8895 if(no_space_count)
8896 *no_space_count = count + no_similar_count;
8897 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8900 else // equipped bag
8902 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8903 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8904 if(res!=EQUIP_ERR_OK)
8905 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8907 if(res!=EQUIP_ERR_OK)
8909 if(no_space_count)
8910 *no_space_count = count + no_similar_count;
8911 return res;
8914 if(count==0)
8916 if(no_similar_count==0)
8917 return EQUIP_ERR_OK;
8919 if(no_space_count)
8920 *no_space_count = count + no_similar_count;
8921 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8926 // search free slot in bag for place to
8927 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8929 // search free slot - keyring case
8930 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8932 uint32 keyringSize = GetMaxKeyringSize();
8933 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8934 if(res!=EQUIP_ERR_OK)
8936 if(no_space_count)
8937 *no_space_count = count + no_similar_count;
8938 return res;
8941 if(count==0)
8943 if(no_similar_count==0)
8944 return EQUIP_ERR_OK;
8946 if(no_space_count)
8947 *no_space_count = count + no_similar_count;
8948 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8951 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8952 if(res!=EQUIP_ERR_OK)
8954 if(no_space_count)
8955 *no_space_count = count + no_similar_count;
8956 return res;
8959 if(count==0)
8961 if(no_similar_count==0)
8962 return EQUIP_ERR_OK;
8964 if(no_space_count)
8965 *no_space_count = count + no_similar_count;
8966 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8969 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
8971 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8972 if(res!=EQUIP_ERR_OK)
8974 if(no_space_count)
8975 *no_space_count = count + no_similar_count;
8976 return res;
8979 if(count==0)
8981 if(no_similar_count==0)
8982 return EQUIP_ERR_OK;
8984 if(no_space_count)
8985 *no_space_count = count + no_similar_count;
8986 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8990 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8991 if(res!=EQUIP_ERR_OK)
8993 if(no_space_count)
8994 *no_space_count = count + no_similar_count;
8995 return res;
8998 if(count==0)
9000 if(no_similar_count==0)
9001 return EQUIP_ERR_OK;
9003 if(no_space_count)
9004 *no_space_count = count + no_similar_count;
9005 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9008 else // equipped bag
9010 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9011 if(res!=EQUIP_ERR_OK)
9012 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9014 if(res!=EQUIP_ERR_OK)
9016 if(no_space_count)
9017 *no_space_count = count + no_similar_count;
9018 return res;
9021 if(count==0)
9023 if(no_similar_count==0)
9024 return EQUIP_ERR_OK;
9026 if(no_space_count)
9027 *no_space_count = count + no_similar_count;
9028 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9033 // not specific bag or have space for partly store only in specific bag
9035 // search stack for merge to
9036 if( pProto->Stackable != 1 )
9038 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9039 if(res!=EQUIP_ERR_OK)
9041 if(no_space_count)
9042 *no_space_count = count + no_similar_count;
9043 return res;
9046 if(count==0)
9048 if(no_similar_count==0)
9049 return EQUIP_ERR_OK;
9051 if(no_space_count)
9052 *no_space_count = count + no_similar_count;
9053 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9056 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9057 if(res!=EQUIP_ERR_OK)
9059 if(no_space_count)
9060 *no_space_count = count + no_similar_count;
9061 return res;
9064 if(count==0)
9066 if(no_similar_count==0)
9067 return EQUIP_ERR_OK;
9069 if(no_space_count)
9070 *no_space_count = count + no_similar_count;
9071 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9074 if( pProto->BagFamily )
9076 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9078 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9079 if(res!=EQUIP_ERR_OK)
9080 continue;
9082 if(count==0)
9084 if(no_similar_count==0)
9085 return EQUIP_ERR_OK;
9087 if(no_space_count)
9088 *no_space_count = count + no_similar_count;
9089 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9094 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9096 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9097 if(res!=EQUIP_ERR_OK)
9098 continue;
9100 if(count==0)
9102 if(no_similar_count==0)
9103 return EQUIP_ERR_OK;
9105 if(no_space_count)
9106 *no_space_count = count + no_similar_count;
9107 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9112 // search free slot - special bag case
9113 if( pProto->BagFamily )
9115 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9117 uint32 keyringSize = GetMaxKeyringSize();
9118 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9119 if(res!=EQUIP_ERR_OK)
9121 if(no_space_count)
9122 *no_space_count = count + no_similar_count;
9123 return res;
9126 if(count==0)
9128 if(no_similar_count==0)
9129 return EQUIP_ERR_OK;
9131 if(no_space_count)
9132 *no_space_count = count + no_similar_count;
9133 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9136 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9138 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9139 if(res!=EQUIP_ERR_OK)
9141 if(no_space_count)
9142 *no_space_count = count + no_similar_count;
9143 return res;
9146 if(count==0)
9148 if(no_similar_count==0)
9149 return EQUIP_ERR_OK;
9151 if(no_space_count)
9152 *no_space_count = count + no_similar_count;
9153 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9157 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9159 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9160 if(res!=EQUIP_ERR_OK)
9161 continue;
9163 if(count==0)
9165 if(no_similar_count==0)
9166 return EQUIP_ERR_OK;
9168 if(no_space_count)
9169 *no_space_count = count + no_similar_count;
9170 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9175 // search free slot
9176 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9177 if(res!=EQUIP_ERR_OK)
9179 if(no_space_count)
9180 *no_space_count = count + no_similar_count;
9181 return res;
9184 if(count==0)
9186 if(no_similar_count==0)
9187 return EQUIP_ERR_OK;
9189 if(no_space_count)
9190 *no_space_count = count + no_similar_count;
9191 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9194 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9196 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9197 if(res!=EQUIP_ERR_OK)
9198 continue;
9200 if(count==0)
9202 if(no_similar_count==0)
9203 return EQUIP_ERR_OK;
9205 if(no_space_count)
9206 *no_space_count = count + no_similar_count;
9207 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9211 if(no_space_count)
9212 *no_space_count = count + no_similar_count;
9214 return EQUIP_ERR_INVENTORY_FULL;
9217 //////////////////////////////////////////////////////////////////////////
9218 uint8 Player::CanStoreItems( Item **pItems,int count) const
9220 Item *pItem2;
9222 // fill space table
9223 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9224 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9225 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9226 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9228 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9229 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9230 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9231 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9233 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9235 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9237 if (pItem2 && !pItem2->IsInTrade())
9239 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9243 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9245 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9247 if (pItem2 && !pItem2->IsInTrade())
9249 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9253 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9255 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9257 if (pItem2 && !pItem2->IsInTrade())
9259 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9263 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9265 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9267 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9269 pItem2 = GetItemByPos( i, j );
9270 if (pItem2 && !pItem2->IsInTrade())
9272 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9278 // check free space for all items
9279 for (int k = 0; k < count; ++k)
9281 Item *pItem = pItems[k];
9283 // no item
9284 if (!pItem) continue;
9286 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9287 ItemPrototype const *pProto = pItem->GetProto();
9289 // strange item
9290 if( !pProto )
9291 return EQUIP_ERR_ITEM_NOT_FOUND;
9293 // item it 'bind'
9294 if(pItem->IsBindedNotWith(GetGUID()))
9295 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9297 Bag *pBag;
9298 ItemPrototype const *pBagProto;
9300 // item is 'one item only'
9301 uint8 res = CanTakeMoreSimilarItems(pItem);
9302 if(res != EQUIP_ERR_OK)
9303 return res;
9305 // search stack for merge to
9306 if( pProto->Stackable != 1 )
9308 bool b_found = false;
9310 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9312 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9313 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9315 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9316 b_found = true;
9317 break;
9320 if (b_found) continue;
9322 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9324 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9325 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9327 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9328 b_found = true;
9329 break;
9332 if (b_found) continue;
9334 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9336 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9337 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9339 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9340 b_found = true;
9341 break;
9344 if (b_found) continue;
9346 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9348 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9349 if( pBag )
9351 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9353 pItem2 = GetItemByPos( t, j );
9354 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9356 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9357 b_found = true;
9358 break;
9363 if (b_found) continue;
9366 // special bag case
9367 if( pProto->BagFamily )
9369 bool b_found = false;
9370 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9372 uint32 keyringSize = GetMaxKeyringSize();
9373 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9375 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9377 inv_keys[t-KEYRING_SLOT_START] = 1;
9378 b_found = true;
9379 break;
9384 if (b_found) continue;
9386 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9388 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9390 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9392 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9393 b_found = true;
9394 break;
9399 if (b_found) continue;
9401 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9403 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9404 if( pBag )
9406 pBagProto = pBag->GetProto();
9408 // not plain container check
9409 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9410 ItemCanGoIntoBag(pProto,pBagProto) )
9412 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9414 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9416 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9417 b_found = true;
9418 break;
9424 if (b_found) continue;
9427 // search free slot
9428 bool b_found = false;
9429 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9431 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9433 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9434 b_found = true;
9435 break;
9438 if (b_found) continue;
9440 // search free slot in bags
9441 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9443 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9444 if( pBag )
9446 pBagProto = pBag->GetProto();
9448 // special bag already checked
9449 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9450 continue;
9452 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9454 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9456 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9457 b_found = true;
9458 break;
9464 // no free slot found?
9465 if (!b_found)
9466 return EQUIP_ERR_INVENTORY_FULL;
9469 return EQUIP_ERR_OK;
9472 //////////////////////////////////////////////////////////////////////////
9473 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9475 dest = 0;
9476 Item *pItem = Item::CreateItem( item, 1, this );
9477 if( pItem )
9479 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9480 delete pItem;
9481 return result;
9484 return EQUIP_ERR_ITEM_NOT_FOUND;
9487 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9489 dest = 0;
9490 if( pItem )
9492 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9493 ItemPrototype const *pProto = pItem->GetProto();
9494 if( pProto )
9496 if(pItem->IsBindedNotWith(GetGUID()))
9497 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9499 // check count of items (skip for auto move for same player from bank)
9500 uint8 res = CanTakeMoreSimilarItems(pItem);
9501 if(res != EQUIP_ERR_OK)
9502 return res;
9504 // check this only in game
9505 if(not_loading)
9507 // May be here should be more stronger checks; STUNNED checked
9508 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9509 if (hasUnitState(UNIT_STAT_STUNNED))
9510 return EQUIP_ERR_YOU_ARE_STUNNED;
9512 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9513 // - combat
9514 // - in-progress arenas
9515 if( !pProto->CanChangeEquipStateInCombat() )
9517 if( isInCombat() )
9518 return EQUIP_ERR_NOT_IN_COMBAT;
9520 if(BattleGround* bg = GetBattleGround())
9521 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9522 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9525 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9526 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9528 if(IsNonMeleeSpellCasted(false))
9529 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9532 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9533 if( eslot == NULL_SLOT )
9534 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9536 uint8 msg = CanUseItem( pItem , not_loading );
9537 if( msg != EQUIP_ERR_OK )
9538 return msg;
9539 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9540 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9542 // if swap ignore item (equipped also)
9543 if(uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9544 return res2;
9546 // check unique-equipped special item classes
9547 if (pProto->Class == ITEM_CLASS_QUIVER)
9549 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9551 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9553 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9555 if( pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot ) )
9557 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9558 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9559 else
9560 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9567 uint32 type = pProto->InventoryType;
9569 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9571 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9573 if(!CanDualWield())
9574 return EQUIP_ERR_CANT_DUAL_WIELD;
9576 else if (type == INVTYPE_2HWEAPON)
9578 if(!CanDualWield() || !CanTitanGrip())
9579 return EQUIP_ERR_CANT_DUAL_WIELD;
9582 if(IsTwoHandUsed())
9583 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9586 // equip two-hand weapon case (with possible unequip 2 items)
9587 if( type == INVTYPE_2HWEAPON )
9589 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9591 if (!CanTitanGrip())
9592 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9594 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9595 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9597 if (!CanTitanGrip())
9599 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9600 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9601 ItemPosCountVec off_dest;
9602 if( offItem && (!not_loading ||
9603 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9604 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9605 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9608 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9609 return EQUIP_ERR_OK;
9612 if( !swap )
9613 return EQUIP_ERR_ITEM_NOT_FOUND;
9614 else
9615 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9618 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9620 // Applied only to equipped items and bank bags
9621 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9622 return EQUIP_ERR_OK;
9624 Item* pItem = GetItemByPos(pos);
9626 // Applied only to existed equipped item
9627 if( !pItem )
9628 return EQUIP_ERR_OK;
9630 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9632 ItemPrototype const *pProto = pItem->GetProto();
9633 if( !pProto )
9634 return EQUIP_ERR_ITEM_NOT_FOUND;
9636 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9637 // - combat
9638 // - in-progress arenas
9639 if( !pProto->CanChangeEquipStateInCombat() )
9641 if( isInCombat() )
9642 return EQUIP_ERR_NOT_IN_COMBAT;
9644 if(BattleGround* bg = GetBattleGround())
9645 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9646 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9649 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9650 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9652 return EQUIP_ERR_OK;
9655 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9657 if( !pItem )
9658 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9660 uint32 count = pItem->GetCount();
9662 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9663 ItemPrototype const *pProto = pItem->GetProto();
9664 if( !pProto )
9665 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9667 if( pItem->IsBindedNotWith(GetGUID()) )
9668 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9670 // check count of items (skip for auto move for same player from bank)
9671 uint8 res = CanTakeMoreSimilarItems(pItem);
9672 if(res != EQUIP_ERR_OK)
9673 return res;
9675 // in specific slot
9676 if( bag != NULL_BAG && slot != NULL_SLOT )
9678 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9680 if (!pItem->IsBag())
9681 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9683 if( !HasBankBagSlot( slot ) )
9684 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9686 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9687 return cantuse;
9690 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9691 if(res!=EQUIP_ERR_OK)
9692 return res;
9694 if(count==0)
9695 return EQUIP_ERR_OK;
9698 // not specific slot or have space for partly store only in specific slot
9700 // in specific bag
9701 if( bag != NULL_BAG )
9703 if( pProto->InventoryType == INVTYPE_BAG )
9705 Bag *pBag = (Bag*)pItem;
9706 if( pBag && !pBag->IsEmpty() )
9707 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9710 // search stack in bag for merge to
9711 if( pProto->Stackable != 1 )
9713 if( bag == INVENTORY_SLOT_BAG_0 )
9715 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9716 if(res!=EQUIP_ERR_OK)
9717 return res;
9719 if(count==0)
9720 return EQUIP_ERR_OK;
9722 else
9724 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9725 if(res!=EQUIP_ERR_OK)
9726 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9728 if(res!=EQUIP_ERR_OK)
9729 return res;
9731 if(count==0)
9732 return EQUIP_ERR_OK;
9736 // search free slot in bag
9737 if( bag == INVENTORY_SLOT_BAG_0 )
9739 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9740 if(res!=EQUIP_ERR_OK)
9741 return res;
9743 if(count==0)
9744 return EQUIP_ERR_OK;
9746 else
9748 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
9749 if(res != EQUIP_ERR_OK)
9750 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
9752 if(res != EQUIP_ERR_OK)
9753 return res;
9755 if(count == 0)
9756 return EQUIP_ERR_OK;
9760 // not specific bag or have space for partly store only in specific bag
9762 // search stack for merge to
9763 if( pProto->Stackable != 1 )
9765 // in slots
9766 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9767 if(res != EQUIP_ERR_OK)
9768 return res;
9770 if(count == 0)
9771 return EQUIP_ERR_OK;
9773 // in special bags
9774 if( pProto->BagFamily )
9776 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9778 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9779 if(res!=EQUIP_ERR_OK)
9780 continue;
9782 if(count==0)
9783 return EQUIP_ERR_OK;
9787 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9789 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9790 if(res!=EQUIP_ERR_OK)
9791 continue;
9793 if(count==0)
9794 return EQUIP_ERR_OK;
9798 // search free place in special bag
9799 if( pProto->BagFamily )
9801 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9803 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9804 if(res!=EQUIP_ERR_OK)
9805 continue;
9807 if(count==0)
9808 return EQUIP_ERR_OK;
9812 // search free space
9813 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9814 if(res!=EQUIP_ERR_OK)
9815 return res;
9817 if(count==0)
9818 return EQUIP_ERR_OK;
9820 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9822 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9823 if(res!=EQUIP_ERR_OK)
9824 continue;
9826 if(count==0)
9827 return EQUIP_ERR_OK;
9829 return EQUIP_ERR_BANK_FULL;
9832 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9834 if( pItem )
9836 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9837 if( !isAlive() && not_loading )
9838 return EQUIP_ERR_YOU_ARE_DEAD;
9839 //if( isStunned() )
9840 // return EQUIP_ERR_YOU_ARE_STUNNED;
9841 ItemPrototype const *pProto = pItem->GetProto();
9842 if( pProto )
9844 if( pItem->IsBindedNotWith(GetGUID()) )
9845 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9846 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9847 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9848 if( pItem->GetSkill() != 0 )
9850 if( GetSkillValue( pItem->GetSkill() ) == 0 )
9851 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9853 if( pProto->RequiredSkill != 0 )
9855 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9856 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9857 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9858 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9860 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9861 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9862 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
9863 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9864 if( getLevel() < pProto->RequiredLevel )
9865 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9866 return EQUIP_ERR_OK;
9869 return EQUIP_ERR_ITEM_NOT_FOUND;
9872 bool Player::CanUseItem( ItemPrototype const *pProto )
9874 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9876 if( pProto )
9878 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9879 return false;
9880 if( pProto->RequiredSkill != 0 )
9882 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9883 return false;
9884 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9885 return false;
9887 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9888 return false;
9889 if( getLevel() < pProto->RequiredLevel )
9890 return false;
9891 return true;
9893 return false;
9896 uint8 Player::CanUseAmmo( uint32 item ) const
9898 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
9899 if( !isAlive() )
9900 return EQUIP_ERR_YOU_ARE_DEAD;
9901 //if( isStunned() )
9902 // return EQUIP_ERR_YOU_ARE_STUNNED;
9903 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
9904 if( pProto )
9906 if( pProto->InventoryType!= INVTYPE_AMMO )
9907 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
9908 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9909 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9910 if( pProto->RequiredSkill != 0 )
9912 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9913 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9914 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9915 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9917 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9918 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9919 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
9920 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9922 if( getLevel() < pProto->RequiredLevel )
9923 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9925 // Requires No Ammo
9926 if(GetDummyAura(46699))
9927 return EQUIP_ERR_BAG_FULL6;
9929 return EQUIP_ERR_OK;
9931 return EQUIP_ERR_ITEM_NOT_FOUND;
9934 void Player::SetAmmo( uint32 item )
9936 if(!item)
9937 return;
9939 // already set
9940 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
9941 return;
9943 // check ammo
9944 if(item)
9946 uint8 msg = CanUseAmmo( item );
9947 if( msg != EQUIP_ERR_OK )
9949 SendEquipError( msg, NULL, NULL );
9950 return;
9954 SetUInt32Value(PLAYER_AMMO_ID, item);
9956 _ApplyAmmoBonuses();
9959 void Player::RemoveAmmo()
9961 SetUInt32Value(PLAYER_AMMO_ID, 0);
9963 m_ammoDPS = 0.0f;
9965 if(CanModifyStats())
9966 UpdateDamagePhysical(RANGED_ATTACK);
9969 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9970 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
9972 uint32 count = 0;
9973 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
9974 count += itr->count;
9976 Item *pItem = Item::CreateItem( item, count, this );
9977 if( pItem )
9979 ItemAddedQuestCheck( item, count );
9980 if(randomPropertyId)
9981 pItem->SetItemRandomProperties(randomPropertyId);
9982 pItem = StoreItem( dest, pItem, update );
9984 return pItem;
9987 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
9989 if( !pItem )
9990 return NULL;
9992 Item* lastItem = pItem;
9993 uint32 entry = pItem->GetEntry();
9994 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
9996 uint16 pos = itr->pos;
9997 uint32 count = itr->count;
9999 ++itr;
10001 if(itr == dest.end())
10003 lastItem = _StoreItem(pos,pItem,count,false,update);
10004 break;
10007 lastItem = _StoreItem(pos,pItem,count,true,update);
10009 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10010 return lastItem;
10013 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10014 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10016 if( !pItem )
10017 return NULL;
10019 uint8 bag = pos >> 8;
10020 uint8 slot = pos & 255;
10022 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10024 Item *pItem2 = GetItemByPos( bag, slot );
10026 if (!pItem2)
10028 if (clone)
10029 pItem = pItem->CloneItem(count, this);
10030 else
10031 pItem->SetCount(count);
10033 if (!pItem)
10034 return NULL;
10036 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10037 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10038 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10039 pItem->SetBinding( true );
10041 if (bag == INVENTORY_SLOT_BAG_0)
10043 m_items[slot] = pItem;
10044 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10045 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10046 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10048 pItem->SetSlot( slot );
10049 pItem->SetContainer( NULL );
10051 // need update known currency
10052 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10053 UpdateKnownCurrencies(pItem->GetEntry(), true);
10055 if (IsInWorld() && update)
10057 pItem->AddToWorld();
10058 pItem->SendUpdateToPlayer( this );
10061 pItem->SetState(ITEM_CHANGED, this);
10063 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10065 pBag->StoreItem( slot, pItem, update );
10066 if( IsInWorld() && update )
10068 pItem->AddToWorld();
10069 pItem->SendUpdateToPlayer( this );
10071 pItem->SetState(ITEM_CHANGED, this);
10072 pBag->SetState(ITEM_CHANGED, this);
10075 AddEnchantmentDurations(pItem);
10076 AddItemDurations(pItem);
10078 return pItem;
10080 else
10082 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10083 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10084 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10085 pItem2->SetBinding( true );
10087 pItem2->SetCount( pItem2->GetCount() + count );
10088 if (IsInWorld() && update)
10089 pItem2->SendUpdateToPlayer( this );
10091 if (!clone)
10093 // delete item (it not in any slot currently)
10094 if (IsInWorld() && update)
10096 pItem->RemoveFromWorld();
10097 pItem->DestroyForPlayer( this );
10100 RemoveEnchantmentDurations(pItem);
10101 RemoveItemDurations(pItem);
10103 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10104 pItem->SetState(ITEM_REMOVED, this);
10107 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10108 AddEnchantmentDurations(pItem2);
10110 pItem2->SetState(ITEM_CHANGED, this);
10112 return pItem2;
10116 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10118 if (Item *pItem = Item::CreateItem( item, 1, this ))
10120 ItemAddedQuestCheck( item, 1 );
10121 return EquipItem( pos, pItem, update );
10124 return NULL;
10127 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10130 AddEnchantmentDurations(pItem);
10131 AddItemDurations(pItem);
10133 uint8 bag = pos >> 8;
10134 uint8 slot = pos & 255;
10136 Item *pItem2 = GetItemByPos( bag, slot );
10138 if( !pItem2 )
10140 VisualizeItem( slot, pItem);
10142 if(isAlive())
10144 ItemPrototype const *pProto = pItem->GetProto();
10146 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10147 if(pProto && pProto->ItemSet)
10148 AddItemsSetItem(this, pItem);
10150 _ApplyItemMods(pItem, slot, true);
10152 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10154 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10156 if (getClass() == CLASS_ROGUE)
10157 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10159 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10161 if (!spellProto)
10162 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10163 else
10165 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10167 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10168 data << uint64(GetGUID());
10169 data << uint8(1);
10170 data << uint32(cooldownSpell);
10171 data << uint32(0);
10172 GetSession()->SendPacket(&data);
10177 if( IsInWorld() && update )
10179 pItem->AddToWorld();
10180 pItem->SendUpdateToPlayer( this );
10183 ApplyEquipCooldown(pItem);
10185 if( slot == EQUIPMENT_SLOT_MAINHAND )
10186 UpdateExpertise(BASE_ATTACK);
10187 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10188 UpdateExpertise(OFF_ATTACK);
10190 else
10192 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10193 if( IsInWorld() && update )
10194 pItem2->SendUpdateToPlayer( this );
10196 // delete item (it not in any slot currently)
10197 //pItem->DeleteFromDB();
10198 if( IsInWorld() && update )
10200 pItem->RemoveFromWorld();
10201 pItem->DestroyForPlayer( this );
10204 RemoveEnchantmentDurations(pItem);
10205 RemoveItemDurations(pItem);
10207 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10208 pItem->SetState(ITEM_REMOVED, this);
10209 pItem2->SetState(ITEM_CHANGED, this);
10211 ApplyEquipCooldown(pItem2);
10213 return pItem2;
10216 // only for full equip instead adding to stack
10217 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10219 return pItem;
10222 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10224 if( pItem )
10226 AddEnchantmentDurations(pItem);
10227 AddItemDurations(pItem);
10229 uint8 slot = pos & 255;
10230 VisualizeItem( slot, pItem);
10232 if( IsInWorld() )
10234 pItem->AddToWorld();
10235 pItem->SendUpdateToPlayer( this );
10240 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10242 if(pItem)
10244 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10245 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10246 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10248 else
10250 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10251 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10255 void Player::VisualizeItem( uint8 slot, Item *pItem)
10257 if(!pItem)
10258 return;
10260 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10261 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10262 pItem->SetBinding( true );
10264 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10266 m_items[slot] = pItem;
10267 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10268 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10269 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10270 pItem->SetSlot( slot );
10271 pItem->SetContainer( NULL );
10273 if( slot < EQUIPMENT_SLOT_END )
10274 SetVisibleItemSlot(slot, pItem);
10276 pItem->SetState(ITEM_CHANGED, this);
10279 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10281 // note: removeitem does not actually change the item
10282 // it only takes the item out of storage temporarily
10283 // note2: if removeitem is to be used for delinking
10284 // the item must be removed from the player's updatequeue
10286 Item *pItem = GetItemByPos( bag, slot );
10287 if( pItem )
10289 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10291 RemoveEnchantmentDurations(pItem);
10292 RemoveItemDurations(pItem);
10294 if( bag == INVENTORY_SLOT_BAG_0 )
10296 if ( slot < INVENTORY_SLOT_BAG_END )
10298 ItemPrototype const *pProto = pItem->GetProto();
10299 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10301 if(pProto && pProto->ItemSet)
10302 RemoveItemsSetItem(this, pProto);
10304 _ApplyItemMods(pItem, slot, false);
10306 // remove item dependent auras and casts (only weapon and armor slots)
10307 if(slot < EQUIPMENT_SLOT_END)
10309 RemoveItemDependentAurasAndCasts(pItem);
10311 // remove held enchantments, update expertise
10312 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10314 if (pItem->GetItemSuffixFactor())
10316 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10317 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10319 else
10321 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10322 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10325 UpdateExpertise(BASE_ATTACK);
10327 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10328 UpdateExpertise(OFF_ATTACK);
10331 // need update known currency
10332 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10333 UpdateKnownCurrencies(pItem->GetEntry(), false);
10335 m_items[slot] = NULL;
10336 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10338 if ( slot < EQUIPMENT_SLOT_END )
10339 SetVisibleItemSlot(slot, NULL);
10341 else
10343 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10344 if( pBag )
10345 pBag->RemoveItem(slot, update);
10347 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10348 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10349 pItem->SetSlot( NULL_SLOT );
10350 if( IsInWorld() && update )
10351 pItem->SendUpdateToPlayer( this );
10355 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10356 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10358 if(Item* it = GetItemByPos(bag,slot))
10360 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10361 RemoveItem(bag, slot, update);
10362 it->RemoveFromUpdateQueueOf(this);
10363 if(it->IsInWorld())
10365 it->RemoveFromWorld();
10366 it->DestroyForPlayer( this );
10371 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10372 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10374 // update quest counters
10375 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10377 // store item
10378 Item* pLastItem = StoreItem(dest, pItem, update);
10380 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10381 if(pLastItem == pItem)
10383 // update owner for last item (this can be original item with wrong owner
10384 if(pLastItem->GetOwnerGUID() != GetGUID())
10385 pLastItem->SetOwnerGUID(GetGUID());
10387 // if this original item then it need create record in inventory
10388 // in case trade we already have item in other player inventory
10389 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10393 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10395 Item *pItem = GetItemByPos( bag, slot );
10396 if( pItem )
10398 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10400 // start from destroy contained items (only equipped bag can have its)
10401 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10403 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10404 DestroyItem(slot, i, update);
10407 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10408 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10410 RemoveEnchantmentDurations(pItem);
10411 RemoveItemDurations(pItem);
10413 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10415 if( bag == INVENTORY_SLOT_BAG_0 )
10417 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10419 // equipment and equipped bags can have applied bonuses
10420 if ( slot < INVENTORY_SLOT_BAG_END )
10422 ItemPrototype const *pProto = pItem->GetProto();
10424 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10425 if(pProto && pProto->ItemSet)
10426 RemoveItemsSetItem(this, pProto);
10428 _ApplyItemMods(pItem, slot, false);
10431 if ( slot < EQUIPMENT_SLOT_END )
10433 // remove item dependent auras and casts (only weapon and armor slots)
10434 RemoveItemDependentAurasAndCasts(pItem);
10436 // update expertise
10437 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10438 UpdateExpertise(BASE_ATTACK);
10439 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10440 UpdateExpertise(OFF_ATTACK);
10442 // equipment visual show
10443 SetVisibleItemSlot(slot, NULL);
10445 // need update known currency
10446 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10447 UpdateKnownCurrencies(pItem->GetEntry(), false);
10449 m_items[slot] = NULL;
10451 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10452 pBag->RemoveItem(slot, update);
10454 if( IsInWorld() && update )
10456 pItem->RemoveFromWorld();
10457 pItem->DestroyForPlayer(this);
10460 //pItem->SetOwnerGUID(0);
10461 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10462 pItem->SetSlot( NULL_SLOT );
10463 pItem->SetState(ITEM_REMOVED, this);
10467 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10469 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10470 uint32 remcount = 0;
10472 // in inventory
10473 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10475 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10477 if (pItem->GetEntry() == item)
10479 if (pItem->GetCount() + remcount <= count)
10481 // all items in inventory can unequipped
10482 remcount += pItem->GetCount();
10483 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10485 if (remcount >= count)
10486 return;
10488 else
10490 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10491 pItem->SetCount( pItem->GetCount() - count + remcount );
10492 if (IsInWorld() & update)
10493 pItem->SendUpdateToPlayer( this );
10494 pItem->SetState(ITEM_CHANGED, this);
10495 return;
10501 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10503 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10505 if (pItem->GetEntry() == item)
10507 if (pItem->GetCount() + remcount <= count)
10509 // all keys can be unequipped
10510 remcount += pItem->GetCount();
10511 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10513 if (remcount >= count)
10514 return;
10516 else
10518 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10519 pItem->SetCount( pItem->GetCount() - count + remcount );
10520 if (IsInWorld() & update)
10521 pItem->SendUpdateToPlayer( this );
10522 pItem->SetState(ITEM_CHANGED, this);
10523 return;
10529 // in inventory bags
10530 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10532 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10534 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10536 if(Item* pItem = pBag->GetItemByPos(j))
10538 if (pItem->GetEntry() == item)
10540 // all items in bags can be unequipped
10541 if (pItem->GetCount() + remcount <= count)
10543 remcount += pItem->GetCount();
10544 DestroyItem( i, j, update );
10546 if (remcount >= count)
10547 return;
10549 else
10551 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10552 pItem->SetCount( pItem->GetCount() - count + remcount );
10553 if (IsInWorld() && update)
10554 pItem->SendUpdateToPlayer( this );
10555 pItem->SetState(ITEM_CHANGED, this);
10556 return;
10564 // in equipment and bag list
10565 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10567 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10569 if (pItem && pItem->GetEntry() == item)
10571 if (pItem->GetCount() + remcount <= count)
10573 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
10575 remcount += pItem->GetCount();
10576 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10578 if (remcount >= count)
10579 return;
10582 else
10584 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10585 pItem->SetCount( pItem->GetCount() - count + remcount );
10586 if (IsInWorld() & update)
10587 pItem->SendUpdateToPlayer( this );
10588 pItem->SetState(ITEM_CHANGED, this);
10589 return;
10596 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10598 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10600 // in inventory
10601 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10602 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10603 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10604 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10606 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10607 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10608 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10609 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10611 // in inventory bags
10612 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10613 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10614 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10615 if (Item* pItem = pBag->GetItemByPos(j))
10616 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10617 DestroyItem( i, j, update);
10619 // in equipment and bag list
10620 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10621 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10622 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10623 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10626 void Player::DestroyConjuredItems( bool update )
10628 // used when entering arena
10629 // destroys all conjured items
10630 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10632 // in inventory
10633 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10634 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10635 if (pItem->IsConjuredConsumable())
10636 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10638 // in inventory bags
10639 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10640 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10641 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10642 if (Item* pItem = pBag->GetItemByPos(j))
10643 if (pItem->IsConjuredConsumable())
10644 DestroyItem( i, j, update);
10646 // in equipment and bag list
10647 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10648 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10649 if (pItem->IsConjuredConsumable())
10650 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10653 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10655 if(!pItem)
10656 return;
10658 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10660 if( pItem->GetCount() <= count )
10662 count -= pItem->GetCount();
10664 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10666 else
10668 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10669 pItem->SetCount( pItem->GetCount() - count );
10670 count = 0;
10671 if( IsInWorld() & update )
10672 pItem->SendUpdateToPlayer( this );
10673 pItem->SetState(ITEM_CHANGED, this);
10677 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10679 uint8 srcbag = src >> 8;
10680 uint8 srcslot = src & 255;
10682 uint8 dstbag = dst >> 8;
10683 uint8 dstslot = dst & 255;
10685 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10686 if( !pSrcItem )
10688 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10689 return;
10692 // not let split all items (can be only at cheating)
10693 if(pSrcItem->GetCount() == count)
10695 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10696 return;
10699 // not let split more existed items (can be only at cheating)
10700 if(pSrcItem->GetCount() < count)
10702 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10703 return;
10706 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10708 //best error message found for attempting to split while looting
10709 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10710 return;
10713 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10714 Item *pNewItem = pSrcItem->CloneItem( count, this );
10715 if( !pNewItem )
10717 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10718 return;
10721 if( IsInventoryPos( dst ) )
10723 // change item amount before check (for unique max count check)
10724 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10726 ItemPosCountVec dest;
10727 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10728 if( msg != EQUIP_ERR_OK )
10730 delete pNewItem;
10731 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10732 SendEquipError( msg, pSrcItem, NULL );
10733 return;
10736 if( IsInWorld() )
10737 pSrcItem->SendUpdateToPlayer( this );
10738 pSrcItem->SetState(ITEM_CHANGED, this);
10739 StoreItem( dest, pNewItem, true);
10741 else if( IsBankPos ( dst ) )
10743 // change item amount before check (for unique max count check)
10744 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10746 ItemPosCountVec dest;
10747 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10748 if( msg != EQUIP_ERR_OK )
10750 delete pNewItem;
10751 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10752 SendEquipError( msg, pSrcItem, NULL );
10753 return;
10756 if( IsInWorld() )
10757 pSrcItem->SendUpdateToPlayer( this );
10758 pSrcItem->SetState(ITEM_CHANGED, this);
10759 BankItem( dest, pNewItem, true);
10761 else if( IsEquipmentPos ( dst ) )
10763 // change item amount before check (for unique max count check), provide space for splitted items
10764 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10766 uint16 dest;
10767 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10768 if( msg != EQUIP_ERR_OK )
10770 delete pNewItem;
10771 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10772 SendEquipError( msg, pSrcItem, NULL );
10773 return;
10776 if( IsInWorld() )
10777 pSrcItem->SendUpdateToPlayer( this );
10778 pSrcItem->SetState(ITEM_CHANGED, this);
10779 EquipItem( dest, pNewItem, true);
10780 AutoUnequipOffhandIfNeed();
10784 void Player::SwapItem( uint16 src, uint16 dst )
10786 uint8 srcbag = src >> 8;
10787 uint8 srcslot = src & 255;
10789 uint8 dstbag = dst >> 8;
10790 uint8 dstslot = dst & 255;
10792 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10793 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10795 if( !pSrcItem )
10796 return;
10798 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10800 if(!isAlive() )
10802 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10803 return;
10806 // SRC checks
10808 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10810 //best error message found for attempting to swap while looting
10811 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10812 return;
10815 // check unequip potability for equipped items and bank bags
10816 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10818 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10819 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
10820 if(msg != EQUIP_ERR_OK)
10822 SendEquipError( msg, pSrcItem, pDstItem );
10823 return;
10827 // prevent put equipped/bank bag in self
10828 if( IsBagPos ( src ) && srcslot == dstbag)
10830 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10831 return;
10834 // DST checks
10836 if (pDstItem)
10838 if(pDstItem->m_lootGenerated) // prevent swap looting item
10840 //best error message found for attempting to swap while looting
10841 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10842 return;
10845 // check unequip potability for equipped items and bank bags
10846 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10848 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10849 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
10850 if(msg != EQUIP_ERR_OK)
10852 SendEquipError( msg, pSrcItem, pDstItem );
10853 return;
10858 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10859 // or swap empty bag with another empty or not empty bag (with items exchange)
10861 // Move case
10862 if( !pDstItem )
10864 if( IsInventoryPos( dst ) )
10866 ItemPosCountVec dest;
10867 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10868 if( msg != EQUIP_ERR_OK )
10870 SendEquipError( msg, pSrcItem, NULL );
10871 return;
10874 RemoveItem(srcbag, srcslot, true);
10875 StoreItem( dest, pSrcItem, true);
10877 else if( IsBankPos ( dst ) )
10879 ItemPosCountVec dest;
10880 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10881 if( msg != EQUIP_ERR_OK )
10883 SendEquipError( msg, pSrcItem, NULL );
10884 return;
10887 RemoveItem(srcbag, srcslot, true);
10888 BankItem( dest, pSrcItem, true);
10890 else if( IsEquipmentPos ( dst ) )
10892 uint16 dest;
10893 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10894 if( msg != EQUIP_ERR_OK )
10896 SendEquipError( msg, pSrcItem, NULL );
10897 return;
10900 RemoveItem(srcbag, srcslot, true);
10901 EquipItem(dest, pSrcItem, true);
10902 AutoUnequipOffhandIfNeed();
10905 return;
10908 // attempt merge to / fill target item
10909 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
10911 uint8 msg;
10912 ItemPosCountVec sDest;
10913 uint16 eDest;
10914 if( IsInventoryPos( dst ) )
10915 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
10916 else if( IsBankPos ( dst ) )
10917 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
10918 else if( IsEquipmentPos ( dst ) )
10919 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
10920 else
10921 return;
10923 // can be merge/fill
10924 if(msg == EQUIP_ERR_OK)
10926 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
10928 RemoveItem(srcbag, srcslot, true);
10930 if( IsInventoryPos( dst ) )
10931 StoreItem( sDest, pSrcItem, true);
10932 else if( IsBankPos ( dst ) )
10933 BankItem( sDest, pSrcItem, true);
10934 else if( IsEquipmentPos ( dst ) )
10936 EquipItem( eDest, pSrcItem, true);
10937 AutoUnequipOffhandIfNeed();
10940 else
10942 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
10943 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
10944 pSrcItem->SetState(ITEM_CHANGED, this);
10945 pDstItem->SetState(ITEM_CHANGED, this);
10946 if( IsInWorld() )
10948 pSrcItem->SendUpdateToPlayer( this );
10949 pDstItem->SendUpdateToPlayer( this );
10952 return;
10956 // impossible merge/fill, do real swap
10957 uint8 msg;
10959 // check src->dest move possibility
10960 ItemPosCountVec sDest;
10961 uint16 eDest = 0;
10962 if( IsInventoryPos( dst ) )
10963 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
10964 else if( IsBankPos( dst ) )
10965 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
10966 else if( IsEquipmentPos( dst ) )
10968 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
10969 if( msg == EQUIP_ERR_OK )
10970 msg = CanUnequipItem( eDest, true );
10973 if( msg != EQUIP_ERR_OK )
10975 SendEquipError( msg, pSrcItem, pDstItem );
10976 return;
10979 // check dest->src move possibility
10980 ItemPosCountVec sDest2;
10981 uint16 eDest2 = 0;
10982 if( IsInventoryPos( src ) )
10983 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
10984 else if( IsBankPos( src ) )
10985 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
10986 else if( IsEquipmentPos( src ) )
10988 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
10989 if( msg == EQUIP_ERR_OK )
10990 msg = CanUnequipItem( eDest2, true);
10993 if( msg != EQUIP_ERR_OK )
10995 SendEquipError( msg, pDstItem, pSrcItem );
10996 return;
10999 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11000 if(pSrcItem->IsBag() && pDstItem->IsBag())
11002 Bag* emptyBag = NULL;
11003 Bag* fullBag = NULL;
11004 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11006 emptyBag = (Bag*)pSrcItem;
11007 fullBag = (Bag*)pDstItem;
11009 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11011 emptyBag = (Bag*)pDstItem;
11012 fullBag = (Bag*)pSrcItem;
11015 // bag swap (with items exchange) case
11016 if(emptyBag && fullBag)
11018 ItemPrototype const* emotyProto = emptyBag->GetProto();
11020 uint32 count = 0;
11022 for(int i=0; i < fullBag->GetBagSize(); ++i)
11024 Item *bagItem = fullBag->GetItemByPos(i);
11025 if (!bagItem)
11026 continue;
11028 ItemPrototype const* bagItemProto = bagItem->GetProto();
11029 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11031 // one from items not go to empty target bag
11032 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11033 return;
11036 ++count;
11040 if (count > emptyBag->GetBagSize())
11042 // too small targeted bag
11043 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11044 return;
11047 // Items swap
11048 count = 0; // will pos in new bag
11049 for(int i = 0; i< fullBag->GetBagSize(); ++i)
11051 Item *bagItem = fullBag->GetItemByPos(i);
11052 if (!bagItem)
11053 continue;
11055 fullBag->RemoveItem(i, true);
11056 emptyBag->StoreItem(count, bagItem, true);
11057 bagItem->SetState(ITEM_CHANGED, this);
11059 ++count;
11064 // now do moves, remove...
11065 RemoveItem(dstbag, dstslot, false);
11066 RemoveItem(srcbag, srcslot, false);
11068 // add to dest
11069 if( IsInventoryPos( dst ) )
11070 StoreItem(sDest, pSrcItem, true);
11071 else if( IsBankPos( dst ) )
11072 BankItem(sDest, pSrcItem, true);
11073 else if( IsEquipmentPos( dst ) )
11074 EquipItem(eDest, pSrcItem, true);
11076 // add to src
11077 if( IsInventoryPos( src ) )
11078 StoreItem(sDest2, pDstItem, true);
11079 else if( IsBankPos( src ) )
11080 BankItem(sDest2, pDstItem, true);
11081 else if( IsEquipmentPos( src ) )
11082 EquipItem(eDest2, pDstItem, true);
11084 AutoUnequipOffhandIfNeed();
11087 void Player::AddItemToBuyBackSlot( Item *pItem )
11089 if( pItem )
11091 uint32 slot = m_currentBuybackSlot;
11092 // if current back slot non-empty search oldest or free
11093 if(m_items[slot])
11095 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11096 uint32 oldest_slot = BUYBACK_SLOT_START;
11098 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11100 // found empty
11101 if(!m_items[i])
11103 slot = i;
11104 break;
11107 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11109 if(oldest_time > i_time)
11111 oldest_time = i_time;
11112 oldest_slot = i;
11116 // find oldest
11117 slot = oldest_slot;
11120 RemoveItemFromBuyBackSlot( slot, true );
11121 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11123 m_items[slot] = pItem;
11124 time_t base = time(NULL);
11125 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11126 uint32 eslot = slot - BUYBACK_SLOT_START;
11128 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11129 ItemPrototype const *pProto = pItem->GetProto();
11130 if( pProto )
11131 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11132 else
11133 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11134 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11136 // move to next (for non filled list is move most optimized choice)
11137 if(m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11138 ++m_currentBuybackSlot;
11142 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11144 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11145 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11146 return m_items[slot];
11147 return NULL;
11150 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11152 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11153 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11155 Item *pItem = m_items[slot];
11156 if( pItem )
11158 pItem->RemoveFromWorld();
11159 if(del) pItem->SetState(ITEM_REMOVED, this);
11162 m_items[slot] = NULL;
11164 uint32 eslot = slot - BUYBACK_SLOT_START;
11165 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11166 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11167 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11169 // if current backslot is filled set to now free slot
11170 if(m_items[m_currentBuybackSlot])
11171 m_currentBuybackSlot = slot;
11175 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11177 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11178 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11179 data << uint8(msg);
11181 if(msg)
11183 data << uint64(pItem ? pItem->GetGUID() : 0);
11184 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11185 data << uint8(0); // not 0 there...
11187 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11189 uint32 level = 0;
11191 if(pItem)
11192 if(ItemPrototype const* proto = pItem->GetProto())
11193 level = proto->RequiredLevel;
11195 data << uint32(level); // new 2.4.0
11198 GetSession()->SendPacket(&data);
11201 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11203 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11204 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11205 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11206 data << uint32(item);
11207 if( param > 0 )
11208 data << uint32(param);
11209 data << uint8(msg);
11210 GetSession()->SendPacket(&data);
11213 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11215 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11216 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11217 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11218 data << uint64(guid);
11219 if( param > 0 )
11220 data << uint32(param);
11221 data << uint8(msg);
11222 GetSession()->SendPacket(&data);
11225 void Player::ClearTrade()
11227 tradeGold = 0;
11228 acceptTrade = false;
11229 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11230 tradeItems[i] = NULL_SLOT;
11233 void Player::TradeCancel(bool sendback)
11235 if(pTrader)
11237 // send yellow "Trade canceled" message to both traders
11238 WorldSession* ws;
11239 ws = GetSession();
11240 if(sendback)
11241 ws->SendCancelTrade();
11242 ws = pTrader->GetSession();
11243 if(!ws->PlayerLogout())
11244 ws->SendCancelTrade();
11246 // cleanup
11247 ClearTrade();
11248 pTrader->ClearTrade();
11249 // prevent loss of reference
11250 pTrader->pTrader = NULL;
11251 pTrader = NULL;
11255 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11257 if(m_itemDuration.empty())
11258 return;
11260 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11262 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11264 Item* item = *itr;
11265 ++itr; // current element can be erased in UpdateDuration
11267 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11268 item->UpdateDuration(this,time);
11272 void Player::UpdateEnchantTime(uint32 time)
11274 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11276 assert(itr->item);
11277 next = itr;
11278 if(!itr->item->GetEnchantmentId(itr->slot))
11280 next = m_enchantDuration.erase(itr);
11282 else if(itr->leftduration <= time)
11284 ApplyEnchantment(itr->item, itr->slot, false, false);
11285 itr->item->ClearEnchantment(itr->slot);
11286 next = m_enchantDuration.erase(itr);
11288 else if(itr->leftduration > time)
11290 itr->leftduration -= time;
11291 ++next;
11296 void Player::AddEnchantmentDurations(Item *item)
11298 for(int x=0; x<MAX_ENCHANTMENT_SLOT; ++x)
11300 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11301 continue;
11303 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11304 if( duration > 0 )
11305 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11309 void Player::RemoveEnchantmentDurations(Item *item)
11311 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11313 if(itr->item == item)
11315 // save duration in item
11316 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11317 itr = m_enchantDuration.erase(itr);
11319 else
11320 ++itr;
11324 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11326 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11327 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11329 next = itr;
11330 if(itr->slot == slot)
11332 if(itr->item && itr->item->GetEnchantmentId(slot))
11334 // remove from stats
11335 ApplyEnchantment(itr->item, slot, false, false);
11336 // remove visual
11337 itr->item->ClearEnchantment(slot);
11339 // remove from update list
11340 next = m_enchantDuration.erase(itr);
11342 else
11343 ++next;
11346 // remove enchants from inventory items
11347 // NOTE: no need to remove these from stats, since these aren't equipped
11348 // in inventory
11349 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11351 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11352 if( pItem && pItem->GetEnchantmentId(slot) )
11353 pItem->ClearEnchantment(slot);
11356 // in inventory bags
11357 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11359 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11360 if( pBag )
11362 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11364 Item* pItem = pBag->GetItemByPos(j);
11365 if( pItem && pItem->GetEnchantmentId(slot) )
11366 pItem->ClearEnchantment(slot);
11372 // duration == 0 will remove item enchant
11373 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11375 if(!item)
11376 return;
11378 if(slot >= MAX_ENCHANTMENT_SLOT)
11379 return;
11381 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11383 if(itr->item == item && itr->slot == slot)
11385 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11386 m_enchantDuration.erase(itr);
11387 break;
11390 if(item && duration > 0 )
11392 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11393 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11397 void Player::ApplyEnchantment(Item *item,bool apply)
11399 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11400 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11403 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11405 if(!item)
11406 return;
11408 if(!item->IsEquipped())
11409 return;
11411 if(slot >= MAX_ENCHANTMENT_SLOT)
11412 return;
11414 uint32 enchant_id = item->GetEnchantmentId(slot);
11415 if(!enchant_id)
11416 return;
11418 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11419 if(!pEnchant)
11420 return;
11422 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11423 return;
11425 if (!item->IsBroken())
11427 for (int s = 0; s < 3; ++s)
11429 uint32 enchant_display_type = pEnchant->type[s];
11430 uint32 enchant_amount = pEnchant->amount[s];
11431 uint32 enchant_spell_id = pEnchant->spellid[s];
11433 switch(enchant_display_type)
11435 case ITEM_ENCHANTMENT_TYPE_NONE:
11436 break;
11437 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11438 // processed in Player::CastItemCombatSpell
11439 break;
11440 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11441 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11442 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11443 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11444 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11445 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11446 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11447 break;
11448 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11449 if(enchant_spell_id)
11451 if(apply)
11453 int32 basepoints = 0;
11454 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11455 if (item->GetItemRandomPropertyId())
11457 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11458 if (item_rand)
11460 // Search enchant_amount
11461 for (int k = 0; k < 3; ++k)
11463 if(item_rand->enchant_id[k] == enchant_id)
11465 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11466 break;
11471 // Cast custom spell vs all equal basepoints getted from enchant_amount
11472 if (basepoints)
11473 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11474 else
11475 CastSpell(this, enchant_spell_id, true, item);
11477 else
11478 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11480 break;
11481 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11482 if (!enchant_amount)
11484 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11485 if(item_rand)
11487 for (int k = 0; k < 3; ++k)
11489 if(item_rand->enchant_id[k] == enchant_id)
11491 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11492 break;
11498 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11499 break;
11500 case ITEM_ENCHANTMENT_TYPE_STAT:
11502 if (!enchant_amount)
11504 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11505 if(item_rand_suffix)
11507 for (int k = 0; k < 3; ++k)
11509 if(item_rand_suffix->enchant_id[k] == enchant_id)
11511 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11512 break;
11518 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11519 switch (enchant_spell_id)
11521 case ITEM_MOD_AGILITY:
11522 sLog.outDebug("+ %u AGILITY",enchant_amount);
11523 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11524 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11525 break;
11526 case ITEM_MOD_STRENGTH:
11527 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11528 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11529 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11530 break;
11531 case ITEM_MOD_INTELLECT:
11532 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11533 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11534 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11535 break;
11536 case ITEM_MOD_SPIRIT:
11537 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11538 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11539 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11540 break;
11541 case ITEM_MOD_STAMINA:
11542 sLog.outDebug("+ %u STAMINA",enchant_amount);
11543 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11544 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11545 break;
11546 case ITEM_MOD_DEFENSE_SKILL_RATING:
11547 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11548 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11549 break;
11550 case ITEM_MOD_DODGE_RATING:
11551 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11552 sLog.outDebug("+ %u DODGE", enchant_amount);
11553 break;
11554 case ITEM_MOD_PARRY_RATING:
11555 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11556 sLog.outDebug("+ %u PARRY", enchant_amount);
11557 break;
11558 case ITEM_MOD_BLOCK_RATING:
11559 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11560 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11561 break;
11562 case ITEM_MOD_HIT_MELEE_RATING:
11563 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11564 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11565 break;
11566 case ITEM_MOD_HIT_RANGED_RATING:
11567 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11568 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11569 break;
11570 case ITEM_MOD_HIT_SPELL_RATING:
11571 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11572 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11573 break;
11574 case ITEM_MOD_CRIT_MELEE_RATING:
11575 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11576 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11577 break;
11578 case ITEM_MOD_CRIT_RANGED_RATING:
11579 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11580 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11581 break;
11582 case ITEM_MOD_CRIT_SPELL_RATING:
11583 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11584 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11585 break;
11586 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11587 // in Enchantments
11588 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11589 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11590 // break;
11591 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11592 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11593 // break;
11594 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11595 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11596 // break;
11597 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11598 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11599 // break;
11600 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11601 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11602 // break;
11603 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11604 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11605 // break;
11606 // case ITEM_MOD_HASTE_MELEE_RATING:
11607 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11608 // break;
11609 // case ITEM_MOD_HASTE_RANGED_RATING:
11610 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11611 // break;
11612 case ITEM_MOD_HASTE_SPELL_RATING:
11613 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11614 break;
11615 case ITEM_MOD_HIT_RATING:
11616 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11617 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11618 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11619 sLog.outDebug("+ %u HIT", enchant_amount);
11620 break;
11621 case ITEM_MOD_CRIT_RATING:
11622 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11623 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11624 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11625 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11626 break;
11627 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11628 // case ITEM_MOD_HIT_TAKEN_RATING:
11629 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11630 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11631 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11632 // break;
11633 // case ITEM_MOD_CRIT_TAKEN_RATING:
11634 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11635 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11636 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11637 // break;
11638 case ITEM_MOD_RESILIENCE_RATING:
11639 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11640 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11641 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11642 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11643 break;
11644 case ITEM_MOD_HASTE_RATING:
11645 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11646 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11647 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11648 sLog.outDebug("+ %u HASTE", enchant_amount);
11649 break;
11650 case ITEM_MOD_EXPERTISE_RATING:
11651 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11652 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11653 break;
11654 case ITEM_MOD_ATTACK_POWER:
11655 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11656 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11657 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11658 break;
11659 case ITEM_MOD_RANGED_ATTACK_POWER:
11660 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11661 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11662 break;
11663 case ITEM_MOD_FERAL_ATTACK_POWER:
11664 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11665 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11666 break;
11667 case ITEM_MOD_SPELL_HEALING_DONE:
11668 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11669 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
11670 break;
11671 case ITEM_MOD_SPELL_DAMAGE_DONE:
11672 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11673 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
11674 break;
11675 case ITEM_MOD_MANA_REGENERATION:
11676 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
11677 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
11678 break;
11679 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11680 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11681 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11682 break;
11683 case ITEM_MOD_SPELL_POWER:
11684 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11685 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11686 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
11687 break;
11688 default:
11689 break;
11691 break;
11693 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11695 if(getClass() == CLASS_SHAMAN)
11697 float addValue = 0.0f;
11698 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11700 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11701 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11703 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11705 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11706 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11709 break;
11711 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
11712 // processed in Player::CastItemUseSpell
11713 break;
11714 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
11715 // nothing do..
11716 break;
11717 default:
11718 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
11719 break;
11720 } /*switch(enchant_display_type)*/
11721 } /*for*/
11724 // visualize enchantment at player and equipped items
11725 if(slot == PERM_ENCHANTMENT_SLOT)
11726 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
11728 if(slot == TEMP_ENCHANTMENT_SLOT)
11729 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
11732 if(apply_dur)
11734 if(apply)
11736 // set duration
11737 uint32 duration = item->GetEnchantmentDuration(slot);
11738 if(duration > 0)
11739 AddEnchantmentDuration(item, slot, duration);
11741 else
11743 // duration == 0 will remove EnchantDuration
11744 AddEnchantmentDuration(item, slot, 0);
11749 void Player::SendEnchantmentDurations()
11751 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11753 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
11757 void Player::SendItemDurations()
11759 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
11761 (*itr)->SendTimeUpdate(this);
11765 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11767 if(!item) // prevent crash
11768 return;
11770 // last check 2.0.10
11771 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11772 data << uint64(GetGUID()); // player GUID
11773 data << uint32(received); // 0=looted, 1=from npc
11774 data << uint32(created); // 0=received, 1=created
11775 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11776 data << uint8(item->GetBagSlot()); // bagslot
11777 // item slot, but when added to stack: 0xFFFFFFFF
11778 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
11779 data << uint32(item->GetEntry()); // item id
11780 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11781 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11782 data << uint32(count); // count of items
11783 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
11785 if (broadcast && GetGroup())
11786 GetGroup()->BroadcastPacket(&data, true);
11787 else
11788 GetSession()->SendPacket(&data);
11791 /*********************************************************/
11792 /*** QUEST SYSTEM ***/
11793 /*********************************************************/
11795 void Player::PrepareQuestMenu( uint64 guid )
11797 Object *pObject;
11798 QuestRelations* pObjectQR;
11799 QuestRelations* pObjectQIR;
11801 // pets also can have quests
11802 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
11803 if( pCreature )
11805 pObject = (Object*)pCreature;
11806 pObjectQR = &objmgr.mCreatureQuestRelations;
11807 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11809 else
11811 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11812 if( pGameObject )
11814 pObject = (Object*)pGameObject;
11815 pObjectQR = &objmgr.mGOQuestRelations;
11816 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11818 else
11819 return;
11822 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11823 qm.ClearMenu();
11825 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11827 uint32 quest_id = i->second;
11828 QuestStatus status = GetQuestStatus( quest_id );
11829 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11830 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11831 else if ( status == QUEST_STATUS_INCOMPLETE )
11832 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11833 else if (status == QUEST_STATUS_AVAILABLE )
11834 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11837 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11839 uint32 quest_id = i->second;
11840 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11841 if(!pQuest) continue;
11843 QuestStatus status = GetQuestStatus( quest_id );
11845 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11846 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11847 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11848 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11852 void Player::SendPreparedQuest( uint64 guid )
11854 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11855 if( questMenu.Empty() )
11856 return;
11858 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11860 uint32 status = qmi0.m_qIcon;
11862 // single element case
11863 if ( questMenu.MenuItemCount() == 1 )
11865 // Auto open -- maybe also should verify there is no greeting
11866 uint32 quest_id = qmi0.m_qId;
11867 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11869 if ( pQuest )
11871 if( status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus( quest_id ) )
11872 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
11873 else if( status == DIALOG_STATUS_UNK2 )
11874 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
11875 // Send completable on repeatable quest if player don't have quest
11876 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
11877 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11878 else
11879 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11882 // multiply entries
11883 else
11885 QEmote qe;
11886 qe._Delay = 0;
11887 qe._Emote = 0;
11888 std::string title = "";
11890 // need pet case for some quests
11891 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
11892 if( pCreature )
11894 uint32 textid = pCreature->GetNpcTextId();
11895 GossipText const* gossiptext = objmgr.GetGossipText(textid);
11896 if( !gossiptext )
11898 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11899 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11900 title = "";
11902 else
11904 qe = gossiptext->Options[0].Emotes[0];
11906 if(!gossiptext->Options[0].Text_0.empty())
11908 title = gossiptext->Options[0].Text_0;
11910 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11911 if (loc_idx >= 0)
11913 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11914 if (nl)
11916 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
11917 title = nl->Text_0[0][loc_idx];
11921 else
11923 title = gossiptext->Options[0].Text_1;
11925 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11926 if (loc_idx >= 0)
11928 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11929 if (nl)
11931 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
11932 title = nl->Text_1[0][loc_idx];
11938 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
11942 bool Player::IsActiveQuest( uint32 quest_id ) const
11944 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
11946 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
11949 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
11951 Object *pObject;
11952 QuestRelations* pObjectQR;
11953 QuestRelations* pObjectQIR;
11955 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
11956 if( pCreature )
11958 pObject = (Object*)pCreature;
11959 pObjectQR = &objmgr.mCreatureQuestRelations;
11960 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11962 else
11964 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11965 if( pGameObject )
11967 pObject = (Object*)pGameObject;
11968 pObjectQR = &objmgr.mGOQuestRelations;
11969 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11971 else
11972 return NULL;
11975 uint32 nextQuestID = pQuest->GetNextQuestInChain();
11976 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
11978 if (itr->second == nextQuestID)
11979 return objmgr.GetQuestTemplate(nextQuestID);
11982 return NULL;
11985 bool Player::CanSeeStartQuest( Quest const *pQuest )
11987 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
11988 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
11989 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
11990 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
11992 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
11995 return false;
11998 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12000 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12001 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12002 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12003 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12004 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12005 && SatisfyQuestDay( pQuest, msg );
12008 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12010 if( !SatisfyQuestLog( msg ) )
12011 return false;
12013 uint32 srcitem = pQuest->GetSrcItemId();
12014 if( srcitem > 0 )
12016 uint32 count = pQuest->GetSrcItemCount();
12017 ItemPosCountVec dest;
12018 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12020 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12021 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12022 return true;
12023 else if( msg2 != EQUIP_ERR_OK )
12025 SendEquipError( msg2, NULL, NULL );
12026 return false;
12029 return true;
12032 bool Player::CanCompleteQuest( uint32 quest_id )
12034 if( quest_id )
12036 QuestStatusData& q_status = mQuestStatus[quest_id];
12037 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12038 return false; // not allow re-complete quest
12040 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12042 if(!qInfo)
12043 return false;
12045 // auto complete quest
12046 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12047 return true;
12049 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12052 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12054 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12056 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12057 return false;
12061 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12063 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12065 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12066 continue;
12068 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12069 return false;
12073 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12074 return false;
12076 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12077 return false;
12079 if ( qInfo->GetRewOrReqMoney() < 0 )
12081 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12082 return false;
12085 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12086 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12087 return false;
12089 return true;
12092 return false;
12095 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12097 // Solve problem that player don't have the quest and try complete it.
12098 // if repeatable she must be able to complete event if player don't have it.
12099 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12100 if( !CanTakeQuest(pQuest, false) )
12101 return false;
12103 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12104 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12105 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12106 return false;
12108 if( !CanRewardQuest(pQuest, false) )
12109 return false;
12111 return true;
12114 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12116 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12117 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12118 return false;
12120 // daily quest can't be rewarded (25 daily quest already completed)
12121 if(!SatisfyQuestDay(pQuest,true))
12122 return false;
12124 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12125 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12126 return false;
12128 // prevent receive reward with quest items in bank
12129 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12131 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12133 if( pQuest->ReqItemCount[i]!= 0 &&
12134 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12136 if(msg)
12137 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12138 return false;
12143 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12144 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12145 return false;
12147 return true;
12150 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12152 // prevent receive reward with quest items in bank or for not completed quest
12153 if(!CanRewardQuest(pQuest,msg))
12154 return false;
12156 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12158 if( pQuest->RewChoiceItemId[reward] )
12160 ItemPosCountVec dest;
12161 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12162 if( res != EQUIP_ERR_OK )
12164 SendEquipError( res, NULL, NULL );
12165 return false;
12170 if ( pQuest->GetRewItemsCount() > 0 )
12172 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12174 if( pQuest->RewItemId[i] )
12176 ItemPosCountVec dest;
12177 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12178 if( res != EQUIP_ERR_OK )
12180 SendEquipError( res, NULL, NULL );
12181 return false;
12187 return true;
12190 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12192 uint16 log_slot = FindQuestSlot( 0 );
12193 assert(log_slot < MAX_QUEST_LOG_SIZE);
12195 uint32 quest_id = pQuest->GetQuestId();
12197 // if not exist then created with set uState==NEW and rewarded=false
12198 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12200 // check for repeatable quests status reset
12201 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12202 questStatusData.m_explored = false;
12204 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12206 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12207 questStatusData.m_itemcount[i] = 0;
12210 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12212 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12213 questStatusData.m_creatureOrGOcount[i] = 0;
12216 GiveQuestSourceItem( pQuest );
12217 AdjustQuestReqItemCount( pQuest, questStatusData );
12219 if( pQuest->GetRepObjectiveFaction() )
12220 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12221 GetReputationMgr().SetVisible(factionEntry);
12223 uint32 qtime = 0;
12224 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12226 uint32 limittime = pQuest->GetLimitTime();
12228 // shared timed quest
12229 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12230 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12232 AddTimedQuest( quest_id );
12233 questStatusData.m_timer = limittime * IN_MILISECONDS;
12234 qtime = static_cast<uint32>(time(NULL)) + limittime;
12236 else
12237 questStatusData.m_timer = 0;
12239 SetQuestSlot(log_slot, quest_id, qtime);
12241 if (questStatusData.uState != QUEST_NEW)
12242 questStatusData.uState = QUEST_CHANGED;
12244 //starting initial quest script
12245 if(questGiver && pQuest->GetQuestStartScript()!=0)
12246 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12248 // Some spells applied at quest activation
12249 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12250 if(saBounds.first != saBounds.second)
12252 uint32 zone, area;
12253 GetZoneAndAreaId(zone,area);
12255 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12256 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12257 if( !HasAura(itr->second->spellId,0) )
12258 CastSpell(this,itr->second->spellId,true);
12261 UpdateForQuestWorldObjects();
12264 void Player::CompleteQuest( uint32 quest_id )
12266 if( quest_id )
12268 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12270 uint16 log_slot = FindQuestSlot( quest_id );
12271 if( log_slot < MAX_QUEST_LOG_SIZE)
12272 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12274 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12276 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12277 RewardQuest(qInfo,0,this,false);
12278 else
12279 SendQuestComplete( quest_id );
12284 void Player::IncompleteQuest( uint32 quest_id )
12286 if( quest_id )
12288 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12290 uint16 log_slot = FindQuestSlot( quest_id );
12291 if( log_slot < MAX_QUEST_LOG_SIZE)
12292 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12296 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12298 uint32 quest_id = pQuest->GetQuestId();
12300 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i )
12302 if ( pQuest->ReqItemId[i] )
12303 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12306 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12307 // SetTimedQuest( 0 );
12308 m_timedquests.erase(pQuest->GetQuestId());
12310 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12312 if( pQuest->RewChoiceItemId[reward] )
12314 ItemPosCountVec dest;
12315 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12317 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12318 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12323 if ( pQuest->GetRewItemsCount() > 0 )
12325 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12327 if( pQuest->RewItemId[i] )
12329 ItemPosCountVec dest;
12330 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12332 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12333 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12339 RewardReputation( pQuest );
12341 if( pQuest->GetRewSpellCast() > 0 )
12342 CastSpell( this, pQuest->GetRewSpellCast(), true);
12343 else if( pQuest->GetRewSpell() > 0)
12344 CastSpell( this, pQuest->GetRewSpell(), true);
12346 uint16 log_slot = FindQuestSlot( quest_id );
12347 if( log_slot < MAX_QUEST_LOG_SIZE)
12348 SetQuestSlot(log_slot,0);
12350 QuestStatusData& q_status = mQuestStatus[quest_id];
12352 // Not give XP in case already completed once repeatable quest
12353 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12355 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12356 GiveXP( XP , NULL );
12357 else
12359 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12360 ModifyMoney( money );
12361 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12364 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12365 if(pQuest->GetRewOrReqMoney())
12367 ModifyMoney( pQuest->GetRewOrReqMoney() );
12369 if(pQuest->GetRewOrReqMoney() > 0)
12370 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12373 // honor reward
12374 if(pQuest->GetRewHonorableKills())
12375 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12377 // title reward
12378 if(pQuest->GetCharTitleId())
12380 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12381 SetTitle(titleEntry);
12384 if(pQuest->GetBonusTalents())
12386 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12387 InitTalentForLevel();
12390 // Send reward mail
12391 if(pQuest->GetRewMailTemplateId())
12393 MailMessageType mailType;
12394 uint32 senderGuidOrEntry;
12395 switch(questGiver->GetTypeId())
12397 case TYPEID_UNIT:
12398 mailType = MAIL_CREATURE;
12399 senderGuidOrEntry = questGiver->GetEntry();
12400 break;
12401 case TYPEID_GAMEOBJECT:
12402 mailType = MAIL_GAMEOBJECT;
12403 senderGuidOrEntry = questGiver->GetEntry();
12404 break;
12405 case TYPEID_ITEM:
12406 mailType = MAIL_ITEM;
12407 senderGuidOrEntry = questGiver->GetEntry();
12408 break;
12409 case TYPEID_PLAYER:
12410 mailType = MAIL_NORMAL;
12411 senderGuidOrEntry = questGiver->GetGUIDLow();
12412 break;
12413 default:
12414 mailType = MAIL_NORMAL;
12415 senderGuidOrEntry = GetGUIDLow();
12416 break;
12419 Loot questMailLoot;
12421 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12423 // fill mail
12424 MailItemsInfo mi; // item list preparing
12426 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12427 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12429 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12431 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12433 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12434 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12439 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12442 if(pQuest->IsDaily())
12444 SetDailyQuestStatus(quest_id);
12445 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12448 if ( !pQuest->IsRepeatable() )
12449 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12450 else
12451 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12453 q_status.m_rewarded = true;
12455 if(announce)
12456 SendQuestReward( pQuest, XP, questGiver );
12458 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12459 if (pQuest->GetZoneOrSort() > 0)
12460 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12461 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12462 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
12464 uint32 zone = 0;
12465 uint32 area = 0;
12467 // remove auras from spells with quest reward state limitations
12468 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12469 if(saEndBounds.first != saEndBounds.second)
12471 GetZoneAndAreaId(zone,area);
12473 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12474 if(!itr->second->IsFitToRequirements(this,zone,area))
12475 RemoveAurasDueToSpell(itr->second->spellId);
12478 // Some spells applied at quest reward
12479 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12480 if(saBounds.first != saBounds.second)
12482 if(!zone || !area)
12483 GetZoneAndAreaId(zone,area);
12485 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12486 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12487 if( !HasAura(itr->second->spellId,0) )
12488 CastSpell(this,itr->second->spellId,true);
12492 void Player::FailQuest( uint32 quest_id )
12494 if( quest_id )
12496 IncompleteQuest( quest_id );
12498 uint16 log_slot = FindQuestSlot( quest_id );
12499 if( log_slot < MAX_QUEST_LOG_SIZE)
12501 SetQuestSlotTimer(log_slot, 1 );
12502 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12504 SendQuestFailed( quest_id );
12508 void Player::FailTimedQuest( uint32 quest_id )
12510 if( quest_id )
12512 QuestStatusData& q_status = mQuestStatus[quest_id];
12514 q_status.m_timer = 0;
12515 if (q_status.uState != QUEST_NEW)
12516 q_status.uState = QUEST_CHANGED;
12518 IncompleteQuest( quest_id );
12520 uint16 log_slot = FindQuestSlot( quest_id );
12521 if( log_slot < MAX_QUEST_LOG_SIZE)
12523 SetQuestSlotTimer(log_slot, 1 );
12524 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12526 SendQuestTimerFailed( quest_id );
12530 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12532 int32 zoneOrSort = qInfo->GetZoneOrSort();
12533 int32 skillOrClass = qInfo->GetSkillOrClass();
12535 // skip zone zoneOrSort and 0 case skillOrClass
12536 if( zoneOrSort >= 0 && skillOrClass == 0 )
12537 return true;
12539 int32 questSort = -zoneOrSort;
12540 uint8 reqSortClass = ClassByQuestSort(questSort);
12542 // check class sort cases in zoneOrSort
12543 if( reqSortClass != 0 && getClass() != reqSortClass)
12545 if( msg )
12546 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12547 return false;
12550 // check class
12551 if( skillOrClass < 0 )
12553 uint8 reqClass = -int32(skillOrClass);
12554 if(getClass() != reqClass)
12556 if( msg )
12557 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12558 return false;
12561 // check skill
12562 else if( skillOrClass > 0 )
12564 uint32 reqSkill = skillOrClass;
12565 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12567 if( msg )
12568 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12569 return false;
12573 return true;
12576 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12578 if( getLevel() < qInfo->GetMinLevel() )
12580 if( msg )
12581 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12582 return false;
12584 return true;
12587 bool Player::SatisfyQuestLog( bool msg )
12589 // exist free slot
12590 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12591 return true;
12593 if( msg )
12595 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12596 GetSession()->SendPacket( &data );
12597 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12599 return false;
12602 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12604 // No previous quest (might be first quest in a series)
12605 if( qInfo->prevQuests.empty())
12606 return true;
12608 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12610 uint32 prevId = abs(*iter);
12612 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12613 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12615 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12617 // If any of the positive previous quests completed, return true
12618 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12620 // skip one-from-all exclusive group
12621 if(qPrevInfo->GetExclusiveGroup() >= 0)
12622 return true;
12624 // each-from-all exclusive group ( < 0)
12625 // can be start if only all quests in prev quest exclusive group completed and rewarded
12626 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12627 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12629 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12631 for(; iter2 != end; ++iter2)
12633 uint32 exclude_Id = iter2->second;
12635 // skip checked quest id, only state of other quests in group is interesting
12636 if(exclude_Id == prevId)
12637 continue;
12639 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12641 // alternative quest from group also must be completed and rewarded(reported)
12642 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12644 if( msg )
12645 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12646 return false;
12649 return true;
12651 // If any of the negative previous quests active, return true
12652 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12653 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12655 // skip one-from-all exclusive group
12656 if(qPrevInfo->GetExclusiveGroup() >= 0)
12657 return true;
12659 // each-from-all exclusive group ( < 0)
12660 // can be start if only all quests in prev quest exclusive group active
12661 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12662 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12664 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12666 for(; iter2 != end; ++iter2)
12668 uint32 exclude_Id = iter2->second;
12670 // skip checked quest id, only state of other quests in group is interesting
12671 if(exclude_Id == prevId)
12672 continue;
12674 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12676 // alternative quest from group also must be active
12677 if( i_exstatus == mQuestStatus.end() ||
12678 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12679 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12681 if( msg )
12682 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12683 return false;
12686 return true;
12691 // Has only positive prev. quests in non-rewarded state
12692 // and negative prev. quests in non-active state
12693 if( msg )
12694 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12696 return false;
12699 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12701 uint32 reqraces = qInfo->GetRequiredRaces();
12702 if ( reqraces == 0 )
12703 return true;
12704 if( (reqraces & getRaceMask()) == 0 )
12706 if( msg )
12707 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12708 return false;
12710 return true;
12713 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12715 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12716 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12718 if( msg )
12719 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12720 return false;
12723 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12724 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12726 if( msg )
12727 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12728 return false;
12731 return true;
12734 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12736 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12737 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12739 if( msg )
12740 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12741 return false;
12743 return true;
12746 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12748 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12750 if( msg )
12751 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12752 return false;
12754 return true;
12757 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12759 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12760 if(qInfo->GetExclusiveGroup() <= 0)
12761 return true;
12763 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12764 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12766 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12768 for(; iter != end; ++iter)
12770 uint32 exclude_Id = iter->second;
12772 // skip checked quest id, only state of other quests in group is interesting
12773 if(exclude_Id == qInfo->GetQuestId())
12774 continue;
12776 // not allow have daily quest if daily quest from exclusive group already recently completed
12777 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12778 if( !SatisfyQuestDay(Nquest, false) )
12780 if( msg )
12781 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12782 return false;
12785 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12787 // alternative quest already started or completed
12788 if( i_exstatus != mQuestStatus.end()
12789 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12791 if( msg )
12792 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12793 return false;
12796 return true;
12799 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12801 if(!qInfo->GetNextQuestInChain())
12802 return true;
12804 // next quest in chain already started or completed
12805 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12806 if( itr != mQuestStatus.end()
12807 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12809 if( msg )
12810 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12811 return false;
12814 // check for all quests further up the chain
12815 // only necessary if there are quest chains with more than one quest that can be skipped
12816 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12817 return true;
12820 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12822 // No previous quest in chain
12823 if( qInfo->prevChainQuests.empty())
12824 return true;
12826 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12828 uint32 prevId = *iter;
12830 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12832 if( i_prevstatus != mQuestStatus.end() )
12834 // If any of the previous quests in chain active, return false
12835 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12836 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12838 if( msg )
12839 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12840 return false;
12844 // check for all quests further down the chain
12845 // only necessary if there are quest chains with more than one quest that can be skipped
12846 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12847 // return false;
12850 // No previous quest in chain active
12851 return true;
12854 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12856 if(!qInfo->IsDaily())
12857 return true;
12859 bool have_slot = false;
12860 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12862 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12863 if(qInfo->GetQuestId()==id)
12864 return false;
12866 if(!id)
12867 have_slot = true;
12870 if(!have_slot)
12872 if( msg )
12873 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12874 return false;
12877 return true;
12880 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12882 uint32 srcitem = pQuest->GetSrcItemId();
12883 if( srcitem > 0 )
12885 uint32 count = pQuest->GetSrcItemCount();
12886 if( count <= 0 )
12887 count = 1;
12889 ItemPosCountVec dest;
12890 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12891 if( msg == EQUIP_ERR_OK )
12893 Item * item = StoreNewItem(dest, srcitem, true);
12894 SendNewItem(item, count, true, false);
12895 return true;
12897 // player already have max amount required item, just report success
12898 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12899 return true;
12900 else
12901 SendEquipError( msg, NULL, NULL );
12902 return false;
12905 return true;
12908 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12910 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12911 if( qInfo )
12913 uint32 srcitem = qInfo->GetSrcItemId();
12914 if( srcitem > 0 )
12916 uint32 count = qInfo->GetSrcItemCount();
12917 if( count <= 0 )
12918 count = 1;
12920 // exist one case when destroy source quest item not possible:
12921 // non un-equippable item (equipped non-empty bag, for example)
12922 uint8 res = CanUnequipItems(srcitem,count);
12923 if(res != EQUIP_ERR_OK)
12925 if(msg)
12926 SendEquipError( res, NULL, NULL );
12927 return false;
12930 DestroyItemCount(srcitem, count, true, true);
12933 return true;
12936 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12938 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12939 if( qInfo )
12941 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12942 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12943 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12944 && !qInfo->IsRepeatable() )
12945 return itr->second.m_rewarded;
12947 return false;
12949 return false;
12952 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
12954 if( quest_id )
12956 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12957 if( itr != mQuestStatus.end() )
12958 return itr->second.m_status;
12960 return QUEST_STATUS_NONE;
12963 bool Player::CanShareQuest(uint32 quest_id) const
12965 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12966 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
12968 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12969 if( itr != mQuestStatus.end() )
12970 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
12972 return false;
12975 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
12977 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12978 if( qInfo )
12980 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
12982 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12983 m_timedquests.erase(qInfo->GetQuestId());
12986 QuestStatusData& q_status = mQuestStatus[quest_id];
12988 q_status.m_status = status;
12989 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12992 UpdateForQuestWorldObjects();
12995 // not used in MaNGOS, but used in scripting code
12996 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
12998 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12999 if( !qInfo )
13000 return 0;
13002 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13003 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13004 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13006 return 0;
13009 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13011 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13013 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13015 uint32 reqitemcount = pQuest->ReqItemCount[i];
13016 if( reqitemcount != 0 )
13018 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13020 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13021 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13027 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13029 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13030 if ( GetQuestSlotQuestId(i) == quest_id )
13031 return i;
13033 return MAX_QUEST_LOG_SIZE;
13036 void Player::AreaExploredOrEventHappens( uint32 questId )
13038 if( questId )
13040 uint16 log_slot = FindQuestSlot( questId );
13041 if( log_slot < MAX_QUEST_LOG_SIZE)
13043 QuestStatusData& q_status = mQuestStatus[questId];
13045 if(!q_status.m_explored)
13047 q_status.m_explored = true;
13048 if (q_status.uState != QUEST_NEW)
13049 q_status.uState = QUEST_CHANGED;
13052 if( CanCompleteQuest( questId ) )
13053 CompleteQuest( questId );
13057 //not used in mangosd, function for external script library
13058 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13060 if( Group *pGroup = GetGroup() )
13062 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13064 Player *pGroupGuy = itr->getSource();
13066 // for any leave or dead (with not released body) group member at appropriate distance
13067 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13068 pGroupGuy->AreaExploredOrEventHappens(questId);
13071 else
13072 AreaExploredOrEventHappens(questId);
13075 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13077 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13079 uint32 questid = GetQuestSlotQuestId(i);
13080 if ( questid == 0 )
13081 continue;
13083 QuestStatusData& q_status = mQuestStatus[questid];
13085 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13086 continue;
13088 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13089 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13090 continue;
13092 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13094 uint32 reqitem = qInfo->ReqItemId[j];
13095 if ( reqitem == entry )
13097 uint32 reqitemcount = qInfo->ReqItemCount[j];
13098 uint32 curitemcount = q_status.m_itemcount[j];
13099 if ( curitemcount < reqitemcount )
13101 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13102 q_status.m_itemcount[j] += additemcount;
13103 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13105 SendQuestUpdateAddItem( qInfo, j, additemcount );
13107 if ( CanCompleteQuest( questid ) )
13108 CompleteQuest( questid );
13109 return;
13113 UpdateForQuestWorldObjects();
13116 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13118 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13120 uint32 questid = GetQuestSlotQuestId(i);
13121 if(!questid)
13122 continue;
13123 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13124 if ( !qInfo )
13125 continue;
13126 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13127 continue;
13129 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13131 uint32 reqitem = qInfo->ReqItemId[j];
13132 if ( reqitem == entry )
13134 QuestStatusData& q_status = mQuestStatus[questid];
13136 uint32 reqitemcount = qInfo->ReqItemCount[j];
13137 uint32 curitemcount;
13138 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13139 curitemcount = q_status.m_itemcount[j];
13140 else
13141 curitemcount = GetItemCount(entry,true);
13142 if ( curitemcount < reqitemcount + count )
13144 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13145 q_status.m_itemcount[j] = curitemcount - remitemcount;
13146 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13148 IncompleteQuest( questid );
13150 return;
13154 UpdateForQuestWorldObjects();
13157 void Player::KilledMonster( uint32 entry, uint64 guid )
13159 uint32 addkillcount = 1;
13160 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13161 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13163 uint32 questid = GetQuestSlotQuestId(i);
13164 if(!questid)
13165 continue;
13167 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13168 if( !qInfo )
13169 continue;
13170 // just if !ingroup || !noraidgroup || raidgroup
13171 QuestStatusData& q_status = mQuestStatus[questid];
13172 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13174 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13176 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13178 // skip GO activate objective or none
13179 if(qInfo->ReqCreatureOrGOId[j] <=0)
13180 continue;
13182 // skip Cast at creature objective
13183 if(qInfo->ReqSpell[j] !=0 )
13184 continue;
13186 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13188 if ( reqkill == entry )
13190 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13191 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13192 if ( curkillcount < reqkillcount )
13194 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13195 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13197 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13199 if ( CanCompleteQuest( questid ) )
13200 CompleteQuest( questid );
13202 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13203 continue;
13211 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13213 bool isCreature = IS_CREATURE_GUID(guid);
13215 uint32 addCastCount = 1;
13216 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13218 uint32 questid = GetQuestSlotQuestId(i);
13219 if(!questid)
13220 continue;
13222 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13223 if ( !qInfo )
13224 continue;
13226 QuestStatusData& q_status = mQuestStatus[questid];
13228 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13230 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13232 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13234 // skip kill creature objective (0) or wrong spell casts
13235 if(qInfo->ReqSpell[j] != spell_id )
13236 continue;
13238 uint32 reqTarget = 0;
13240 if(isCreature)
13242 // creature activate objectives
13243 if(qInfo->ReqCreatureOrGOId[j] > 0)
13244 // checked at quest_template loading
13245 reqTarget = qInfo->ReqCreatureOrGOId[j];
13247 else
13249 // GO activate objective
13250 if(qInfo->ReqCreatureOrGOId[j] < 0)
13251 // checked at quest_template loading
13252 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13255 // other not this creature/GO related objectives
13256 if( reqTarget != entry )
13257 continue;
13259 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13260 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13261 if ( curCastCount < reqCastCount )
13263 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13264 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13266 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13269 if ( CanCompleteQuest( questid ) )
13270 CompleteQuest( questid );
13272 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13273 break;
13280 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13282 uint32 addTalkCount = 1;
13283 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13285 uint32 questid = GetQuestSlotQuestId(i);
13286 if(!questid)
13287 continue;
13289 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13290 if ( !qInfo )
13291 continue;
13293 QuestStatusData& q_status = mQuestStatus[questid];
13295 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13297 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13299 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13301 // skip spell casts and Gameobject objectives
13302 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13303 continue;
13305 uint32 reqTarget = 0;
13307 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13308 // checked at quest_template loading
13309 reqTarget = qInfo->ReqCreatureOrGOId[j];
13310 else
13311 continue;
13313 if ( reqTarget == entry )
13315 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13316 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13317 if ( curTalkCount < reqTalkCount )
13319 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13320 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13322 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13324 if ( CanCompleteQuest( questid ) )
13325 CompleteQuest( questid );
13327 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13328 continue;
13336 void Player::MoneyChanged( uint32 count )
13338 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13340 uint32 questid = GetQuestSlotQuestId(i);
13341 if (!questid)
13342 continue;
13344 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13345 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13347 QuestStatusData& q_status = mQuestStatus[questid];
13349 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13351 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13353 if ( CanCompleteQuest( questid ) )
13354 CompleteQuest( questid );
13357 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13359 if(int32(count) < -qInfo->GetRewOrReqMoney())
13360 IncompleteQuest( questid );
13366 void Player::ReputationChanged(FactionEntry const* factionEntry )
13368 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13370 if(uint32 questid = GetQuestSlotQuestId(i))
13372 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13374 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13376 QuestStatusData& q_status = mQuestStatus[questid];
13377 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13379 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13380 if ( CanCompleteQuest( questid ) )
13381 CompleteQuest( questid );
13383 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13385 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13386 IncompleteQuest( questid );
13394 bool Player::HasQuestForItem( uint32 itemid ) const
13396 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13398 uint32 questid = GetQuestSlotQuestId(i);
13399 if ( questid == 0 )
13400 continue;
13402 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13403 if(qs_itr == mQuestStatus.end())
13404 continue;
13406 QuestStatusData const& q_status = qs_itr->second;
13408 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13410 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13411 if(!qinfo)
13412 continue;
13414 // hide quest if player is in raid-group and quest is no raid quest
13415 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13416 continue;
13418 // There should be no mixed ReqItem/ReqSource drop
13419 // This part for ReqItem drop
13420 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13422 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13423 return true;
13425 // This part - for ReqSource
13426 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
13428 // examined item is a source item
13429 if (qinfo->ReqSourceId[j] == itemid)
13431 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13433 // 'unique' item
13434 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13435 return true;
13437 // allows custom amount drop when not 0
13438 if (qinfo->ReqSourceCount[j])
13440 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13441 return true;
13442 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13443 return true;
13448 return false;
13451 void Player::SendQuestComplete( uint32 quest_id )
13453 if( quest_id )
13455 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13456 data << uint32(quest_id);
13457 GetSession()->SendPacket( &data );
13458 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13462 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13464 uint32 questid = pQuest->GetQuestId();
13465 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13466 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13467 data << uint32(questid);
13469 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13471 data << uint32(XP);
13472 data << uint32(pQuest->GetRewOrReqMoney());
13474 else
13476 data << uint32(0);
13477 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13480 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13481 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13482 GetSession()->SendPacket( &data );
13484 if (pQuest->GetQuestCompleteScript() != 0)
13485 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13488 void Player::SendQuestFailed( uint32 quest_id )
13490 if( quest_id )
13492 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13493 data << quest_id;
13494 data << uint32(0); // failed reason (4 for inventory is full)
13495 GetSession()->SendPacket( &data );
13496 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13500 void Player::SendQuestTimerFailed( uint32 quest_id )
13502 if( quest_id )
13504 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13505 data << quest_id;
13506 GetSession()->SendPacket( &data );
13507 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13511 void Player::SendCanTakeQuestResponse( uint32 msg )
13513 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13514 data << uint32(msg);
13515 GetSession()->SendPacket( &data );
13516 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13519 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13521 if( pPlayer )
13523 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13524 data << uint64(pPlayer->GetGUID());
13525 data << uint8(msg); // valid values: 0-8
13526 GetSession()->SendPacket( &data );
13527 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13531 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13533 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13534 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13535 //data << pQuest->ReqItemId[item_idx];
13536 //data << count;
13537 GetSession()->SendPacket( &data );
13540 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13542 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13544 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13545 if (entry < 0)
13546 // client expected gameobject template id in form (id|0x80000000)
13547 entry = (-entry) | 0x80000000;
13549 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13550 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13551 data << uint32(pQuest->GetQuestId());
13552 data << uint32(entry);
13553 data << uint32(old_count + add_count);
13554 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13555 data << uint64(guid);
13556 GetSession()->SendPacket(&data);
13558 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13559 if( log_slot < MAX_QUEST_LOG_SIZE)
13560 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13563 /*********************************************************/
13564 /*** LOAD SYSTEM ***/
13565 /*********************************************************/
13567 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13569 bool delete_result = true;
13570 if(!result)
13572 // 0 1 2 3 4 5 6 7 8 9
13573 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13574 if(!result) return false;
13576 else delete_result = false;
13578 Field *fields = result->Fetch();
13580 if(!LoadValues( fields[1].GetString()))
13582 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13583 if(delete_result) delete result;
13584 return false;
13587 // overwrite possible wrong/corrupted guid
13588 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13590 m_name = fields[2].GetCppString();
13592 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13593 SetMapId(fields[6].GetUInt32());
13594 // the instance id is not needed at character enum
13596 m_Played_time[0] = fields[7].GetUInt32();
13597 m_Played_time[1] = fields[8].GetUInt32();
13599 m_atLoginFlags = fields[9].GetUInt32();
13601 // I don't see these used anywhere ..
13602 /*_LoadGroup();
13604 _LoadBoundInstances();*/
13606 if (delete_result) delete result;
13608 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
13609 m_items[i] = NULL;
13611 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13612 m_deathState = DEAD;
13614 return true;
13617 void Player::_LoadDeclinedNames(QueryResult* result)
13619 if(!result)
13620 return;
13622 if(m_declinedname)
13623 delete m_declinedname;
13625 m_declinedname = new DeclinedName;
13626 Field *fields = result->Fetch();
13627 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13628 m_declinedname->name[i] = fields[i].GetCppString();
13630 delete result;
13633 void Player::_LoadArenaTeamInfo(QueryResult *result)
13635 // arenateamid, played_week, played_season, personal_rating
13636 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13637 if (!result)
13638 return;
13642 Field *fields = result->Fetch();
13644 uint32 arenateamid = fields[0].GetUInt32();
13645 uint32 played_week = fields[1].GetUInt32();
13646 uint32 played_season = fields[2].GetUInt32();
13647 uint32 personal_rating = fields[3].GetUInt32();
13649 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13650 if(!aTeam)
13652 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13653 continue;
13655 uint8 arenaSlot = aTeam->GetSlot();
13657 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13658 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13659 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13660 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13661 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13662 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13664 }while (result->NextRow());
13665 delete result;
13668 void Player::_LoadEquipmentSets(QueryResult *result)
13670 // 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));
13671 if (!result)
13672 return;
13674 uint32 count = 0;
13677 Field *fields = result->Fetch();
13679 EquipmentSet eqSet;
13681 eqSet.Guid = fields[0].GetUInt64();
13682 uint32 index = fields[1].GetUInt32();
13683 eqSet.Name = fields[2].GetCppString();
13684 eqSet.IconName = fields[3].GetCppString();
13685 eqSet.state = EQUIPMENT_SET_UNCHANGED;
13687 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
13688 eqSet.Items[i] = fields[4+i].GetUInt32();
13690 m_EquipmentSets[index] = eqSet;
13692 ++count;
13694 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
13695 break;
13696 } while (result->NextRow());
13697 delete result;
13700 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13702 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13703 if(!result)
13704 return false;
13706 Field *fields = result->Fetch();
13708 x = fields[0].GetFloat();
13709 y = fields[1].GetFloat();
13710 z = fields[2].GetFloat();
13711 o = fields[3].GetFloat();
13712 mapid = fields[4].GetUInt32();
13713 in_flight = !fields[5].GetCppString().empty();
13715 delete result;
13716 return true;
13719 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13721 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13722 if( !result )
13723 return false;
13725 Field *fields = result->Fetch();
13727 data = StrSplit(fields[0].GetCppString(), " ");
13729 delete result;
13731 return true;
13734 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13736 if(index >= data.size())
13737 return 0;
13739 return (uint32)atoi(data[index].c_str());
13742 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13744 float result;
13745 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13746 memcpy(&result, &temp, sizeof(result));
13748 return result;
13751 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13753 Tokens data;
13754 if(!LoadValuesArrayFromDB(data,guid))
13755 return 0;
13757 return GetUInt32ValueFromArray(data,index);
13760 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13762 float result;
13763 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13764 memcpy(&result, &temp, sizeof(result));
13766 return result;
13769 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13771 //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [28] [29] 30 31 32 33 34 35 36 37 38 39 40
13772 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points,bgid,bgteam,bgmap,bgx,bgy,bgz,bgo FROM characters WHERE guid = '%u'", guid);
13773 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13775 if(!result)
13777 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13778 return false;
13781 Field *fields = result->Fetch();
13783 uint32 dbAccountId = fields[1].GetUInt32();
13785 // check if the character's account in the db and the logged in account match.
13786 // player should be able to load/delete character only with correct account!
13787 if( dbAccountId != GetSession()->GetAccountId() )
13789 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13790 delete result;
13791 return false;
13794 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13796 m_name = fields[3].GetCppString();
13798 // check name limitations
13799 if(!ObjectMgr::IsValidName(m_name) || (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name)))
13801 delete result;
13802 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13803 return false;
13806 if(!LoadValues( fields[2].GetString()))
13808 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
13809 delete result;
13810 return false;
13813 // overwrite possible wrong/corrupted guid
13814 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13816 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13817 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13819 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
13820 SetVisibleItemSlot(slot, NULL);
13822 if (m_items[slot])
13824 delete m_items[slot];
13825 m_items[slot] = NULL;
13829 // update money limits
13830 if(GetMoney() > MAX_MONEY_AMOUNT)
13831 SetMoney(MAX_MONEY_AMOUNT);
13833 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13834 outDebugValues();
13836 m_race = fields[4].GetUInt8();
13837 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13838 //Other way is to saves m_team into characters table.
13839 setFactionForRace(m_race);
13840 SetCharm(NULL);
13842 m_class = fields[5].GetUInt8();
13844 // load home bind and check in same time class/race pair, it used later for restore broken positions
13845 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13846 return false;
13848 InitPrimaryProffesions(); // to max set before any spell loaded
13850 // init saved position, and fix it later if problematic
13851 uint32 transGUID = fields[24].GetUInt32();
13852 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13853 SetMapId(fields[9].GetUInt32());
13854 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13856 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13858 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
13860 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
13861 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
13862 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
13864 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
13866 // check arena teams integrity
13867 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13869 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13870 if(!arena_team_id)
13871 continue;
13873 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13874 if(at->HaveMember(GetGUID()))
13875 continue;
13877 // arena team not exist or not member, cleanup fields
13878 for(int j =0; j < 6; ++j)
13879 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13882 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13884 if(!IsPositionValid())
13886 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());
13887 RelocateToHomebind();
13889 transGUID = 0;
13891 m_movementInfo.t_x = 0.0f;
13892 m_movementInfo.t_y = 0.0f;
13893 m_movementInfo.t_z = 0.0f;
13894 m_movementInfo.t_o = 0.0f;
13897 uint32 bgid = fields[34].GetUInt32();
13898 uint32 bgteam = fields[35].GetUInt32();
13900 if(bgid) //saved in BattleGround
13902 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
13904 // check entry point and fix to homebind if need
13905 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
13906 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
13907 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
13909 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid, BATTLEGROUND_TYPE_NONE);
13911 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
13913 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
13914 AddBattleGroundQueueId(bgQueueTypeId);
13916 SetBattleGroundId(currentBg->GetInstanceID(), currentBg->GetTypeID());
13917 SetBGTeam(bgteam);
13919 //join player to battleground group
13920 currentBg->EventPlayerLoggedIn(this, GetGUID());
13921 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
13923 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
13925 else
13927 Relocate(GetBattleGroundEntryPoint());
13928 //RemoveArenaAuras(true);
13931 else
13933 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
13934 // if server restart after player save in BG or area
13935 // player can have current coordinates in to BG/Arean map, fix this
13936 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
13938 // return to BG master
13939 SetMapId(fields[36].GetUInt32());
13940 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
13942 // check entry point and fix to homebind if need
13943 mapEntry = sMapStore.LookupEntry(GetMapId());
13944 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
13945 RelocateToHomebind();
13949 if (transGUID != 0)
13951 m_movementInfo.t_x = fields[20].GetFloat();
13952 m_movementInfo.t_y = fields[21].GetFloat();
13953 m_movementInfo.t_z = fields[22].GetFloat();
13954 m_movementInfo.t_o = fields[23].GetFloat();
13956 if( !MaNGOS::IsValidMapCoord(
13957 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13958 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13959 // transport size limited
13960 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13962 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13963 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13964 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13966 RelocateToHomebind();
13968 m_movementInfo.t_x = 0.0f;
13969 m_movementInfo.t_y = 0.0f;
13970 m_movementInfo.t_z = 0.0f;
13971 m_movementInfo.t_o = 0.0f;
13973 transGUID = 0;
13977 if (transGUID != 0)
13979 for (MapManager::TransportSet::const_iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13981 if( (*iter)->GetGUIDLow() == transGUID)
13983 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
13984 // client without expansion support
13985 if(GetSession()->Expansion() < transMapEntry->Expansion())
13987 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
13988 break;
13991 m_transport = *iter;
13992 m_transport->AddPassenger(this);
13993 SetMapId(m_transport->GetMapId());
13994 break;
13998 if(!m_transport)
14000 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14001 guid,transGUID);
14003 RelocateToHomebind();
14005 m_movementInfo.t_x = 0.0f;
14006 m_movementInfo.t_y = 0.0f;
14007 m_movementInfo.t_z = 0.0f;
14008 m_movementInfo.t_o = 0.0f;
14010 transGUID = 0;
14013 else // not transport case
14015 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14016 // client without expansion support
14017 if(GetSession()->Expansion() < mapEntry->Expansion())
14019 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14020 RelocateToHomebind();
14024 // NOW player must have valid map
14025 // load the player's map here if it's not already loaded
14026 Map *map = GetMap();
14028 // since the player may not be bound to the map yet, make sure subsequent
14029 // getmap calls won't create new maps
14030 SetInstanceId(map->GetInstanceId());
14032 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14033 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14035 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14036 if(at)
14037 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14038 else
14039 sLog.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no aretrigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14042 SaveRecallPosition();
14044 time_t now = time(NULL);
14045 time_t logoutTime = time_t(fields[16].GetUInt64());
14047 // since last logout (in seconds)
14048 uint64 time_diff = uint64(now - logoutTime);
14050 // set value, including drunk invisibility detection
14051 // calculate sobering. after 15 minutes logged out, the player will be sober again
14052 float soberFactor;
14053 if(time_diff > 15*MINUTE)
14054 soberFactor = 0;
14055 else
14056 soberFactor = 1-time_diff/(15.0f*MINUTE);
14057 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14058 SetDrunkValue(newDrunkenValue);
14060 m_rest_bonus = fields[15].GetFloat();
14061 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14062 float bubble0 = 0.031;
14063 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14064 float bubble1 = 0.125;
14066 if((int32)fields[16].GetUInt32() > 0)
14068 float bubble = fields[17].GetUInt32() > 0
14069 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14070 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14072 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14075 m_cinematic = fields[12].GetUInt32();
14076 m_Played_time[0]= fields[13].GetUInt32();
14077 m_Played_time[1]= fields[14].GetUInt32();
14079 m_resetTalentsCost = fields[18].GetUInt32();
14080 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14082 // reserve some flags
14083 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14085 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14086 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14088 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14090 uint32 extraflags = fields[25].GetUInt32();
14092 m_stableSlots = fields[26].GetUInt32();
14093 if(m_stableSlots > MAX_PET_STABLES)
14095 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14096 m_stableSlots = MAX_PET_STABLES;
14099 m_atLoginFlags = fields[27].GetUInt32();
14101 // Honor system
14102 // Update Honor kills data
14103 m_lastHonorUpdateTime = logoutTime;
14104 UpdateHonorFields();
14106 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14107 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14108 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14110 std::string taxi_nodes = fields[31].GetCppString();
14112 delete result;
14114 // clear channel spell data (if saved at channel spell casting)
14115 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14116 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14118 // clear charm/summon related fields
14119 SetCharm(NULL);
14120 SetPet(NULL);
14121 SetCharmerGUID(0);
14122 SetOwnerGUID(0);
14123 SetCreatorGUID(0);
14125 // reset some aura modifiers before aura apply
14126 SetFarSightGUID(0);
14127 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14128 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14130 _LoadSkills();
14132 // make sure the unit is considered out of combat for proper loading
14133 ClearInCombat();
14135 // make sure the unit is considered not in duel for proper loading
14136 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14137 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14139 // remember loaded power/health values to restore after stats initialization and modifier applying
14140 uint32 savedHealth = GetHealth();
14141 uint32 savedPower[MAX_POWERS];
14142 for(uint32 i = 0; i < MAX_POWERS; ++i)
14143 savedPower[i] = GetPower(Powers(i));
14145 // reset stats before loading any modifiers
14146 InitStatsForLevel();
14147 InitTaxiNodesForLevel();
14148 InitGlyphsForLevel();
14149 InitRunes();
14151 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14153 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14154 //_LoadMail();
14156 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14157 _LoadGlyphAuras();
14159 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14160 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14161 m_deathState = DEAD;
14163 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14165 // after spell load, learn rewarded spell if need also
14166 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14167 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14169 // after spell and quest load
14170 InitTalentForLevel();
14171 learnDefaultSpells();
14173 // must be before inventory (some items required reputation check)
14174 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14176 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14178 // update items with duration and realtime
14179 UpdateItemDuration(time_diff, true);
14181 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14183 // unread mails and next delivery time, actual mails not loaded
14184 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14186 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14188 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14189 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14190 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14192 if(!HasTitle(curTitle))
14193 SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
14196 // Not finish taxi flight path
14197 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14199 // problems with taxi path loading
14200 TaxiNodesEntry const* nodeEntry = NULL;
14201 if(uint32 node_id = m_taxi.GetTaxiSource())
14202 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14204 if(!nodeEntry) // don't know taxi start node, to homebind
14206 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14207 RelocateToHomebind();
14208 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14210 else // have start node, to it
14212 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14213 SetMapId(nodeEntry->map_id);
14214 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14215 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14217 m_taxi.ClearTaxiDestinations();
14219 else if(uint32 node_id = m_taxi.GetTaxiSource())
14221 // save source node as recall coord to prevent recall and fall from sky
14222 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14223 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14224 m_recallMap = nodeEntry->map_id;
14225 m_recallX = nodeEntry->x;
14226 m_recallY = nodeEntry->y;
14227 m_recallZ = nodeEntry->z;
14229 // flight will started later
14232 // has to be called after last Relocate() in Player::LoadFromDB
14233 SetFallInformation(0, GetPositionZ());
14235 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14237 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14238 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14239 if(!isAlive())
14240 RemoveAllAurasOnDeath();
14242 //apply all stat bonuses from items and auras
14243 SetCanModifyStats(true);
14244 UpdateAllStats();
14246 // restore remembered power/health values (but not more max values)
14247 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14248 for(uint32 i = 0; i < MAX_POWERS; ++i)
14249 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14251 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14252 outDebugValues();
14254 // GM state
14255 if(GetSession()->GetSecurity() > SEC_PLAYER)
14257 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14259 default:
14260 case 0: break; // disable
14261 case 1: SetGameMaster(true); break; // enable
14262 case 2: // save state
14263 if(extraflags & PLAYER_EXTRA_GM_ON)
14264 SetGameMaster(true);
14265 break;
14268 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14270 default:
14271 case 0: SetGMVisible(false); break; // invisible
14272 case 1: break; // visible
14273 case 2: // save state
14274 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14275 SetGMVisible(false);
14276 break;
14279 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14281 default:
14282 case 0: break; // disable
14283 case 1: SetAcceptTicket(true); break; // enable
14284 case 2: // save state
14285 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14286 SetAcceptTicket(true);
14287 break;
14290 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14292 default:
14293 case 0: break; // disable
14294 case 1: SetGMChat(true); break; // enable
14295 case 2: // save state
14296 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14297 SetGMChat(true);
14298 break;
14301 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14303 default:
14304 case 0: break; // disable
14305 case 1: SetAcceptWhispers(true); break; // enable
14306 case 2: // save state
14307 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14308 SetAcceptWhispers(true);
14309 break;
14313 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14315 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14316 m_achievementMgr.CheckAllAchievementCriteria();
14318 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
14320 return true;
14323 bool Player::isAllowedToLoot(Creature* creature)
14325 if(Player* recipient = creature->GetLootRecipient())
14327 if (recipient == this)
14328 return true;
14329 if( Group* otherGroup = recipient->GetGroup())
14331 Group* thisGroup = GetGroup();
14332 if(!thisGroup)
14333 return false;
14334 return thisGroup == otherGroup;
14336 return false;
14338 else
14339 // prevent other players from looting if the recipient got disconnected
14340 return !creature->hasLootRecipient();
14343 void Player::_LoadActions(QueryResult *result)
14345 m_actionButtons.clear();
14347 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14349 if(result)
14353 Field *fields = result->Fetch();
14355 uint8 button = fields[0].GetUInt8();
14357 if(addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8()))
14358 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14359 else
14361 sLog.outError( " ...at loading, and will deleted in DB also");
14363 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14364 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14367 while( result->NextRow() );
14369 delete result;
14373 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14375 m_Auras.clear();
14376 for (int i = 0; i < TOTAL_AURAS; ++i)
14377 m_modAuras[i].clear();
14379 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14381 if(result)
14385 Field *fields = result->Fetch();
14386 uint64 caster_guid = fields[0].GetUInt64();
14387 uint32 spellid = fields[1].GetUInt32();
14388 uint32 effindex = fields[2].GetUInt32();
14389 uint32 stackcount = fields[3].GetUInt32();
14390 int32 damage = (int32)fields[4].GetUInt32();
14391 int32 maxduration = (int32)fields[5].GetUInt32();
14392 int32 remaintime = (int32)fields[6].GetUInt32();
14393 int32 remaincharges = (int32)fields[7].GetUInt32();
14395 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14396 if(!spellproto)
14398 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14399 continue;
14402 if(effindex >= 3)
14404 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14405 continue;
14408 // negative effects should continue counting down after logout
14409 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14411 if(remaintime <= int32(timediff))
14412 continue;
14414 remaintime -= timediff;
14417 // prevent wrong values of remaincharges
14418 if(spellproto->procCharges)
14420 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14421 remaincharges = spellproto->procCharges;
14423 else
14424 remaincharges = 0;
14427 for(uint32 i=0; i<stackcount; ++i)
14429 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14430 if(!damage)
14431 damage = aura->GetModifier()->m_amount;
14433 // reset stolen single target auras
14434 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14435 aura->SetIsSingleTarget(false);
14437 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14438 AddAura(aura);
14439 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14442 while( result->NextRow() );
14444 delete result;
14447 if(m_class == CLASS_WARRIOR)
14448 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14451 void Player::_LoadGlyphAuras()
14453 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14455 if (uint32 glyph = GetGlyph(i))
14457 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14459 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14461 if(gp->TypeFlags == gs->TypeFlags)
14463 CastSpell(this, gp->SpellId, true);
14464 continue;
14466 else
14467 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14469 else
14470 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14472 else
14473 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14475 // On any error remove glyph
14476 SetGlyph(i, 0);
14481 void Player::LoadCorpse()
14483 if( isAlive() )
14485 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14487 else
14489 if(Corpse *corpse = GetCorpse())
14491 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14493 else
14495 //Prevent Dead Player login without corpse
14496 ResurrectPlayer(0.5f);
14501 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14503 //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());
14504 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14505 //NOTE: the "order by `bag`" is important because it makes sure
14506 //the bagMap is filled before items in the bags are loaded
14507 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14508 //expected to be equipped before offhand items (TODO: fixme)
14510 uint32 zone = GetZoneId();
14512 if (result)
14514 std::list<Item*> problematicItems;
14516 // prevent items from being added to the queue when stored
14517 m_itemUpdateQueueBlocked = true;
14520 Field *fields = result->Fetch();
14521 uint32 bag_guid = fields[1].GetUInt32();
14522 uint8 slot = fields[2].GetUInt8();
14523 uint32 item_guid = fields[3].GetUInt32();
14524 uint32 item_id = fields[4].GetUInt32();
14526 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14528 if(!proto)
14530 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14531 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14532 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14533 continue;
14536 Item *item = NewItemOrBag(proto);
14538 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14540 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14541 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14542 item->FSetState(ITEM_REMOVED);
14543 item->SaveToDB(); // it also deletes item object !
14544 continue;
14547 // not allow have in alive state item limited to another map/zone
14548 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14550 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14551 item->FSetState(ITEM_REMOVED);
14552 item->SaveToDB(); // it also deletes item object !
14553 continue;
14556 // "Conjured items disappear if you are logged out for more than 15 minutes"
14557 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14559 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14560 item->FSetState(ITEM_REMOVED);
14561 item->SaveToDB(); // it also deletes item object !
14562 continue;
14565 bool success = true;
14567 if (!bag_guid)
14569 // the item is not in a bag
14570 item->SetContainer( NULL );
14571 item->SetSlot(slot);
14573 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14575 ItemPosCountVec dest;
14576 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14577 item = StoreItem(dest, item, true);
14578 else
14579 success = false;
14581 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14583 uint16 dest;
14584 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14585 QuickEquipItem(dest, item);
14586 else
14587 success = false;
14589 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14591 ItemPosCountVec dest;
14592 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14593 item = BankItem(dest, item, true);
14594 else
14595 success = false;
14598 if(success)
14600 // store bags that may contain items in them
14601 if(item->IsBag() && IsBagPos(item->GetPos()))
14602 bagMap[item_guid] = (Bag*)item;
14605 else
14607 item->SetSlot(NULL_SLOT);
14608 // the item is in a bag, find the bag
14609 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
14610 if(itr != bagMap.end())
14611 itr->second->StoreItem(slot, item, true );
14612 else
14613 success = false;
14616 // item's state may have changed after stored
14617 if (success)
14618 item->SetState(ITEM_UNCHANGED, this);
14619 else
14621 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);
14622 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14623 problematicItems.push_back(item);
14625 } while (result->NextRow());
14627 delete result;
14628 m_itemUpdateQueueBlocked = false;
14630 // send by mail problematic items
14631 while(!problematicItems.empty())
14633 // fill mail
14634 MailItemsInfo mi; // item list preparing
14636 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14638 Item* item = problematicItems.front();
14639 problematicItems.pop_front();
14641 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14644 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14646 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14649 //if(isAlive())
14650 _ApplyAllItemMods();
14653 // load mailed item which should receive current player
14654 void Player::_LoadMailedItems(Mail *mail)
14656 // data needs to be at first place for Item::LoadFromDB
14657 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);
14658 if(!result)
14659 return;
14663 Field *fields = result->Fetch();
14664 uint32 item_guid_low = fields[1].GetUInt32();
14665 uint32 item_template = fields[2].GetUInt32();
14667 mail->AddItem(item_guid_low, item_template);
14669 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14671 if(!proto)
14673 sLog.outError( "Player %u have unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID);
14674 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14675 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14676 continue;
14679 Item *item = NewItemOrBag(proto);
14681 if(!item->LoadFromDB(item_guid_low, 0, result))
14683 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14684 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14685 item->FSetState(ITEM_REMOVED);
14686 item->SaveToDB(); // it also deletes item object !
14687 continue;
14690 AddMItem(item);
14691 } while (result->NextRow());
14693 delete result;
14696 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14698 //set a count of unread mails
14699 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" I64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
14700 if (resultUnread)
14702 Field *fieldMail = resultUnread->Fetch();
14703 unReadMails = fieldMail[0].GetUInt8();
14704 delete resultUnread;
14707 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14708 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14709 if (resultDelivery)
14711 Field *fieldMail = resultDelivery->Fetch();
14712 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14713 delete resultDelivery;
14717 void Player::_LoadMail()
14719 m_mail.clear();
14720 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14721 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());
14722 if(result)
14726 Field *fields = result->Fetch();
14727 Mail *m = new Mail;
14728 m->messageID = fields[0].GetUInt32();
14729 m->messageType = fields[1].GetUInt8();
14730 m->sender = fields[2].GetUInt32();
14731 m->receiver = fields[3].GetUInt32();
14732 m->subject = fields[4].GetCppString();
14733 m->itemTextId = fields[5].GetUInt32();
14734 bool has_items = fields[6].GetBool();
14735 m->expire_time = (time_t)fields[7].GetUInt64();
14736 m->deliver_time = (time_t)fields[8].GetUInt64();
14737 m->money = fields[9].GetUInt32();
14738 m->COD = fields[10].GetUInt32();
14739 m->checked = fields[11].GetUInt32();
14740 m->stationery = fields[12].GetUInt8();
14741 m->mailTemplateId = fields[13].GetInt16();
14743 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14745 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14746 m->mailTemplateId = 0;
14749 m->state = MAIL_STATE_UNCHANGED;
14751 if (has_items)
14752 _LoadMailedItems(m);
14754 m_mail.push_back(m);
14755 } while( result->NextRow() );
14756 delete result;
14758 m_mailsLoaded = true;
14761 void Player::LoadPet()
14763 //fixme: the pet should still be loaded if the player is not in world
14764 // just not added to the map
14765 if(IsInWorld())
14767 Pet *pet = new Pet;
14768 if(!pet->LoadPetFromDB(this,0,0,true))
14769 delete pet;
14773 void Player::_LoadQuestStatus(QueryResult *result)
14775 mQuestStatus.clear();
14777 uint32 slot = 0;
14779 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14780 //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());
14782 if(result)
14786 Field *fields = result->Fetch();
14788 uint32 quest_id = fields[0].GetUInt32();
14789 // used to be new, no delete?
14790 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14791 if( pQuest )
14793 // find or create
14794 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14796 uint32 qstatus = fields[1].GetUInt32();
14797 if(qstatus < MAX_QUEST_STATUS)
14798 questStatusData.m_status = QuestStatus(qstatus);
14799 else
14801 questStatusData.m_status = QUEST_STATUS_NONE;
14802 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14805 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14806 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14808 time_t quest_time = time_t(fields[4].GetUInt64());
14810 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14812 AddTimedQuest( quest_id );
14814 if (quest_time <= sWorld.GetGameTime())
14815 questStatusData.m_timer = 1;
14816 else
14817 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
14819 else
14820 quest_time = 0;
14822 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14823 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14824 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14825 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14826 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14827 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14828 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14829 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14831 questStatusData.uState = QUEST_UNCHANGED;
14833 // add to quest log
14834 if( slot < MAX_QUEST_LOG_SIZE &&
14835 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14836 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
14837 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14839 SetQuestSlot(slot,quest_id,quest_time);
14841 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14842 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14844 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14845 if(questStatusData.m_creatureOrGOcount[idx])
14846 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14848 ++slot;
14851 if(questStatusData.m_rewarded)
14853 // learn rewarded spell if unknown
14854 learnQuestRewardedSpells(pQuest);
14856 // set rewarded title if any
14857 if(pQuest->GetCharTitleId())
14859 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14860 SetTitle(titleEntry);
14863 if(pQuest->GetBonusTalents())
14864 m_questRewardTalentCount+=pQuest->GetBonusTalents();
14867 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14870 while( result->NextRow() );
14872 delete result;
14875 // clear quest log tail
14876 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14877 SetQuestSlot(i,0);
14880 void Player::_LoadDailyQuestStatus(QueryResult *result)
14882 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14883 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14885 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14887 if(result)
14889 uint32 quest_daily_idx = 0;
14893 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14895 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14896 break;
14899 Field *fields = result->Fetch();
14901 uint32 quest_id = fields[0].GetUInt32();
14903 // save _any_ from daily quest times (it must be after last reset anyway)
14904 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14906 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14907 if( !pQuest )
14908 continue;
14910 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14911 ++quest_daily_idx;
14913 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14915 while( result->NextRow() );
14917 delete result;
14920 m_DailyQuestChanged = false;
14923 void Player::_LoadSpells(QueryResult *result)
14925 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14927 if(result)
14931 Field *fields = result->Fetch();
14933 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
14935 while( result->NextRow() );
14937 delete result;
14941 void Player::_LoadGroup(QueryResult *result)
14943 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14944 if(result)
14946 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14947 delete result;
14948 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14949 if(group)
14951 uint8 subgroup = group->GetMemberGroup(GetGUID());
14952 SetGroup(group, subgroup);
14953 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14955 // the group leader may change the instance difficulty while the player is offline
14956 SetDifficulty(group->GetDifficulty());
14962 void Player::_LoadBoundInstances(QueryResult *result)
14964 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
14965 m_boundInstances[i].clear();
14967 Group *group = GetGroup();
14969 //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));
14970 if(result)
14974 Field *fields = result->Fetch();
14975 bool perm = fields[1].GetBool();
14976 uint32 mapId = fields[2].GetUInt32();
14977 uint32 instanceId = fields[0].GetUInt32();
14978 uint8 difficulty = fields[3].GetUInt8();
14979 time_t resetTime = (time_t)fields[4].GetUInt64();
14980 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14981 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14982 // and in that case it is not used
14984 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
14985 if(!mapEntry || !mapEntry->IsDungeon())
14987 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
14988 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14989 continue;
14992 if(!perm && group)
14994 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);
14995 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14996 continue;
14999 // since non permanent binds are always solo bind, they can always be reset
15000 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15001 if(save) BindToInstance(save, perm, true);
15002 } while(result->NextRow());
15003 delete result;
15007 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15009 // some instances only have one difficulty
15010 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15011 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15013 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15014 if(itr != m_boundInstances[difficulty].end())
15015 return &itr->second;
15016 else
15017 return NULL;
15020 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15022 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15023 UnbindInstance(itr, difficulty, unload);
15026 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15028 if(itr != m_boundInstances[difficulty].end())
15030 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15031 itr->second.save->RemovePlayer(this); // save can become invalid
15032 m_boundInstances[difficulty].erase(itr++);
15036 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15038 if(save)
15040 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15041 if(bind.save)
15043 // update the save when the group kills a boss
15044 if(permanent != bind.perm || save != bind.save)
15045 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());
15047 else
15048 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15050 if(bind.save != save)
15052 if(bind.save) bind.save->RemovePlayer(this);
15053 save->AddPlayer(this);
15056 if(permanent) save->SetCanReset(false);
15058 bind.save = save;
15059 bind.perm = permanent;
15060 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());
15061 return &bind;
15063 else
15064 return NULL;
15067 void Player::SendRaidInfo()
15069 uint32 counter = 0;
15071 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15073 size_t p_counter = data.wpos();
15074 data << uint32(counter); // placeholder
15076 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15078 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15080 if(itr->second.perm)
15082 InstanceSave *save = itr->second.save;
15083 data << uint32(save->GetMapId());
15084 data << uint32(save->GetResetTime() - time(NULL));
15085 data << uint32(save->GetInstanceId());
15086 data << uint32(save->GetDifficulty());
15087 ++counter;
15091 data.put<uint32>(p_counter,counter);
15092 GetSession()->SendPacket(&data);
15096 - called on every successful teleportation to a map
15098 void Player::SendSavedInstances()
15100 bool hasBeenSaved = false;
15101 WorldPacket data;
15103 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15105 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15107 if(itr->second.perm) // only permanent binds are sent
15109 hasBeenSaved = true;
15110 break;
15115 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15116 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15117 data << uint32(hasBeenSaved);
15118 GetSession()->SendPacket(&data);
15120 if(!hasBeenSaved)
15121 return;
15123 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15125 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15127 if(itr->second.perm)
15129 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15130 data << uint32(itr->second.save->GetMapId());
15131 GetSession()->SendPacket(&data);
15137 /// convert the player's binds to the group
15138 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15140 bool has_binds = false;
15141 bool has_solo = false;
15143 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15144 assert(player_guid);
15146 // copy all binds to the group, when changing leader it's assumed the character
15147 // will not have any solo binds
15149 if(player)
15151 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15153 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15155 has_binds = true;
15156 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15157 // permanent binds are not removed
15158 if(!itr->second.perm)
15160 player->UnbindInstance(itr, i, true); // increments itr
15161 has_solo = true;
15163 else
15164 ++itr;
15169 // if the player's not online we don't know what binds it has
15170 if(!player || !group || has_binds) CharacterDatabase.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid));
15171 // the following should not get executed when changing leaders
15172 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15175 bool Player::_LoadHomeBind(QueryResult *result)
15177 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15178 if(!info)
15180 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15181 return false;
15184 bool ok = false;
15185 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15186 if (result)
15188 Field *fields = result->Fetch();
15189 m_homebindMapId = fields[0].GetUInt32();
15190 m_homebindZoneId = fields[1].GetUInt16();
15191 m_homebindX = fields[2].GetFloat();
15192 m_homebindY = fields[3].GetFloat();
15193 m_homebindZ = fields[4].GetFloat();
15194 delete result;
15196 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15198 // accept saved data only for valid position (and non instanceable), and accessable
15199 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15200 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15202 ok = true;
15204 else
15205 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15208 if(!ok)
15210 m_homebindMapId = info->mapId;
15211 m_homebindZoneId = info->zoneId;
15212 m_homebindX = info->positionX;
15213 m_homebindY = info->positionY;
15214 m_homebindZ = info->positionZ;
15216 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);
15219 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15220 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15222 return true;
15225 /*********************************************************/
15226 /*** SAVE SYSTEM ***/
15227 /*********************************************************/
15229 void Player::SaveToDB()
15231 // delay auto save at any saves (manual, in code, or autosave)
15232 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15234 // first save/honor gain after midnight will also update the player's honor fields
15235 UpdateHonorFields();
15237 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15238 //save, far from tavern/city
15239 //save, but in tavern/city
15240 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15241 outDebugValues();
15243 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15244 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15245 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15246 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15247 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15248 uint32 tmp_displayid = GetDisplayId();
15250 // Set player sit state to standing on save, also stealth and shifted form
15251 SetByteValue(UNIT_FIELD_BYTES_1, 0, UNIT_STAND_STATE_STAND);
15252 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15253 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15254 SetDisplayId(GetNativeDisplayId());
15256 bool inworld = IsInWorld();
15258 CharacterDatabase.BeginTransaction();
15260 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15262 std::string sql_name = m_name;
15263 CharacterDatabase.escape_string(sql_name);
15265 std::ostringstream ss;
15266 ss << "INSERT INTO characters (guid,account,name,race,class,"
15267 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15268 "taximask, online, cinematic, "
15269 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15270 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15271 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15272 << GetGUIDLow() << ", "
15273 << GetSession()->GetAccountId() << ", '"
15274 << sql_name << "', "
15275 << m_race << ", "
15276 << m_class << ", ";
15278 if(!IsBeingTeleported())
15280 ss << GetMapId() << ", "
15281 << (uint32)GetDifficulty() << ", "
15282 << finiteAlways(GetPositionX()) << ", "
15283 << finiteAlways(GetPositionY()) << ", "
15284 << finiteAlways(GetPositionZ()) << ", "
15285 << finiteAlways(GetOrientation()) << ", '";
15287 else
15289 ss << GetTeleportDest().mapid << ", "
15290 << (uint32)GetDifficulty() << ", "
15291 << finiteAlways(GetTeleportDest().x) << ", "
15292 << finiteAlways(GetTeleportDest().y) << ", "
15293 << finiteAlways(GetTeleportDest().z) << ", "
15294 << finiteAlways(GetTeleportDest().o) << ", '";
15297 uint16 i;
15298 for( i = 0; i < m_valuesCount; ++i )
15300 ss << GetUInt32Value(i) << " ";
15303 ss << "', ";
15305 ss << m_taxi; // string with TaxiMaskSize numbers
15307 ss << ", ";
15308 ss << (inworld ? 1 : 0);
15310 ss << ", ";
15311 ss << m_cinematic;
15313 ss << ", ";
15314 ss << m_Played_time[0];
15315 ss << ", ";
15316 ss << m_Played_time[1];
15318 ss << ", ";
15319 ss << finiteAlways(m_rest_bonus);
15320 ss << ", ";
15321 ss << (uint64)time(NULL);
15322 ss << ", ";
15323 ss << is_save_resting;
15324 ss << ", ";
15325 ss << m_resetTalentsCost;
15326 ss << ", ";
15327 ss << (uint64)m_resetTalentsTime;
15329 ss << ", ";
15330 ss << finiteAlways(m_movementInfo.t_x);
15331 ss << ", ";
15332 ss << finiteAlways(m_movementInfo.t_y);
15333 ss << ", ";
15334 ss << finiteAlways(m_movementInfo.t_z);
15335 ss << ", ";
15336 ss << finiteAlways(m_movementInfo.t_o);
15337 ss << ", ";
15338 if (m_transport)
15339 ss << m_transport->GetGUIDLow();
15340 else
15341 ss << "0";
15343 ss << ", ";
15344 ss << m_ExtraFlags;
15346 ss << ", ";
15347 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15349 ss << ", ";
15350 ss << uint32(m_atLoginFlags);
15352 ss << ", ";
15353 ss << GetZoneId();
15355 ss << ", ";
15356 ss << (uint64)m_deathExpireTime;
15358 ss << ", '";
15359 ss << m_taxi.SaveTaxiDestinationsToString();
15360 ss << "', '0', ";
15361 ss << GetBattleGroundId();
15362 ss << ", ";
15363 ss << GetBGTeam();
15364 ss << ", ";
15365 ss << m_bgEntryPoint.mapid << ", "
15366 << finiteAlways(m_bgEntryPoint.x) << ", "
15367 << finiteAlways(m_bgEntryPoint.y) << ", "
15368 << finiteAlways(m_bgEntryPoint.z) << ", "
15369 << finiteAlways(m_bgEntryPoint.o);
15370 ss << ")";
15372 CharacterDatabase.Execute( ss.str().c_str() );
15374 if(m_mailsUpdated) //save mails only when needed
15375 _SaveMail();
15377 _SaveInventory();
15378 _SaveQuestStatus();
15379 _SaveDailyQuestStatus();
15380 _SaveSpells();
15381 _SaveSpellCooldowns();
15382 _SaveActions();
15383 _SaveAuras();
15384 m_achievementMgr.SaveToDB();
15385 m_reputationMgr.SaveToDB();
15386 _SaveEquipmentSets();
15387 GetSession()->SaveTutorialsData(); // changed only while character in game
15389 CharacterDatabase.CommitTransaction();
15391 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15392 SetDisplayId(tmp_displayid);
15393 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15394 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15395 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15396 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15398 // save pet (hunter pet level and experience and all type pets health/mana).
15399 if(Pet* pet = GetPet())
15400 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15403 // fast save function for item/money cheating preventing - save only inventory and money state
15404 void Player::SaveInventoryAndGoldToDB()
15406 _SaveInventory();
15407 //money is in data field
15408 SaveDataFieldToDB();
15411 void Player::_SaveActions()
15413 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15415 switch (itr->second.uState)
15417 case ACTIONBUTTON_NEW:
15418 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15419 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15420 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15421 ++itr;
15422 break;
15423 case ACTIONBUTTON_CHANGED:
15424 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15425 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15426 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15427 ++itr;
15428 break;
15429 case ACTIONBUTTON_DELETED:
15430 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15431 m_actionButtons.erase(itr++);
15432 break;
15433 default:
15434 ++itr;
15435 break;
15440 void Player::_SaveAuras()
15442 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15444 AuraMap const& auras = GetAuras();
15446 if (auras.empty())
15447 return;
15449 spellEffectPair lastEffectPair = auras.begin()->first;
15450 uint32 stackCounter = 1;
15452 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15454 if(itr == auras.end() || lastEffectPair != itr->first)
15456 AuraMap::const_iterator itr2 = itr;
15457 // save previous spellEffectPair to db
15458 itr2--;
15460 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15462 //skip all auras from spells that are passive or need a shapeshift
15463 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15465 //do not save single target auras (unless they were cast by the player)
15466 if (!(itr2->second->GetCasterGUID() != GetGUID() && itr2->second->IsSingleTarget()))
15468 uint8 i;
15469 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15470 for (i = 0; i < 3; ++i)
15471 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15472 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15473 break;
15475 if (i == 3)
15477 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15478 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15479 GetGUIDLow(), itr2->second->GetCasterGUID(), (uint32)itr2->second->GetId(), (uint32)itr2->second->GetEffIndex(), stackCounter, itr2->second->GetModifier()->m_amount,int(itr2->second->GetAuraMaxDuration()),int(itr2->second->GetAuraDuration()),int(itr2->second->GetAuraCharges()));
15484 if(itr == auras.end())
15485 break;
15488 if (lastEffectPair == itr->first)
15489 stackCounter++;
15490 else
15492 lastEffectPair = itr->first;
15493 stackCounter = 1;
15498 void Player::_SaveInventory()
15500 // force items in buyback slots to new state
15501 // and remove those that aren't already
15502 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
15504 Item *item = m_items[i];
15505 if (!item || item->GetState() == ITEM_NEW) continue;
15506 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15507 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15508 m_items[i]->FSetState(ITEM_NEW);
15511 // update enchantment durations
15512 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15514 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15517 // if no changes
15518 if (m_itemUpdateQueue.empty()) return;
15520 // do not save if the update queue is corrupt
15521 bool error = false;
15522 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15524 Item *item = m_itemUpdateQueue[i];
15525 if(!item || item->GetState() == ITEM_REMOVED) continue;
15526 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15528 if (test == NULL)
15530 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());
15531 error = true;
15533 else if (test != item)
15535 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());
15536 error = true;
15540 if (error)
15542 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15543 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15544 return;
15547 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15549 Item *item = m_itemUpdateQueue[i];
15550 if(!item) continue;
15552 Bag *container = item->GetContainer();
15553 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15555 switch(item->GetState())
15557 case ITEM_NEW:
15558 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());
15559 break;
15560 case ITEM_CHANGED:
15561 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());
15562 break;
15563 case ITEM_REMOVED:
15564 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15565 break;
15566 case ITEM_UNCHANGED:
15567 break;
15570 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15572 m_itemUpdateQueue.clear();
15575 void Player::_SaveMail()
15577 if (!m_mailsLoaded)
15578 return;
15580 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15582 Mail *m = (*itr);
15583 if (m->state == MAIL_STATE_CHANGED)
15585 CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" I64FMTD "', deliver_time = '" I64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15586 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15587 if(m->removedItems.size())
15589 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15590 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15591 m->removedItems.clear();
15593 m->state = MAIL_STATE_UNCHANGED;
15595 else if (m->state == MAIL_STATE_DELETED)
15597 if (m->HasItems())
15598 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15599 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15600 if (m->itemTextId)
15601 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15602 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15603 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15607 //deallocate deleted mails...
15608 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15610 if ((*itr)->state == MAIL_STATE_DELETED)
15612 Mail* m = *itr;
15613 m_mail.erase(itr);
15614 delete m;
15615 itr = m_mail.begin();
15617 else
15618 ++itr;
15621 m_mailsUpdated = false;
15624 void Player::_SaveQuestStatus()
15626 // we don't need transactions here.
15627 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15629 switch (i->second.uState)
15631 case QUEST_NEW :
15632 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15633 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15634 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]);
15635 break;
15636 case QUEST_CHANGED :
15637 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" I64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15638 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 );
15639 break;
15640 case QUEST_UNCHANGED:
15641 break;
15643 i->second.uState = QUEST_UNCHANGED;
15647 void Player::_SaveDailyQuestStatus()
15649 if(!m_DailyQuestChanged)
15650 return;
15652 m_DailyQuestChanged = false;
15654 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15656 // we don't need transactions here.
15657 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15658 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15659 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15660 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15661 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15664 void Player::_SaveSpells()
15666 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15668 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15669 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15671 // add only changed/new not dependent spells
15672 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15673 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);
15675 if (itr->second->state == PLAYERSPELL_REMOVED)
15677 delete itr->second;
15678 m_spells.erase(itr++);
15680 else
15682 itr->second->state = PLAYERSPELL_UNCHANGED;
15683 ++itr;
15689 void Player::outDebugValues() const
15691 if(!sLog.IsOutDebug()) // optimize disabled debug output
15692 return;
15694 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15695 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15696 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15697 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15698 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15699 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15700 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15701 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15702 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15703 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15704 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15705 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15708 /*********************************************************/
15709 /*** FLOOD FILTER SYSTEM ***/
15710 /*********************************************************/
15712 void Player::UpdateSpeakTime()
15714 // ignore chat spam protection for GMs in any mode
15715 if(GetSession()->GetSecurity() > SEC_PLAYER)
15716 return;
15718 time_t current = time (NULL);
15719 if(m_speakTime > current)
15721 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15722 if(!max_count)
15723 return;
15725 ++m_speakCount;
15726 if(m_speakCount >= max_count)
15728 // prevent overwrite mute time, if message send just before mutes set, for example.
15729 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15730 if(GetSession()->m_muteTime < new_mute)
15731 GetSession()->m_muteTime = new_mute;
15733 m_speakCount = 0;
15736 else
15737 m_speakCount = 0;
15739 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15742 bool Player::CanSpeak() const
15744 return GetSession()->m_muteTime <= time (NULL);
15747 /*********************************************************/
15748 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15749 /*********************************************************/
15751 void Player::SendAttackSwingNotInRange()
15753 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15754 GetSession()->SendPacket( &data );
15757 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15759 std::ostringstream ss;
15760 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15761 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15762 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15763 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15764 sLog.outDebug(ss.str().c_str());
15765 CharacterDatabase.Execute(ss.str().c_str());
15768 void Player::SaveDataFieldToDB()
15770 std::ostringstream ss;
15771 ss<<"UPDATE characters SET data='";
15773 for(uint16 i = 0; i < m_valuesCount; ++i )
15775 ss << GetUInt32Value(i) << " ";
15777 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15779 CharacterDatabase.Execute(ss.str().c_str());
15782 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15784 std::ostringstream ss2;
15785 ss2<<"UPDATE characters SET data='";
15786 int i=0;
15787 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15789 ss2<<tokens[i]<<" ";
15791 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15793 return CharacterDatabase.Execute(ss2.str().c_str());
15796 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15798 char buf[11];
15799 snprintf(buf,11,"%u",value);
15801 if(index >= tokens.size())
15802 return;
15804 tokens[index] = buf;
15807 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15809 Tokens tokens;
15810 if(!LoadValuesArrayFromDB(tokens,guid))
15811 return;
15813 if(index >= tokens.size())
15814 return;
15816 char buf[11];
15817 snprintf(buf,11,"%u",value);
15818 tokens[index] = buf;
15820 SaveValuesArrayInDB(tokens,guid);
15823 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15825 uint32 temp;
15826 memcpy(&temp, &value, sizeof(value));
15827 Player::SetUInt32ValueInDB(index, temp, guid);
15830 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15832 Tokens tokens;
15833 if(!LoadValuesArrayFromDB(tokens, guid))
15834 return;
15836 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15837 uint8 race = unit_bytes0 & 0xFF;
15838 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15840 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15841 if(!info)
15842 return;
15844 unit_bytes0 &= ~(0xFF << 16);
15845 unit_bytes0 |= (gender << 16);
15846 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15848 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
15849 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
15851 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
15853 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
15854 player_bytes2 &= ~0xFF;
15855 player_bytes2 |= facialHair;
15856 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
15858 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
15859 player_bytes3 &= ~0xFF;
15860 player_bytes3 |= gender;
15861 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
15863 SaveValuesArrayInDB(tokens, guid);
15866 void Player::SendAttackSwingNotStanding()
15868 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15869 GetSession()->SendPacket( &data );
15872 void Player::SendAttackSwingDeadTarget()
15874 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15875 GetSession()->SendPacket( &data );
15878 void Player::SendAttackSwingCantAttack()
15880 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15881 GetSession()->SendPacket( &data );
15884 void Player::SendAttackSwingCancelAttack()
15886 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15887 GetSession()->SendPacket( &data );
15890 void Player::SendAttackSwingBadFacingAttack()
15892 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15893 GetSession()->SendPacket( &data );
15896 void Player::SendAutoRepeatCancel()
15898 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
15899 data.append(GetPackGUID()); // may be it's target guid
15900 GetSession()->SendPacket( &data );
15903 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15905 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15906 data << Area;
15907 data << Experience;
15908 GetSession()->SendPacket(&data);
15911 void Player::SendDungeonDifficulty(bool IsInGroup)
15913 uint8 val = 0x00000001;
15914 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15915 data << (uint32)GetDifficulty();
15916 data << uint32(val);
15917 data << uint32(IsInGroup);
15918 GetSession()->SendPacket(&data);
15921 void Player::SendResetFailedNotify(uint32 mapid)
15923 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15924 data << uint32(mapid);
15925 GetSession()->SendPacket(&data);
15928 /// Reset all solo instances and optionally send a message on success for each
15929 void Player::ResetInstances(uint8 method)
15931 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15933 // we assume that when the difficulty changes, all instances that can be reset will be
15934 uint8 dif = GetDifficulty();
15936 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15938 InstanceSave *p = itr->second.save;
15939 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15940 if(!entry || !p->CanReset())
15942 ++itr;
15943 continue;
15946 if(method == INSTANCE_RESET_ALL)
15948 // the "reset all instances" method can only reset normal maps
15949 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15951 ++itr;
15952 continue;
15956 // if the map is loaded, reset it
15957 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
15958 if(map && map->IsDungeon())
15959 ((InstanceMap*)map)->Reset(method);
15961 // since this is a solo instance there should not be any players inside
15962 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
15963 SendResetInstanceSuccess(p->GetMapId());
15965 p->DeleteFromDB();
15966 m_boundInstances[dif].erase(itr++);
15968 // the following should remove the instance save from the manager and delete it as well
15969 p->RemovePlayer(this);
15973 void Player::SendResetInstanceSuccess(uint32 MapId)
15975 WorldPacket data(SMSG_INSTANCE_RESET, 4);
15976 data << MapId;
15977 GetSession()->SendPacket(&data);
15980 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
15982 // TODO: find what other fail reasons there are besides players in the instance
15983 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
15984 data << reason;
15985 data << MapId;
15986 GetSession()->SendPacket(&data);
15989 /*********************************************************/
15990 /*** Update timers ***/
15991 /*********************************************************/
15993 ///checks the 15 afk reports per 5 minutes limit
15994 void Player::UpdateAfkReport(time_t currTime)
15996 if(m_bgAfkReportedTimer <= currTime)
15998 m_bgAfkReportedCount = 0;
15999 m_bgAfkReportedTimer = currTime+5*MINUTE;
16003 void Player::UpdateContestedPvP(uint32 diff)
16005 if(!m_contestedPvPTimer||isInCombat())
16006 return;
16007 if(m_contestedPvPTimer <= diff)
16009 ResetContestedPvP();
16011 else
16012 m_contestedPvPTimer -= diff;
16015 void Player::UpdatePvPFlag(time_t currTime)
16017 if(!IsPvP())
16018 return;
16019 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16020 return;
16022 UpdatePvP(false);
16025 void Player::UpdateDuelFlag(time_t currTime)
16027 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16028 return;
16030 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16031 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16033 duel->startTimer = 0;
16034 duel->startTime = currTime;
16035 duel->opponent->duel->startTimer = 0;
16036 duel->opponent->duel->startTime = currTime;
16039 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16041 if(!pet)
16042 pet = GetPet();
16044 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16046 //returning of reagents only for players, so best done here
16047 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16048 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16050 if(spellInfo)
16052 for(uint32 i = 0; i < 7; ++i)
16054 if(spellInfo->Reagent[i] > 0)
16056 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16057 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16058 if( msg == EQUIP_ERR_OK )
16060 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16061 if(IsInWorld())
16062 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16067 m_temporaryUnsummonedPetNumber = 0;
16070 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16071 return;
16073 // only if current pet in slot
16074 switch(pet->getPetType())
16076 case MINI_PET:
16077 m_miniPet = 0;
16078 break;
16079 case GUARDIAN_PET:
16080 m_guardianPets.erase(pet->GetGUID());
16081 break;
16082 default:
16083 if(GetPetGUID() == pet->GetGUID())
16084 SetPet(NULL);
16085 break;
16088 pet->CombatStop();
16090 if(returnreagent)
16092 switch(pet->GetEntry())
16094 //warlock pets except imp are removed(?) when logging out
16095 case 1860:
16096 case 1863:
16097 case 417:
16098 case 17252:
16099 mode = PET_SAVE_NOT_IN_SLOT;
16100 break;
16104 pet->SavePetToDB(mode);
16106 pet->CleanupsBeforeDelete();
16107 pet->AddObjectToRemoveList();
16108 pet->m_removed = true;
16110 if(pet->isControlled())
16112 WorldPacket data(SMSG_PET_SPELLS, 8);
16113 data << uint64(0);
16114 GetSession()->SendPacket(&data);
16116 if(GetGroup())
16117 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16121 void Player::RemoveMiniPet()
16123 if(Pet* pet = GetMiniPet())
16125 pet->Remove(PET_SAVE_AS_DELETED);
16126 m_miniPet = 0;
16130 Pet* Player::GetMiniPet()
16132 if(!m_miniPet)
16133 return NULL;
16134 return ObjectAccessor::GetPet(m_miniPet);
16137 void Player::RemoveGuardians()
16139 while(!m_guardianPets.empty())
16141 uint64 guid = *m_guardianPets.begin();
16142 if(Pet* pet = ObjectAccessor::GetPet(guid))
16143 pet->Remove(PET_SAVE_AS_DELETED);
16145 m_guardianPets.erase(guid);
16149 bool Player::HasGuardianWithEntry(uint32 entry)
16151 // pet guid middle part is entry (and creature also)
16152 // and in guardian list must be guardians with same entry _always_
16153 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16155 if(Pet* pet = ObjectAccessor::GetPet(*itr))
16156 if (pet->GetEntry() == entry)
16157 return true;
16160 return false;
16163 void Player::Uncharm()
16165 Unit* charm = GetCharm();
16166 if(!charm)
16167 return;
16169 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16170 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16173 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16175 *data << (uint8)msgtype;
16176 *data << (uint32)language;
16177 *data << (uint64)GetGUID();
16178 *data << (uint32)language; //language 2.1.0 ?
16179 *data << (uint64)GetGUID();
16180 *data << (uint32)(text.length()+1);
16181 *data << text;
16182 *data << (uint8)chatTag();
16185 void Player::Say(const std::string& text, const uint32 language)
16187 WorldPacket data(SMSG_MESSAGECHAT, 200);
16188 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16189 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16192 void Player::Yell(const std::string& text, const uint32 language)
16194 WorldPacket data(SMSG_MESSAGECHAT, 200);
16195 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16196 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16199 void Player::TextEmote(const std::string& text)
16201 WorldPacket data(SMSG_MESSAGECHAT, 200);
16202 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16203 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16206 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16208 if (language != LANG_ADDON) // if not addon data
16209 language = LANG_UNIVERSAL; // whispers should always be readable
16211 Player *rPlayer = objmgr.GetPlayer(receiver);
16213 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16214 if(!rPlayer->isDND() || isGameMaster())
16216 WorldPacket data(SMSG_MESSAGECHAT, 200);
16217 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16218 rPlayer->GetSession()->SendPacket(&data);
16220 data.Initialize(SMSG_MESSAGECHAT, 200);
16221 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16222 GetSession()->SendPacket(&data);
16224 else
16226 // announce to player that player he is whispering to is dnd and cannot receive his message
16227 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16230 if(!isAcceptWhispers())
16232 SetAcceptWhispers(true);
16233 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16236 // announce to player that player he is whispering to is afk
16237 if(rPlayer->isAFK())
16238 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16240 // if player whisper someone, auto turn of dnd to be able to receive an answer
16241 if(isDND() && !rPlayer->isGameMaster())
16242 ToggleDND();
16245 void Player::PetSpellInitialize()
16247 Pet* pet = GetPet();
16249 if(!pet)
16250 return;
16252 sLog.outDebug("Pet Spells Groups");
16254 CharmInfo *charmInfo = pet->GetCharmInfo();
16256 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*10+1+1);
16257 data << uint64(pet->GetGUID());
16258 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16259 data << uint32(0);
16260 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16262 // action bar loop
16263 for(uint32 i = 0; i < 10; ++i)
16265 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16268 size_t spellsCountPos = data.wpos();
16270 // spells count
16271 uint8 addlist = 0;
16272 data << uint8(addlist); // placeholder
16274 if (pet->IsPermanentPetFor(this))
16276 // spells loop
16277 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16279 if(itr->second->state == PETSPELL_REMOVED)
16280 continue;
16282 data << uint16(itr->first);
16283 data << uint16(itr->second->active); // pet spell active state isn't boolean
16284 ++addlist;
16288 data.put<uint8>(spellsCountPos, addlist);
16290 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16291 data << uint8(cooldownsCount);
16293 time_t curTime = time(NULL);
16295 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16297 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16299 data << uint32(itr->first); // spellid
16300 data << uint16(0); // spell category?
16301 data << uint32(cooldown); // cooldown
16302 data << uint32(0); // category cooldown
16305 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16307 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16309 data << uint32(itr->first); // spellid
16310 data << uint16(0); // spell category?
16311 data << uint32(0); // cooldown
16312 data << uint32(cooldown); // category cooldown
16315 GetSession()->SendPacket(&data);
16318 void Player::PossessSpellInitialize()
16320 Unit* charm = GetCharm();
16322 if(!charm)
16323 return;
16325 CharmInfo *charmInfo = charm->GetCharmInfo();
16327 if(!charmInfo)
16329 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16330 return;
16333 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*10+1+1);
16334 data << uint64(charm->GetGUID());
16335 data << uint16(0);
16336 data << uint32(0);
16337 data << uint32(0);
16339 for(uint32 i = 0; i < 10; ++i)
16341 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16344 data << uint8(0); // spells count
16345 data << uint8(0); // cooldowns count
16347 GetSession()->SendPacket(&data);
16350 void Player::CharmSpellInitialize()
16352 Unit* charm = GetCharm();
16354 if(!charm)
16355 return;
16357 CharmInfo *charmInfo = charm->GetCharmInfo();
16358 if(!charmInfo)
16360 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16361 return;
16364 uint8 addlist = 0;
16366 if(charm->GetTypeId() != TYPEID_PLAYER)
16368 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16370 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16372 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16374 if(charmInfo->GetCharmSpell(i)->spellId)
16375 ++addlist;
16380 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*10+1+4*addlist+1);
16381 data << uint64(charm->GetGUID());
16382 data << uint16(0);
16383 data << uint32(0);
16385 if(charm->GetTypeId() != TYPEID_PLAYER)
16386 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16387 else
16388 data << uint8(0) << uint8(0) << uint16(0);
16390 for(uint32 i = 0; i < 10; ++i)
16392 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16395 data << uint8(addlist);
16397 if(addlist)
16399 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16401 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16402 if(cspell->spellId)
16404 data << uint16(cspell->spellId);
16405 data << uint16(cspell->active);
16410 data << uint8(0); // cooldowns count
16412 GetSession()->SendPacket(&data);
16415 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16417 if (!mod || !spellInfo)
16418 return false;
16420 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16422 // prevent apply to any spell except spell that trigger expire
16423 if(spell)
16425 if(mod->lastAffected != spell)
16426 return false;
16428 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16429 return false;
16432 return spellmgr.IsAffectedByMod(spellInfo, mod);
16435 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16437 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16439 for(int eff=0;eff<96;++eff)
16441 uint64 _mask = 0;
16442 uint64 _mask2= 0;
16443 if (eff<64) _mask = uint64(1) << (eff- 0);
16444 else _mask2= uint64(1) << (eff-64);
16445 if ( mod->mask & _mask || mod->mask2 & _mask2)
16447 int32 val = 0;
16448 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16450 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16451 val += (*itr)->value;
16453 val += apply ? mod->value : -(mod->value);
16454 WorldPacket data(Opcode, (1+1+4));
16455 data << uint8(eff);
16456 data << uint8(mod->op);
16457 data << int32(val);
16458 SendDirectMessage(&data);
16462 if (apply)
16463 m_spellMods[mod->op].push_back(mod);
16464 else
16466 if (mod->charges == -1)
16467 --m_SpellModRemoveCount;
16468 m_spellMods[mod->op].remove(mod);
16469 delete mod;
16473 void Player::RemoveSpellMods(Spell const* spell)
16475 if(!spell || (m_SpellModRemoveCount == 0))
16476 return;
16478 for(int i=0;i<MAX_SPELLMOD;++i)
16480 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16482 SpellModifier *mod = *itr;
16483 ++itr;
16485 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16487 RemoveAurasDueToSpell(mod->spellId);
16488 if (m_spellMods[i].empty())
16489 break;
16490 else
16491 itr = m_spellMods[i].begin();
16497 // send Proficiency
16498 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16500 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16501 data << pr1 << pr2;
16502 GetSession()->SendPacket (&data);
16505 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16507 QueryResult *result = NULL;
16508 if(type==10)
16509 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16510 else
16511 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16512 if(result)
16514 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.
16515 { // and SendPetitionQueryOpcode reads data from the DB
16516 Field *fields = result->Fetch();
16517 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16518 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16520 // send update if charter owner in game
16521 Player* owner = objmgr.GetPlayer(ownerguid);
16522 if(owner)
16523 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16525 } while ( result->NextRow() );
16527 delete result;
16529 if(type==10)
16530 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16531 else
16532 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16535 CharacterDatabase.BeginTransaction();
16536 if(type == 10)
16538 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16539 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16541 else
16543 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16544 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16546 CharacterDatabase.CommitTransaction();
16549 void Player::LeaveAllArenaTeams(uint64 guid)
16551 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));
16552 if(!result)
16553 return;
16557 Field *fields = result->Fetch();
16558 uint32 at_id = fields[0].GetUInt32();
16559 if(at_id != 0)
16561 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16562 if(at)
16563 at->DelMember(guid);
16565 } while (result->NextRow());
16567 delete result;
16570 void Player::SetRestBonus (float rest_bonus_new)
16572 // Prevent resting on max level
16573 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16574 rest_bonus_new = 0;
16576 if(rest_bonus_new < 0)
16577 rest_bonus_new = 0;
16579 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16581 if(rest_bonus_new > rest_bonus_max)
16582 m_rest_bonus = rest_bonus_max;
16583 else
16584 m_rest_bonus = rest_bonus_new;
16586 // update data for client
16587 if(m_rest_bonus>10)
16588 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16589 else if(m_rest_bonus<=1)
16590 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16592 //RestTickUpdate
16593 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16596 void Player::HandleStealthedUnitsDetection()
16598 std::list<Unit*> stealthedUnits;
16600 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16601 Cell cell(p);
16602 cell.data.Part.reserved = ALL_DISTRICT;
16603 cell.SetNoCreate();
16605 MaNGOS::AnyStealthedCheck u_check;
16606 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16608 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16609 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16611 CellLock<GridReadGuard> cell_lock(cell, p);
16612 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16613 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16615 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16617 if((*i)==this)
16619 i = stealthedUnits.erase(i);
16620 continue;
16623 if ((*i)->isVisibleForOrDetect(this,true))
16626 (*i)->SendUpdateToPlayer(this);
16627 m_clientGUIDs.insert((*i)->GetGUID());
16629 #ifdef MANGOS_DEBUG
16630 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16631 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16632 #endif
16634 // target aura duration for caster show only if target exist at caster client
16635 // send data at target visibility change (adding to client)
16636 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16637 SendAurasForTarget(*i);
16639 i = stealthedUnits.erase(i);
16640 continue;
16643 ++i;
16647 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
16649 if(nodes.size() < 2)
16650 return false;
16652 // 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
16653 if(GetSession()->isLogingOut() || isInCombat())
16655 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16656 data << uint32(ERR_TAXIPLAYERBUSY);
16657 GetSession()->SendPacket(&data);
16658 return false;
16661 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16662 return false;
16664 // taximaster case
16665 if(npc)
16667 // not let cheating with start flight mounted
16668 if(IsMounted())
16670 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16671 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16672 GetSession()->SendPacket(&data);
16673 return false;
16676 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16678 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16679 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16680 GetSession()->SendPacket(&data);
16681 return false;
16684 // 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
16685 if(IsNonMeleeSpellCasted(false))
16687 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16688 data << uint32(ERR_TAXIPLAYERBUSY);
16689 GetSession()->SendPacket(&data);
16690 return false;
16693 // cast case or scripted call case
16694 else
16696 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
16698 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16699 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
16701 if(m_currentSpells[CURRENT_GENERIC_SPELL] && m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id != spellid)
16702 InterruptSpell(CURRENT_GENERIC_SPELL,false);
16704 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
16706 if(m_currentSpells[CURRENT_CHANNELED_SPELL] && m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id != spellid)
16707 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
16710 uint32 sourcenode = nodes[0];
16712 // starting node too far away (cheat?)
16713 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16714 if (!node)
16716 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16717 data << uint32(ERR_TAXINOSUCHPATH);
16718 GetSession()->SendPacket(&data);
16719 return false;
16722 // check node starting pos data set case if provided
16723 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
16725 if (node->map_id != GetMapId() ||
16726 (node->x - GetPositionX())*(node->x - GetPositionX())+
16727 (node->y - GetPositionY())*(node->y - GetPositionY())+
16728 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16729 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
16731 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16732 data << uint32(ERR_TAXITOOFARAWAY);
16733 GetSession()->SendPacket(&data);
16734 return false;
16737 // node must have pos if taxi master case (npc != NULL)
16738 else if (npc)
16740 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16741 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16742 GetSession()->SendPacket(&data);
16743 return false;
16746 // Prepare to flight start now
16748 // stop combat at start taxi flight if any
16749 CombatStop();
16751 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16752 TradeCancel(true);
16754 // clean not finished taxi path if any
16755 m_taxi.ClearTaxiDestinations();
16757 // 0 element current node
16758 m_taxi.AddTaxiDestination(sourcenode);
16760 // fill destinations path tail
16761 uint32 sourcepath = 0;
16762 uint32 totalcost = 0;
16764 uint32 prevnode = sourcenode;
16765 uint32 lastnode = 0;
16767 for(uint32 i = 1; i < nodes.size(); ++i)
16769 uint32 path, cost;
16771 lastnode = nodes[i];
16772 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16774 if(!path)
16776 m_taxi.ClearTaxiDestinations();
16777 return false;
16780 totalcost += cost;
16782 if(prevnode == sourcenode)
16783 sourcepath = path;
16785 m_taxi.AddTaxiDestination(lastnode);
16787 prevnode = lastnode;
16790 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
16791 uint16 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam(), npc == NULL);
16793 // in spell case allow 0 model
16794 if (mount_id == 0 && spellid == 0 || sourcepath == 0)
16796 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16797 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16798 GetSession()->SendPacket(&data);
16799 m_taxi.ClearTaxiDestinations();
16800 return false;
16803 uint32 money = GetMoney();
16805 if (npc)
16806 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16808 if(money < totalcost)
16810 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16811 data << uint32(ERR_TAXINOTENOUGHMONEY);
16812 GetSession()->SendPacket(&data);
16813 m_taxi.ClearTaxiDestinations();
16814 return false;
16817 //Checks and preparations done, DO FLIGHT
16818 ModifyMoney(-(int32)totalcost);
16819 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
16820 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
16822 // prevent stealth flight
16823 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16825 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16826 data << uint32(ERR_TAXIOK);
16827 GetSession()->SendPacket(&data);
16829 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16831 GetSession()->SendDoFlight(mount_id, sourcepath);
16833 return true;
16836 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
16838 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
16839 if(!entry)
16840 return false;
16842 std::vector<uint32> nodes;
16844 nodes.resize(2);
16845 nodes[0] = entry->from;
16846 nodes[1] = entry->to;
16848 return ActivateTaxiPathTo(nodes,NULL,spellid);
16851 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16853 // last check 2.0.10
16854 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16855 data << GetGUID();
16856 data << uint8(0x0); // flags (0x1, 0x2)
16857 time_t curTime = time(NULL);
16858 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16860 if (itr->second->state == PLAYERSPELL_REMOVED)
16861 continue;
16862 uint32 unSpellId = itr->first;
16863 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16864 if (!spellInfo)
16866 ASSERT(spellInfo);
16867 continue;
16870 // Not send cooldown for this spells
16871 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16872 continue;
16874 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16876 data << unSpellId;
16877 data << unTimeMs; // in m.secs
16878 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
16881 GetSession()->SendPacket(&data);
16884 void Player::InitDataForForm(bool reapplyMods)
16886 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16887 if(ssEntry && ssEntry->attackSpeed)
16889 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16890 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16891 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16893 else
16894 SetRegularAttackTime();
16896 switch(m_form)
16898 case FORM_CAT:
16900 if(getPowerType()!=POWER_ENERGY)
16901 setPowerType(POWER_ENERGY);
16902 break;
16904 case FORM_BEAR:
16905 case FORM_DIREBEAR:
16907 if(getPowerType()!=POWER_RAGE)
16908 setPowerType(POWER_RAGE);
16909 break;
16911 default: // 0, for example
16913 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16914 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16915 setPowerType(Powers(cEntry->powerType));
16916 break;
16920 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16921 if (!reapplyMods)
16922 UpdateEquipSpellsAtFormChange();
16924 UpdateAttackPowerAndDamage();
16925 UpdateAttackPowerAndDamage(true);
16928 // Return true is the bought item has a max count to force refresh of window by caller
16929 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16931 // cheating attempt
16932 if(count < 1) count = 1;
16934 if(!isAlive())
16935 return false;
16937 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16938 if( !pProto )
16940 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16941 return false;
16944 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
16945 if (!pCreature)
16947 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16948 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16949 return false;
16952 VendorItemData const* vItems = pCreature->GetVendorItems();
16953 if(!vItems || vItems->Empty())
16955 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16956 return false;
16959 size_t vendor_slot = vItems->FindItemSlot(item);
16960 if(vendor_slot >= vItems->GetItemCount())
16962 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16963 return false;
16966 VendorItem const* crItem = vItems->m_items[vendor_slot];
16968 // check current item amount if it limited
16969 if( crItem->maxcount != 0 )
16971 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16973 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16974 return false;
16978 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16980 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16981 return false;
16984 if(crItem->ExtendedCost)
16986 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16987 if(!iece)
16989 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16990 return false;
16993 // honor points price
16994 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16996 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16997 return false;
17000 // arena points price
17001 if(GetArenaPoints() < (iece->reqarenapoints * count))
17003 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17004 return false;
17007 // item base price
17008 for (uint8 i = 0; i < 5; ++i)
17010 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17012 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17013 return false;
17017 // check for personal arena rating requirement
17018 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17020 // probably not the proper equip err
17021 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17022 return false;
17026 uint32 price = pProto->BuyPrice * count;
17028 // reputation discount
17029 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17031 if( GetMoney() < price )
17033 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17034 return false;
17037 uint8 bag = 0; // init for case invalid bagGUID
17039 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17041 Bag *pBag;
17042 if( bagguid == GetGUID() )
17044 bag = INVENTORY_SLOT_BAG_0;
17046 else
17048 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;++i)
17050 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17051 if( pBag )
17053 if( bagguid == pBag->GetGUID() )
17055 bag = i;
17056 break;
17063 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17065 ItemPosCountVec dest;
17066 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17067 if( msg != EQUIP_ERR_OK )
17069 SendEquipError( msg, NULL, NULL );
17070 return false;
17073 ModifyMoney( -(int32)price );
17074 if(crItem->ExtendedCost) // case for new honor system
17076 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17077 if(iece->reqhonorpoints)
17078 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17079 if(iece->reqarenapoints)
17080 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17081 for (uint8 i = 0; i < 5; ++i)
17083 if(iece->reqitem[i])
17084 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17088 if(Item *it = StoreNewItem( dest, item, true ))
17090 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17092 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17093 data << pCreature->GetGUID();
17094 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17095 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17096 data << (uint32)count;
17097 GetSession()->SendPacket(&data);
17099 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17102 else if( IsEquipmentPos( bag, slot ) )
17104 if(pProto->BuyCount * count != 1)
17106 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17107 return false;
17110 uint16 dest;
17111 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17112 if( msg != EQUIP_ERR_OK )
17114 SendEquipError( msg, NULL, NULL );
17115 return false;
17118 ModifyMoney( -(int32)price );
17119 if(crItem->ExtendedCost) // case for new honor system
17121 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17122 if(iece->reqhonorpoints)
17123 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17124 if(iece->reqarenapoints)
17125 ModifyArenaPoints( - int32(iece->reqarenapoints));
17126 for (uint8 i = 0; i < 5; ++i)
17128 if(iece->reqitem[i])
17129 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17133 if(Item *it = EquipNewItem( dest, item, true ))
17135 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17137 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17138 data << pCreature->GetGUID();
17139 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17140 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17141 data << (uint32)count;
17142 GetSession()->SendPacket(&data);
17144 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17146 AutoUnequipOffhandIfNeed();
17149 else
17151 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17152 return false;
17155 return crItem->maxcount!=0;
17158 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17160 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17161 // the personal rating of the arena team must match the required limit as well
17162 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17163 uint32 max_personal_rating = 0;
17164 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17166 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17168 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17169 uint32 t_rating = at->GetRating();
17170 p_rating = p_rating<t_rating? p_rating : t_rating;
17171 if(max_personal_rating < p_rating)
17172 max_personal_rating = p_rating;
17175 return max_personal_rating;
17178 void Player::UpdateHomebindTime(uint32 time)
17180 // GMs never get homebind timer online
17181 if (m_InstanceValid || isGameMaster())
17183 if(m_HomebindTimer) // instance valid, but timer not reset
17185 // hide reminder
17186 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17187 data << uint32(0);
17188 data << uint32(0);
17189 GetSession()->SendPacket(&data);
17191 // instance is valid, reset homebind timer
17192 m_HomebindTimer = 0;
17194 else if (m_HomebindTimer > 0)
17196 if (time >= m_HomebindTimer)
17198 // teleport to nearest graveyard
17199 RepopAtGraveyard();
17201 else
17202 m_HomebindTimer -= time;
17204 else
17206 // instance is invalid, start homebind timer
17207 m_HomebindTimer = 60000;
17208 // send message to player
17209 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17210 data << m_HomebindTimer;
17211 data << uint32(1);
17212 GetSession()->SendPacket(&data);
17213 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17217 void Player::UpdatePvP(bool state, bool ovrride)
17219 if(!state || ovrride)
17221 SetPvP(state);
17222 if(Pet* pet = GetPet())
17223 pet->SetPvP(state);
17224 if(Unit* charmed = GetCharm())
17225 charmed->SetPvP(state);
17227 pvpInfo.endTimer = 0;
17229 else
17231 if(pvpInfo.endTimer != 0)
17232 pvpInfo.endTimer = time(NULL);
17233 else
17235 SetPvP(state);
17237 if(Pet* pet = GetPet())
17238 pet->SetPvP(state);
17239 if(Unit* charmed = GetCharm())
17240 charmed->SetPvP(state);
17245 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17247 // init cooldown values
17248 uint32 cat = 0;
17249 int32 rec = -1;
17250 int32 catrec = -1;
17252 // some special item spells without correct cooldown in SpellInfo
17253 // cooldown information stored in item prototype
17254 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17256 if(itemId)
17258 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17260 for(int idx = 0; idx < 5; ++idx)
17262 if(proto->Spells[idx].SpellId == spellInfo->Id)
17264 cat = proto->Spells[idx].SpellCategory;
17265 rec = proto->Spells[idx].SpellCooldown;
17266 catrec = proto->Spells[idx].SpellCategoryCooldown;
17267 break;
17273 // if no cooldown found above then base at DBC data
17274 if(rec < 0 && catrec < 0)
17276 cat = spellInfo->Category;
17277 rec = spellInfo->RecoveryTime;
17278 catrec = spellInfo->CategoryRecoveryTime;
17281 time_t curTime = time(NULL);
17283 time_t catrecTime;
17284 time_t recTime;
17286 // overwrite time for selected category
17287 if(infinityCooldown)
17289 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17290 // but not allow ignore until reset or re-login
17291 catrecTime = catrec > 0 ? curTime+MONTH : 0;
17292 recTime = rec > 0 ? curTime+MONTH : catrecTime;
17294 else
17296 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17297 // prevent 0 cooldowns set by another way
17298 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17299 rec = GetAttackTime(RANGED_ATTACK);
17301 // Now we have cooldown data (if found any), time to apply mods
17302 if(rec > 0)
17303 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17305 if(catrec > 0)
17306 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17308 // replace negative cooldowns by 0
17309 if (rec < 0) rec = 0;
17310 if (catrec < 0) catrec = 0;
17312 // no cooldown after applying spell mods
17313 if( rec == 0 && catrec == 0)
17314 return;
17316 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17317 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17320 // self spell cooldown
17321 if(recTime > 0)
17322 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17324 // category spells
17325 if (cat && catrec > 0)
17327 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17328 if(i_scstore != sSpellCategoryStore.end())
17330 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17332 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17333 continue;
17335 AddSpellCooldown(*i_scset, itemId, catrecTime);
17341 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17343 SpellCooldown sc;
17344 sc.end = end_time;
17345 sc.itemid = itemid;
17346 m_spellCooldowns[spellid] = sc;
17349 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17351 // start cooldowns at server side, if any
17352 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17354 // Send activate cooldown timer (possible 0) at client side
17355 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17356 data << spellInfo->Id;
17357 data << GetGUID();
17358 SendDirectMessage(&data);
17361 void Player::UpdatePotionCooldown(Spell* spell)
17363 // no potion used i combat or still in combat
17364 if(!m_lastPotionId || isInCombat())
17365 return;
17367 // Call not from spell cast, send cooldown event for item spells if no in combat
17368 if(!spell)
17370 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17371 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17372 for(int idx = 0; idx < 5; ++idx)
17373 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17374 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17375 SendCooldownEvent(spellInfo,m_lastPotionId);
17377 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17378 else
17379 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17381 m_lastPotionId = 0;
17384 //slot to be excluded while counting
17385 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17387 if(!enchantmentcondition)
17388 return true;
17390 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17392 if(!Condition)
17393 return true;
17395 uint8 curcount[4] = {0, 0, 0, 0};
17397 //counting current equipped gem colors
17398 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17400 if(i == slot)
17401 continue;
17402 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17403 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17405 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17407 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17408 if(!enchant_id)
17409 continue;
17411 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17412 if(!enchantEntry)
17413 continue;
17415 uint32 gemid = enchantEntry->GemID;
17416 if(!gemid)
17417 continue;
17419 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17420 if(!gemProto)
17421 continue;
17423 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17424 if(!gemProperty)
17425 continue;
17427 uint8 GemColor = gemProperty->color;
17429 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17431 if(tmpcolormask & GemColor)
17432 ++curcount[b];
17438 bool activate = true;
17440 for(int i = 0; i < 5; ++i)
17442 if(!Condition->Color[i])
17443 continue;
17445 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17447 // if have <CompareColor> use them as count, else use <value> from Condition
17448 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17450 switch(Condition->Comparator[i])
17452 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17453 activate &= (_cur_gem < _cmp_gem) ? true : false;
17454 break;
17455 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17456 activate &= (_cur_gem > _cmp_gem) ? true : false;
17457 break;
17458 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17459 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17460 break;
17464 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");
17466 return activate;
17469 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17471 //cycle all equipped items
17472 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17474 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17475 if(slot == exceptslot)
17476 continue;
17478 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17480 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17481 continue;
17483 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17485 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17486 if(!enchant_id)
17487 continue;
17489 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17490 if(!enchantEntry)
17491 continue;
17493 uint32 condition = enchantEntry->EnchantmentCondition;
17494 if(condition)
17496 //was enchant active with/without item?
17497 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17498 //should it now be?
17499 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17501 // ignore item gem conditions
17502 //if state changed, (dis)apply enchant
17503 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17510 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17511 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17513 //cycle all equipped items
17514 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17516 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17517 if(slot == exceptslot)
17518 continue;
17520 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17522 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17523 continue;
17525 //cycle all (gem)enchants
17526 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17528 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17529 if(!enchant_id) //if no enchant go to next enchant(slot)
17530 continue;
17532 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17533 if(!enchantEntry)
17534 continue;
17536 //only metagems to be (de)activated, so only enchants with condition
17537 uint32 condition = enchantEntry->EnchantmentCondition;
17538 if(condition)
17539 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17544 void Player::LeaveBattleground(bool teleportToEntryPoint)
17546 if(BattleGround *bg = GetBattleGround())
17548 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17550 // call after remove to be sure that player resurrected for correct cast
17551 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17553 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17554 CastSpell(this, 26013, true); // Deserter
17559 bool Player::CanJoinToBattleground() const
17561 // check Deserter debuff
17562 if(GetDummyAura(26013))
17563 return false;
17565 return true;
17568 bool Player::CanReportAfkDueToLimit()
17570 // a player can complain about 15 people per 5 minutes
17571 if(m_bgAfkReportedCount >= 15)
17572 return false;
17573 ++m_bgAfkReportedCount;
17574 return true;
17577 ///This player has been blamed to be inactive in a battleground
17578 void Player::ReportedAfkBy(Player* reporter)
17580 BattleGround *bg = GetBattleGround();
17581 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17582 return;
17584 // check if player has 'Idle' or 'Inactive' debuff
17585 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17587 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17588 // 3 players have to complain to apply debuff
17589 if(m_bgAfkReporter.size() >= 3)
17591 // cast 'Idle' spell
17592 CastSpell(this, 43680, true);
17593 m_bgAfkReporter.clear();
17598 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17600 // gamemaster in GM mode see all, including ghosts
17601 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17602 return true;
17604 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17605 if (InBattleGround())
17607 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17608 return false;
17609 return true;
17612 // Live player see live player or dead player with not realized corpse
17613 if(pl->isAlive() || pl->m_deathTimer > 0)
17615 return isAlive() || m_deathTimer > 0;
17618 // Ghost see other friendly ghosts, that's for sure
17619 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17620 return true;
17622 // Dead player see live players near own corpse
17623 if(isAlive())
17625 Corpse *corpse = pl->GetCorpse();
17626 if(corpse)
17628 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17629 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17630 return true;
17634 // and not see any other
17635 return false;
17638 bool Player::IsVisibleGloballyFor( Player* u ) const
17640 if(!u)
17641 return false;
17643 // Always can see self
17644 if (u==this)
17645 return true;
17647 // Visible units, always are visible for all players
17648 if (GetVisibility() == VISIBILITY_ON)
17649 return true;
17651 // GMs are visible for higher gms (or players are visible for gms)
17652 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17653 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17655 // non faction visibility non-breakable for non-GMs
17656 if (GetVisibility() == VISIBILITY_OFF)
17657 return false;
17659 // non-gm stealth/invisibility not hide from global player lists
17660 return true;
17663 void Player::UpdateVisibilityOf(WorldObject* target)
17665 if(HaveAtClient(target))
17667 if(!target->isVisibleForInState(this,true))
17669 target->DestroyForPlayer(this);
17670 m_clientGUIDs.erase(target->GetGUID());
17672 #ifdef MANGOS_DEBUG
17673 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17674 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17675 #endif
17678 else
17680 if(target->isVisibleForInState(this,false))
17682 target->SendUpdateToPlayer(this);
17683 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17684 m_clientGUIDs.insert(target->GetGUID());
17686 #ifdef MANGOS_DEBUG
17687 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17688 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17689 #endif
17691 // target aura duration for caster show only if target exist at caster client
17692 // send data at target visibility change (adding to client)
17693 if(target!=this && target->isType(TYPEMASK_UNIT))
17694 SendAurasForTarget((Unit*)target);
17696 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17697 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17702 template<class T>
17703 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17705 s64.insert(target->GetGUID());
17708 template<>
17709 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17711 if(!target->IsTransport())
17712 s64.insert(target->GetGUID());
17715 template<class T>
17716 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17718 if(HaveAtClient(target))
17720 if(!target->isVisibleForInState(this,true))
17722 target->BuildOutOfRangeUpdateBlock(&data);
17723 m_clientGUIDs.erase(target->GetGUID());
17725 #ifdef MANGOS_DEBUG
17726 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17727 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));
17728 #endif
17731 else
17733 if(target->isVisibleForInState(this,false))
17735 visibleNow.insert(target);
17736 target->BuildUpdate(data_updates);
17737 target->BuildCreateUpdateBlockForPlayer(&data, this);
17738 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17740 #ifdef MANGOS_DEBUG
17741 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17742 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));
17743 #endif
17748 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17749 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17750 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17751 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17752 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17754 void Player::InitPrimaryProffesions()
17756 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17759 void Player::SendComboPoints()
17761 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17762 if (combotarget)
17764 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17765 data.append(combotarget->GetPackGUID());
17766 data << uint8(m_comboPoints);
17767 GetSession()->SendPacket(&data);
17771 void Player::AddComboPoints(Unit* target, int8 count)
17773 if(!count)
17774 return;
17776 // without combo points lost (duration checked in aura)
17777 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17779 if(target->GetGUID() == m_comboTarget)
17781 m_comboPoints += count;
17783 else
17785 if(m_comboTarget)
17786 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
17787 target2->RemoveComboPointHolder(GetGUIDLow());
17789 m_comboTarget = target->GetGUID();
17790 m_comboPoints = count;
17792 target->AddComboPointHolder(GetGUIDLow());
17795 if (m_comboPoints > 5) m_comboPoints = 5;
17796 if (m_comboPoints < 0) m_comboPoints = 0;
17798 SendComboPoints();
17801 void Player::ClearComboPoints()
17803 if(!m_comboTarget)
17804 return;
17806 // without combopoints lost (duration checked in aura)
17807 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17809 m_comboPoints = 0;
17811 SendComboPoints();
17813 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17814 target->RemoveComboPointHolder(GetGUIDLow());
17816 m_comboTarget = 0;
17819 void Player::SetGroup(Group *group, int8 subgroup)
17821 if(group == NULL)
17822 m_group.unlink();
17823 else
17825 // never use SetGroup without a subgroup unless you specify NULL for group
17826 assert(subgroup >= 0);
17827 m_group.link(group, this);
17828 m_group.setSubGroup((uint8)subgroup);
17832 void Player::SendInitialPacketsBeforeAddToMap()
17834 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17835 data << uint32(0); // unknown, may be rest state time or experience
17836 GetSession()->SendPacket(&data);
17838 GetSocial()->SendSocialList();
17840 // Homebind
17841 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17842 data << m_homebindX << m_homebindY << m_homebindZ;
17843 data << (uint32) m_homebindMapId;
17844 data << (uint32) m_homebindZoneId;
17845 GetSession()->SendPacket(&data);
17847 // SMSG_SET_PROFICIENCY
17848 // SMSG_UPDATE_AURA_DURATION
17850 SendTalentsInfoData(false);
17851 SendInitialSpells();
17853 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17854 data << uint32(0); // count, for(count) uint32;
17855 GetSession()->SendPacket(&data);
17857 SendInitialActionButtons();
17858 m_reputationMgr.SendInitialReputations();
17859 m_achievementMgr.SendAllAchievementData();
17861 // update zone
17862 uint32 newzone, newarea;
17863 GetZoneAndAreaId(newzone,newarea);
17864 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
17866 SendEquipmentSetList();
17868 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17869 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17870 data << (float)0.01666667f; // game speed
17871 data << uint32(0); // added in 3.1.2
17872 GetSession()->SendPacket( &data );
17874 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17875 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17876 m_movementInfo.flags |= MOVEMENTFLAG_FLYING2;
17878 m_mover = this;
17881 void Player::SendInitialPacketsAfterAddToMap()
17883 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17884 data << uint32(0x00000000); // on blizz it increments periodically
17885 GetSession()->SendPacket(&data);
17887 CastSpell(this, 836, true); // LOGINEFFECT
17889 // set some aura effects that send packet to player client after add player to map
17890 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17891 // same auras state lost at far teleport, send it one more time in this case also
17892 static const AuraType auratypes[] =
17894 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17895 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17896 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17898 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17900 Unit::AuraList const& auraList = GetAurasByType(*itr);
17901 if(!auraList.empty())
17902 auraList.front()->ApplyModifier(true,true);
17905 if(HasAuraType(SPELL_AURA_MOD_STUN))
17906 SetMovement(MOVE_ROOT);
17908 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17909 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17911 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
17912 data2.append(GetPackGUID());
17913 data2 << (uint32)2;
17914 SendMessageToSet(&data2,true);
17917 SendAurasForTarget(this);
17918 SendEnchantmentDurations(); // must be after add to map
17919 SendItemDurations(); // must be after add to map
17922 void Player::SendUpdateToOutOfRangeGroupMembers()
17924 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17925 return;
17926 if(Group* group = GetGroup())
17927 group->UpdatePlayerOutOfRange(this);
17929 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17930 m_auraUpdateMask = 0;
17931 if(Pet *pet = GetPet())
17932 pet->ResetAuraUpdateMask();
17935 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17937 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17938 data << uint32(mapid);
17939 data << uint8(reason); // transfer abort reason
17940 switch(reason)
17942 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17943 case TRANSFER_ABORT_DIFFICULTY:
17944 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17945 data << uint8(arg);
17946 break;
17948 GetSession()->SendPacket(&data);
17951 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17953 // type of warning, based on the time remaining until reset
17954 uint32 type;
17955 if(time > 3600)
17956 type = RAID_INSTANCE_WELCOME;
17957 else if(time > 900 && time <= 3600)
17958 type = RAID_INSTANCE_WARNING_HOURS;
17959 else if(time > 300 && time <= 900)
17960 type = RAID_INSTANCE_WARNING_MIN;
17961 else
17962 type = RAID_INSTANCE_WARNING_MIN_SOON;
17963 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17964 data << uint32(type);
17965 data << uint32(mapid);
17966 data << uint32(time);
17967 GetSession()->SendPacket(&data);
17970 void Player::ApplyEquipCooldown( Item * pItem )
17972 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
17974 _Spell const& spellData = pItem->GetProto()->Spells[i];
17976 // no spell
17977 if( !spellData.SpellId )
17978 continue;
17980 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17981 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17982 continue;
17984 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17986 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17987 data << pItem->GetGUID();
17988 data << uint32(spellData.SpellId);
17989 GetSession()->SendPacket(&data);
17993 void Player::resetSpells()
17995 // not need after this call
17996 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17998 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17999 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
18002 // make full copy of map (spells removed and marked as deleted at another spell remove
18003 // and we can't use original map for safe iterative with visit each spell at loop end
18004 PlayerSpellMap smap = GetSpellMap();
18006 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18007 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
18009 learnDefaultSpells();
18010 learnQuestRewardedSpells();
18013 void Player::learnDefaultSpells()
18015 // learn default race/class spells
18016 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18017 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18019 uint32 tspell = *itr;
18020 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18021 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18022 addSpell(tspell,true,true,true,false);
18023 else // but send in normal spell in game learn case
18024 learnSpell(tspell,true);
18028 void Player::learnQuestRewardedSpells(Quest const* quest)
18030 uint32 spell_id = quest->GetRewSpellCast();
18032 // skip quests without rewarded spell
18033 if( !spell_id )
18034 return;
18036 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18037 if(!spellInfo)
18038 return;
18040 // check learned spells state
18041 bool found = false;
18042 for(int i=0; i < 3; ++i)
18044 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18046 found = true;
18047 break;
18051 // skip quests with not teaching spell or already known spell
18052 if(!found)
18053 return;
18055 // prevent learn non first rank unknown profession and second specialization for same profession)
18056 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18057 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18059 // not have first rank learned (unlearned prof?)
18060 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18061 if( !HasSpell(first_spell) )
18062 return;
18064 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18065 if(!learnedInfo)
18066 return;
18068 // specialization
18069 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18071 // search other specialization for same prof
18072 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18074 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18075 continue;
18077 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18078 if(!itrInfo)
18079 return;
18081 // compare only specializations
18082 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18083 continue;
18085 // compare same chain spells
18086 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18087 continue;
18089 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18090 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18091 return;
18096 CastSpell( this, spell_id, true);
18099 void Player::learnQuestRewardedSpells()
18101 // learn spells received from quest completing
18102 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18104 // skip no rewarded quests
18105 if(!itr->second.m_rewarded)
18106 continue;
18108 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18109 if( !quest )
18110 continue;
18112 learnQuestRewardedSpells(quest);
18116 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18118 uint32 raceMask = getRaceMask();
18119 uint32 classMask = getClassMask();
18120 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18122 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18123 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18124 continue;
18125 // Check race if set
18126 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18127 continue;
18128 // Check class if set
18129 if (pAbility->classmask && !(pAbility->classmask & classMask))
18130 continue;
18132 if (sSpellStore.LookupEntry(pAbility->spellId))
18134 // need unlearn spell
18135 if (skill_value < pAbility->req_skill_value)
18136 removeSpell(pAbility->spellId);
18137 // need learn
18138 else if (!IsInWorld())
18139 addSpell(pAbility->spellId,true,true,true,false);
18140 else
18141 learnSpell(pAbility->spellId,true);
18146 void Player::SendAurasForTarget(Unit *target)
18148 if(target->GetVisibleAuras()->empty()) // speedup things
18149 return;
18151 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18152 data.append(target->GetPackGUID());
18154 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18155 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18157 for(uint32 j = 0; j < 3; ++j)
18159 if(Aura *aura = target->GetAura(itr->second, j))
18161 data << uint8(aura->GetAuraSlot());
18162 data << uint32(aura->GetId());
18164 if(aura->GetId())
18166 uint8 auraFlags = aura->GetAuraFlags();
18167 // flags
18168 data << uint8(auraFlags);
18169 // level
18170 data << uint8(aura->GetAuraLevel());
18171 // charges
18172 data << uint8(aura->GetAuraCharges());
18174 if(!(auraFlags & AFLAG_NOT_CASTER))
18176 data << uint8(0); // packed GUID of someone (caster?)
18179 if(auraFlags & AFLAG_DURATION) // include aura duration
18181 data << uint32(aura->GetAuraMaxDuration());
18182 data << uint32(aura->GetAuraDuration());
18185 break;
18190 GetSession()->SendPacket(&data);
18193 void Player::SetDailyQuestStatus( uint32 quest_id )
18195 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18197 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18199 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18200 m_lastDailyQuestTime = time(NULL); // last daily quest time
18201 m_DailyQuestChanged = true;
18202 break;
18207 void Player::ResetDailyQuestStatus()
18209 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18210 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18212 // DB data deleted in caller
18213 m_DailyQuestChanged = false;
18214 m_lastDailyQuestTime = 0;
18217 BattleGround* Player::GetBattleGround() const
18219 if(GetBattleGroundId()==0)
18220 return NULL;
18222 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
18225 bool Player::InArena() const
18227 BattleGround *bg = GetBattleGround();
18228 if(!bg || !bg->isArena())
18229 return false;
18231 return true;
18234 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18236 // get a template bg instead of running one
18237 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18238 if(!bg)
18239 return false;
18241 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18242 return false;
18244 return true;
18247 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18249 //returned to hardcoded version of this function, because there is no way to code it dynamic
18250 uint32 level = getLevel();
18251 if( bgTypeId == BATTLEGROUND_AV )
18252 level--;
18254 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18255 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18257 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18258 return QUEUE_ID_MAX_LEVEL_80;
18260 return BGQueueIdBasedOnLevel(queue_id);
18263 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18265 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18266 if(!vendor_faction || !vendor_faction->faction)
18267 return 1.0f;
18269 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18270 if(rank <= REP_NEUTRAL)
18271 return 1.0f;
18273 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18276 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18278 uint32 racemask = getRaceMask();
18279 uint32 classmask = getClassMask();
18281 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18282 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18283 if(lower==upper)
18284 return true;
18286 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18288 // skip wrong race skills
18289 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18290 continue;
18292 // skip wrong class skills
18293 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18294 continue;
18296 return true;
18299 return false;
18302 bool Player::HasQuestForGO(int32 GOId) const
18304 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18306 uint32 questid = GetQuestSlotQuestId(i);
18307 if ( questid == 0 )
18308 continue;
18310 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18311 if(qs_itr == mQuestStatus.end())
18312 continue;
18314 QuestStatusData const& qs = qs_itr->second;
18316 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18318 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18319 if(!qinfo)
18320 continue;
18322 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18323 continue;
18325 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
18327 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18328 continue;
18330 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18331 return true;
18335 return false;
18338 void Player::UpdateForQuestWorldObjects()
18340 if(m_clientGUIDs.empty())
18341 return;
18343 UpdateData udata;
18344 WorldPacket packet;
18345 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18347 if(IS_GAMEOBJECT_GUID(*itr))
18349 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18350 if(obj)
18351 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18353 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
18355 Creature *obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
18356 if(!obj)
18357 continue;
18358 // check if this unit requires quest specific flags
18360 SpellClickInfoMap const& map = objmgr.mSpellClickInfoMap;
18361 for(SpellClickInfoMap::const_iterator itr = map.lower_bound(obj->GetEntry()); itr != map.upper_bound(obj->GetEntry()); ++itr)
18363 if(itr->second.questId != 0)
18365 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
18366 break;
18372 udata.BuildPacket(&packet);
18373 GetSession()->SendPacket(&packet);
18376 void Player::SummonIfPossible(bool agree)
18378 if(!agree)
18380 m_summon_expire = 0;
18381 return;
18384 // expire and auto declined
18385 if(m_summon_expire < time(NULL))
18386 return;
18388 // stop taxi flight at summon
18389 if(isInFlight())
18391 GetMotionMaster()->MovementExpired();
18392 m_taxi.ClearTaxiDestinations();
18395 // drop flag at summon
18396 // 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
18397 if(BattleGround *bg = GetBattleGround())
18398 bg->EventPlayerDroppedFlag(this);
18400 m_summon_expire = 0;
18402 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
18404 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18407 void Player::RemoveItemDurations( Item *item )
18409 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18411 if(*itr==item)
18413 m_itemDuration.erase(itr);
18414 break;
18419 void Player::AddItemDurations( Item *item )
18421 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18423 m_itemDuration.push_back(item);
18424 item->SendTimeUpdate(this);
18428 void Player::AutoUnequipOffhandIfNeed()
18430 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18431 if(!offItem)
18432 return;
18434 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18435 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18436 return;
18438 ItemPosCountVec off_dest;
18439 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18440 if( off_msg == EQUIP_ERR_OK )
18442 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18443 StoreItem( off_dest, offItem, true );
18445 else
18447 MailItemsInfo mi;
18448 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18449 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18450 CharacterDatabase.BeginTransaction();
18451 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18452 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18453 CharacterDatabase.CommitTransaction();
18455 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18456 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18460 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18462 if(spellInfo->EquippedItemClass < 0)
18463 return true;
18465 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18466 // for optimize check 2 used cases only
18467 switch(spellInfo->EquippedItemClass)
18469 case ITEM_CLASS_WEAPON:
18471 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18472 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18473 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18474 return true;
18475 break;
18477 case ITEM_CLASS_ARMOR:
18479 // tabard not have dependent spells
18480 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18481 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18482 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18483 return true;
18485 // shields can be equipped to offhand slot
18486 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18487 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18488 return true;
18490 // ranged slot can have some armor subclasses
18491 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18492 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18493 return true;
18495 break;
18497 default:
18498 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18499 break;
18502 return false;
18505 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18507 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18508 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18509 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18510 return true;
18512 // Check no reagent use mask
18513 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18514 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18515 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18516 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18517 return true;
18519 return false;
18522 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18524 AuraMap& auras = GetAuras();
18525 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
18527 Aura* aura = itr->second;
18529 // skip passive (passive item dependent spells work in another way) and not self applied auras
18530 SpellEntry const* spellInfo = aura->GetSpellProto();
18531 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18533 ++itr;
18534 continue;
18537 // skip if not item dependent or have alternative item
18538 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18540 ++itr;
18541 continue;
18544 // no alt item, remove aura, restart check
18545 RemoveAurasDueToSpell(aura->GetId());
18546 itr = auras.begin();
18549 // currently casted spells can be dependent from item
18550 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
18552 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18553 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18554 InterruptSpell(i);
18558 uint32 Player::GetResurrectionSpellId()
18560 // search priceless resurrection possibilities
18561 uint32 prio = 0;
18562 uint32 spell_id = 0;
18563 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18564 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18566 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18567 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18569 switch((*itr)->GetId())
18571 case 20707: spell_id = 3026; break; // rank 1
18572 case 20762: spell_id = 20758; break; // rank 2
18573 case 20763: spell_id = 20759; break; // rank 3
18574 case 20764: spell_id = 20760; break; // rank 4
18575 case 20765: spell_id = 20761; break; // rank 5
18576 case 27239: spell_id = 27240; break; // rank 6
18577 case 47883: spell_id = 47882; break; // rank 7
18578 default:
18579 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
18580 continue;
18583 prio = 3;
18585 // Twisting Nether // prio: 2 (max)
18586 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18588 prio = 2;
18589 spell_id = 23700;
18593 // Reincarnation (passive spell) // prio: 1
18594 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18595 spell_id = 21169;
18597 return spell_id;
18600 // Used in triggers for check "Only to targets that grant experience or honor" req
18601 bool Player::isHonorOrXPTarget(Unit* pVictim)
18603 uint32 v_level = pVictim->getLevel();
18604 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18606 // Victim level less gray level
18607 if(v_level<=k_grey)
18608 return false;
18610 if(pVictim->GetTypeId() == TYPEID_UNIT)
18612 if (((Creature*)pVictim)->isTotem() ||
18613 ((Creature*)pVictim)->isPet() ||
18614 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18615 return false;
18617 return true;
18620 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18622 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18624 // prepare data for near group iteration (PvP and !PvP cases)
18625 uint32 xp = 0;
18626 bool honored_kill = false;
18628 if(Group *pGroup = GetGroup())
18630 uint32 count = 0;
18631 uint32 sum_level = 0;
18632 Player* member_with_max_level = NULL;
18633 Player* not_gray_member_with_max_level = NULL;
18635 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18637 if(member_with_max_level)
18639 /// not get Xp in PvP or no not gray players in group
18640 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18642 /// skip in check PvP case (for speed, not used)
18643 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18644 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18645 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18647 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18649 Player* pGroupGuy = itr->getSource();
18650 if(!pGroupGuy)
18651 continue;
18653 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18654 continue; // member (alive or dead) or his corpse at req. distance
18656 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18657 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18658 honored_kill = true;
18660 // xp and reputation only in !PvP case
18661 if(!PvP)
18663 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18665 // if is in dungeon then all receive full reputation at kill
18666 // rewarded any alive/dead/near_corpse group member
18667 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18669 // XP updated only for alive group member
18670 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18671 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18673 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18675 pGroupGuy->GiveXP(itr_xp, pVictim);
18676 if(Pet* pet = pGroupGuy->GetPet())
18677 pet->GivePetXP(itr_xp/2);
18680 // quest objectives updated only for alive group member or dead but with not released body
18681 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18683 // normal creature (not pet/etc) can be only in !PvP case
18684 if(pVictim->GetTypeId()==TYPEID_UNIT)
18685 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18691 else // if (!pGroup)
18693 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18695 // honor can be in PvP and !PvP (racial leader) cases
18696 if(RewardHonor(pVictim,1))
18697 honored_kill = true;
18699 // xp and reputation only in !PvP case
18700 if(!PvP)
18702 RewardReputation(pVictim,1);
18703 GiveXP(xp, pVictim);
18705 if(Pet* pet = GetPet())
18706 pet->GivePetXP(xp);
18708 // normal creature (not pet/etc) can be only in !PvP case
18709 if(pVictim->GetTypeId()==TYPEID_UNIT)
18710 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18713 return xp || honored_kill;
18716 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
18718 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
18720 // prepare data for near group iteration
18721 if(Group *pGroup = GetGroup())
18723 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18725 Player* pGroupGuy = itr->getSource();
18726 if(!pGroupGuy)
18727 continue;
18729 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
18730 continue; // member (alive or dead) or his corpse at req. distance
18732 // quest objectives updated only for alive group member or dead but with not released body
18733 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18734 pGroupGuy->KilledMonster(creature_id, creature_guid);
18737 else // if (!pGroup)
18738 KilledMonster(creature_id, creature_guid);
18741 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18743 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
18744 return true;
18746 if (isAlive())
18747 return false;
18749 Corpse* corpse = GetCorpse();
18750 if (!corpse)
18751 return false;
18753 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
18756 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18758 Item* item = GetWeaponForAttack(attType,true);
18760 // unarmed only with base attack
18761 if(attType != BASE_ATTACK && !item)
18762 return 0;
18764 // weapon skill or (unarmed for base attack)
18765 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
18766 return GetBaseSkillValue(skill);
18769 void Player::ResurectUsingRequestData()
18771 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18772 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18774 ResurrectPlayer(0.0f,false);
18776 if(GetMaxHealth() > m_resurrectHealth)
18777 SetHealth( m_resurrectHealth );
18778 else
18779 SetHealth( GetMaxHealth() );
18781 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18782 SetPower(POWER_MANA, m_resurrectMana );
18783 else
18784 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18786 SetPower(POWER_RAGE, 0 );
18788 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18790 SpawnCorpseBones();
18793 void Player::SetClientControl(Unit* target, uint8 allowMove)
18795 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18796 data.append(target->GetPackGUID());
18797 data << uint8(allowMove);
18798 GetSession()->SendPacket(&data);
18801 void Player::UpdateZoneDependentAuras( uint32 newZone )
18803 // remove new continent flight forms
18804 if( !IsAllowUseFlyMountsHere() )
18806 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18807 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18810 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18811 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
18812 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18813 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
18814 if( !HasAura(itr->second->spellId,0) )
18815 CastSpell(this,itr->second->spellId,true);
18818 void Player::UpdateAreaDependentAuras( uint32 newArea )
18820 // remove auras from spells with area limitations
18821 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18823 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18824 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
18825 RemoveAura(iter);
18826 else
18827 ++iter;
18830 // some auras applied at subzone enter
18831 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
18832 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18833 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
18834 if( !HasAura(itr->second->spellId,0) )
18835 CastSpell(this,itr->second->spellId,true);
18838 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18840 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18841 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18843 return copseReclaimDelay[0];
18846 time_t now = time(NULL);
18847 // 0..2 full period
18848 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18849 return copseReclaimDelay[count];
18852 void Player::UpdateCorpseReclaimDelay()
18854 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18856 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18857 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18858 return;
18860 time_t now = time(NULL);
18861 if(now < m_deathExpireTime)
18863 // full and partly periods 1..3
18864 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18865 if(count < MAX_DEATH_COUNT)
18866 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18867 else
18868 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18870 else
18871 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18874 void Player::SendCorpseReclaimDelay(bool load)
18876 Corpse* corpse = GetCorpse();
18877 if(!corpse)
18878 return;
18880 uint32 delay;
18881 if(load)
18883 if(corpse->GetGhostTime() > m_deathExpireTime)
18884 return;
18886 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18888 uint32 count;
18889 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18890 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18892 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18893 if(count>=MAX_DEATH_COUNT)
18894 count = MAX_DEATH_COUNT-1;
18896 else
18897 count=0;
18899 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18901 time_t now = time(NULL);
18902 if(now >= expected_time)
18903 return;
18905 delay = expected_time-now;
18907 else
18908 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18910 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18911 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18912 data << uint32(delay*IN_MILISECONDS);
18913 GetSession()->SendPacket( &data );
18916 Player* Player::GetNextRandomRaidMember(float radius)
18918 Group *pGroup = GetGroup();
18919 if(!pGroup)
18920 return NULL;
18922 std::vector<Player*> nearMembers;
18923 nearMembers.reserve(pGroup->GetMembersCount());
18925 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18927 Player* Target = itr->getSource();
18929 // IsHostileTo check duel and controlled by enemy
18930 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18931 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18932 nearMembers.push_back(Target);
18935 if (nearMembers.empty())
18936 return NULL;
18938 uint32 randTarget = urand(0,nearMembers.size()-1);
18939 return nearMembers[randTarget];
18942 PartyResult Player::CanUninviteFromGroup() const
18944 const Group* grp = GetGroup();
18945 if(!grp)
18946 return PARTY_RESULT_YOU_NOT_IN_GROUP;
18948 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
18949 return PARTY_RESULT_YOU_NOT_LEADER;
18951 if(InBattleGround())
18952 return PARTY_RESULT_INVITE_RESTRICTED;
18954 return PARTY_RESULT_OK;
18957 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
18959 //we must move references from m_group to m_originalGroup
18960 SetOriginalGroup(GetGroup(), GetSubGroup());
18962 m_group.unlink();
18963 m_group.link(group, this);
18964 m_group.setSubGroup((uint8)subgroup);
18967 void Player::RemoveFromBattleGroundRaid()
18969 //remove existing reference
18970 m_group.unlink();
18971 if( Group* group = GetOriginalGroup() )
18973 m_group.link(group, this);
18974 m_group.setSubGroup(GetOriginalSubGroup());
18976 SetOriginalGroup(NULL);
18979 void Player::SetOriginalGroup(Group *group, int8 subgroup)
18981 if( group == NULL )
18982 m_originalGroup.unlink();
18983 else
18985 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
18986 assert(subgroup >= 0);
18987 m_originalGroup.link(group, this);
18988 m_originalGroup.setSubGroup((uint8)subgroup);
18992 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18994 LiquidData liquid_status;
18995 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
18996 if (!res)
18998 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
18999 // Small hack for enable breath in WMO
19000 if (IsInWater())
19001 m_MirrorTimerFlags|=UNDERWATER_INWATER;
19002 return;
19005 // All liquids type - check under water position
19006 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
19008 if ( res & LIQUID_MAP_UNDER_WATER)
19009 m_MirrorTimerFlags |= UNDERWATER_INWATER;
19010 else
19011 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
19014 // Allow travel in dark water on taxi or transport
19015 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
19016 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
19017 else
19018 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
19020 // in lava check, anywhere in lava level
19021 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
19023 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19024 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
19025 else
19026 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
19028 // in slime check, anywhere in slime level
19029 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
19031 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19032 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
19033 else
19034 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
19038 void Player::SetCanParry( bool value )
19040 if(m_canParry==value)
19041 return;
19043 m_canParry = value;
19044 UpdateParryPercentage();
19047 void Player::SetCanBlock( bool value )
19049 if(m_canBlock==value)
19050 return;
19052 m_canBlock = value;
19053 UpdateBlockPercentage();
19056 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19058 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19059 if(itr->pos == pos)
19060 return true;
19062 return false;
19065 bool Player::CanUseBattleGroundObject()
19067 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19068 // maybe gameobject code should handle that ForceReaction usage
19069 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19070 return ( //InBattleGround() && // in battleground - not need, check in other cases
19071 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19072 //player cannot use object when he is invulnerable (immune)
19073 !isTotalImmune() && // not totally immune
19074 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19075 !HasStealthAura() && // not stealthed
19076 !HasInvisibilityAura() && // not invisible
19077 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19078 isAlive() // live player
19082 bool Player::CanCaptureTowerPoint()
19084 return ( !HasStealthAura() && // not stealthed
19085 !HasInvisibilityAura() && // not invisible
19086 isAlive() // live player
19090 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19092 uint32 level = getLevel();
19094 if(level > GT_MAX_LEVEL)
19095 level = GT_MAX_LEVEL; // max level in this dbc
19097 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19098 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19099 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19101 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19102 return 0;
19104 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19106 if(!bsc) // shouldn't happen
19107 return 0xFFFFFFFF;
19109 float cost = 0;
19111 if(hairstyle != newhairstyle)
19112 cost += bsc->cost; // full price
19114 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19115 cost += bsc->cost * 0.5f; // +1/2 of price
19117 if(facialhair != newfacialhair)
19118 cost += bsc->cost * 0.75f; // +3/4 of price
19120 return uint32(cost);
19123 void Player::InitGlyphsForLevel()
19125 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19126 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19127 if(gs->Order)
19128 SetGlyphSlot(gs->Order - 1, gs->Id);
19130 uint32 level = getLevel();
19131 uint32 value = 0;
19133 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19134 if(level >= 15)
19135 value |= (0x01 | 0x02);
19136 if(level >= 30)
19137 value |= 0x08;
19138 if(level >= 50)
19139 value |= 0x04;
19140 if(level >= 70)
19141 value |= 0x10;
19142 if(level >= 80)
19143 value |= 0x20;
19145 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19148 void Player::EnterVehicle(Vehicle *vehicle)
19150 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19151 if(!ve)
19152 return;
19154 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19155 if(!veSeat)
19156 return;
19158 vehicle->SetCharmerGUID(GetGUID());
19159 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19160 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19161 vehicle->setFaction(getFaction());
19163 SetCharm(vehicle); // charm
19164 SetFarSightGUID(vehicle->GetGUID()); // set view
19166 SetClientControl(vehicle, 1); // redirect controls to vehicle
19168 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19169 GetSession()->SendPacket(&data);
19171 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19172 data.append(GetPackGUID());
19173 data << uint32(0); // counter?
19174 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19175 data << uint16(0); // special flags
19176 data << uint32(getMSTime()); // time
19177 data << vehicle->GetPositionX(); // x
19178 data << vehicle->GetPositionY(); // y
19179 data << vehicle->GetPositionZ(); // z
19180 data << vehicle->GetOrientation(); // o
19181 // transport part, TODO: load/calculate seat offsets
19182 data << uint64(vehicle->GetGUID()); // transport guid
19183 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19184 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19185 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19186 data << float(0); // transport orientation
19187 data << uint32(getMSTime()); // transport time
19188 data << uint8(0); // seat
19189 // end of transport part
19190 data << uint32(0); // fall time
19191 GetSession()->SendPacket(&data);
19193 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*10+1+1);
19194 data << uint64(vehicle->GetGUID());
19195 data << uint16(0);
19196 data << uint32(0);
19197 data << uint32(0x00000101);
19199 for(uint32 i = 0; i < 10; ++i)
19200 data << uint16(0) << uint8(0) << uint8(i+8);
19202 data << uint8(0);
19203 data << uint8(0);
19204 GetSession()->SendPacket(&data);
19207 void Player::ExitVehicle(Vehicle *vehicle)
19209 vehicle->SetCharmerGUID(0);
19210 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19211 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19212 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19214 SetCharm(NULL);
19215 SetFarSightGUID(0);
19217 SetClientControl(vehicle, 0);
19219 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19220 data.append(GetPackGUID());
19221 data << uint32(0); // counter?
19222 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19223 data << uint16(0x40); // special flags
19224 data << uint32(getMSTime()); // time
19225 data << vehicle->GetPositionX(); // x
19226 data << vehicle->GetPositionY(); // y
19227 data << vehicle->GetPositionZ(); // z
19228 data << vehicle->GetOrientation(); // o
19229 data << uint32(0); // fall time
19230 GetSession()->SendPacket(&data);
19232 data.Initialize(SMSG_PET_SPELLS, 8);
19233 data << uint64(0);
19234 GetSession()->SendPacket(&data);
19236 // maybe called at dummy aura remove?
19237 // CastSpell(this, 45472, true); // Parachute
19240 bool Player::isTotalImmune()
19242 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19244 uint32 immuneMask = 0;
19245 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19247 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19248 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19249 return true;
19251 return false;
19254 bool Player::HasTitle(uint32 bitIndex)
19256 if (bitIndex > 192)
19257 return false;
19259 uint32 fieldIndexOffset = bitIndex / 32;
19260 uint32 flag = 1 << (bitIndex % 32);
19261 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19264 void Player::SetTitle(CharTitlesEntry const* title)
19266 uint32 fieldIndexOffset = title->bit_index / 32;
19267 uint32 flag = 1 << (title->bit_index % 32);
19268 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19271 void Player::ConvertRune(uint8 index, uint8 newType)
19273 SetCurrentRune(index, newType);
19275 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19276 data << uint8(index);
19277 data << uint8(newType);
19278 GetSession()->SendPacket(&data);
19281 void Player::ResyncRunes(uint8 count)
19283 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19284 for(uint32 i = 0; i < count; ++i)
19286 data << uint8(GetCurrentRune(i)); // rune type
19287 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19289 GetSession()->SendPacket(&data);
19292 void Player::AddRunePower(uint8 index)
19294 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19295 data << uint32(1 << index); // mask (0x00-0x3F probably)
19296 GetSession()->SendPacket(&data);
19299 void Player::InitRunes()
19301 if(getClass() != CLASS_DEATH_KNIGHT)
19302 return;
19304 m_runes = new Runes;
19306 m_runes->runeState = 0;
19308 for(uint32 i = 0; i < MAX_RUNES; ++i)
19310 SetBaseRune(i, i / 2); // init base types
19311 SetCurrentRune(i, i / 2); // init current types
19312 SetRuneCooldown(i, 0); // reset cooldowns
19313 m_runes->SetRuneState(i);
19316 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19317 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19320 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19322 Loot loot;
19323 loot.FillLoot (loot_id,store,this,true);
19325 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19326 for(uint32 i = 0; i < max_slot; ++i)
19328 LootItem* lootItem = loot.LootItemInSlot(i,this);
19330 ItemPosCountVec dest;
19331 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19332 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19333 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19334 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19335 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19336 if(msg != EQUIP_ERR_OK)
19338 SendEquipError( msg, NULL, NULL );
19339 continue;
19342 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19343 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19347 uint32 Player::CalculateTalentsPoints() const
19349 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19351 if(getClass() != CLASS_DEATH_KNIGHT)
19352 return base_talent;
19354 uint32 talentPointsForLevel =
19355 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19356 + m_questRewardTalentCount;
19358 if(talentPointsForLevel > base_talent)
19359 talentPointsForLevel = base_talent;
19361 return talentPointsForLevel;
19364 bool Player::IsAllowUseFlyMountsHere() const
19366 if (isGameMaster())
19367 return true;
19369 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19370 return v_map == 530 || v_map == 571 && HasSpell(54197);
19373 void Player::learnSpellHighRank(uint32 spellid)
19375 learnSpell(spellid,false);
19377 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19378 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19379 learnSpellHighRank(itr->second);
19382 void Player::_LoadSkills()
19384 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19386 // reset skill modifiers and set correct unlearn flags
19387 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
19389 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19391 // set correct unlearn bit
19392 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19393 if(!id) continue;
19395 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19396 if(!pSkill) continue;
19398 // enable unlearn button for primary professions only
19399 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19400 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19401 else
19402 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19404 // set fixed skill ranges
19405 switch(GetSkillRangeType(pSkill,false))
19407 case SKILL_RANGE_LANGUAGE: // 300..300
19408 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19409 break;
19410 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19411 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19412 break;
19413 default:
19414 break;
19417 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19418 learnSkillRewardedSpells(id, vskill);
19421 // special settings
19422 if(getClass()==CLASS_DEATH_KNIGHT)
19424 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19425 if(base_level < 1)
19426 base_level = 1;
19427 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19428 if(base_skill < 1)
19429 base_skill = 1; // skill mast be known and then > 0 in any case
19431 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19432 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19433 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19434 SetSkill(SKILL_AXES, base_skill,base_skill);
19435 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19436 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19437 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19438 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19439 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19440 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19441 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19442 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19443 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19444 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19445 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19446 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19450 uint32 Player::GetPhaseMaskForSpawn() const
19452 uint32 phase = PHASEMASK_NORMAL;
19453 if(!isGameMaster())
19454 phase = GetPhaseMask();
19455 else
19457 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19458 if(!phases.empty())
19459 phase = phases.front()->GetMiscValue();
19462 // some aura phases include 1 normal map in addition to phase itself
19463 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19464 return n_phase;
19466 return PHASEMASK_NORMAL;
19469 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19471 ItemPrototype const* pProto = pItem->GetProto();
19473 // proto based limitations
19474 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19475 return res;
19477 // check unique-equipped on gems
19478 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19480 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19481 if(!enchant_id)
19482 continue;
19483 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19484 if(!enchantEntry)
19485 continue;
19487 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19488 if(!pGem)
19489 continue;
19491 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19492 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19493 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19495 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19496 return res;
19499 return EQUIP_ERR_OK;
19502 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19504 // check unique-equipped on item
19505 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19507 // there is an equip limit on this item
19508 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19509 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19512 // check unique-equipped limit
19513 if (itemProto->ItemLimitCategory)
19515 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19516 if(!limitEntry)
19517 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19519 if(limit_count > limitEntry->maxCount)
19520 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19522 // there is an equip limit on this item
19523 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19524 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19527 return EQUIP_ERR_OK;
19530 void Player::HandleFall(MovementInfo const& movementInfo)
19532 // calculate total z distance of the fall
19533 float z_diff = m_lastFallZ - movementInfo.z;
19534 sLog.outDebug("zDiff = %f", z_diff);
19536 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19537 // 14.57 can be calculated by resolving damageperc formula below to 0
19538 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19539 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19540 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19542 //Safe fall, fall height reduction
19543 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19545 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19547 if(damageperc >0 )
19549 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19551 float height = movementInfo.z;
19552 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19554 if (damage > 0)
19556 //Prevent fall damage from being more than the player maximum health
19557 if (damage > GetMaxHealth())
19558 damage = GetMaxHealth();
19560 // Gust of Wind
19561 if (GetDummyAura(43621))
19562 damage = GetMaxHealth()/2;
19564 EnvironmentalDamage(DAMAGE_FALL, damage);
19566 // recheck alive, might have died of EnvironmentalDamage
19567 if (isAlive())
19568 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19571 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19572 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.z, height, GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall);
19577 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19579 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
19582 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
19584 uint32 CurTalentPoints = GetFreeTalentPoints();
19586 if(CurTalentPoints == 0)
19587 return;
19589 if (talentRank >= MAX_TALENT_RANK)
19590 return;
19592 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
19594 if(!talentInfo)
19595 return;
19597 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
19599 if(!talentTabInfo)
19600 return;
19602 // prevent learn talent for different class (cheating)
19603 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
19604 return;
19606 // find current max talent rank
19607 int32 curtalent_maxrank = 0;
19608 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19610 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19612 curtalent_maxrank = k + 1;
19613 break;
19617 // we already have same or higher talent rank learned
19618 if(curtalent_maxrank >= (talentRank + 1))
19619 return;
19621 // check if we have enough talent points
19622 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19623 return;
19625 // Check if it requires another talent
19626 if (talentInfo->DependsOn > 0)
19628 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19630 bool hasEnoughRank = false;
19631 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19633 if (depTalentInfo->RankID[i] != 0)
19634 if (HasSpell(depTalentInfo->RankID[i]))
19635 hasEnoughRank = true;
19637 if (!hasEnoughRank)
19638 return;
19642 // Find out how many points we have in this field
19643 uint32 spentPoints = 0;
19645 uint32 tTab = talentInfo->TalentTab;
19646 if (talentInfo->Row > 0)
19648 unsigned int numRows = sTalentStore.GetNumRows();
19649 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19651 // Someday, someone needs to revamp
19652 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19653 if (tmpTalent) // the way talents are tracked
19655 if (tmpTalent->TalentTab == tTab)
19657 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19659 if (tmpTalent->RankID[j] != 0)
19661 if (HasSpell(tmpTalent->RankID[j]))
19663 spentPoints += j + 1;
19672 // not have required min points spent in talent tree
19673 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
19674 return;
19676 // spell not set in talent.dbc
19677 uint32 spellid = talentInfo->RankID[talentRank];
19678 if( spellid == 0 )
19680 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19681 return;
19684 // already known
19685 if(HasSpell(spellid))
19686 return;
19688 // learn! (other talent ranks will unlearned at learning)
19689 learnSpell(spellid, false);
19690 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19692 // update free talent points
19693 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19696 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
19698 Pet *pet = GetPet();
19700 if(!pet)
19701 return;
19703 if(petGuid != pet->GetGUID())
19704 return;
19706 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
19708 if(CurTalentPoints == 0)
19709 return;
19711 if (talentRank >= MAX_PET_TALENT_RANK)
19712 return;
19714 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
19716 if(!talentInfo)
19717 return;
19719 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
19721 if(!talentTabInfo)
19722 return;
19724 CreatureInfo const *ci = pet->GetCreatureInfo();
19726 if(!ci)
19727 return;
19729 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19731 if(!pet_family)
19732 return;
19734 if(pet_family->petTalentType < 0) // not hunter pet
19735 return;
19737 // prevent learn talent for different family (cheating)
19738 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19739 return;
19741 // find current max talent rank
19742 int32 curtalent_maxrank = 0;
19743 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19745 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
19747 curtalent_maxrank = k + 1;
19748 break;
19752 // we already have same or higher talent rank learned
19753 if(curtalent_maxrank >= (talentRank + 1))
19754 return;
19756 // check if we have enough talent points
19757 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19758 return;
19760 // Check if it requires another talent
19761 if (talentInfo->DependsOn > 0)
19763 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19765 bool hasEnoughRank = false;
19766 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19768 if (depTalentInfo->RankID[i] != 0)
19769 if (pet->HasSpell(depTalentInfo->RankID[i]))
19770 hasEnoughRank = true;
19772 if (!hasEnoughRank)
19773 return;
19777 // Find out how many points we have in this field
19778 uint32 spentPoints = 0;
19780 uint32 tTab = talentInfo->TalentTab;
19781 if (talentInfo->Row > 0)
19783 unsigned int numRows = sTalentStore.GetNumRows();
19784 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19786 // Someday, someone needs to revamp
19787 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19788 if (tmpTalent) // the way talents are tracked
19790 if (tmpTalent->TalentTab == tTab)
19792 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19794 if (tmpTalent->RankID[j] != 0)
19796 if (pet->HasSpell(tmpTalent->RankID[j]))
19798 spentPoints += j + 1;
19807 // not have required min points spent in talent tree
19808 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
19809 return;
19811 // spell not set in talent.dbc
19812 uint32 spellid = talentInfo->RankID[talentRank];
19813 if( spellid == 0 )
19815 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19816 return;
19819 // already known
19820 if(pet->HasSpell(spellid))
19821 return;
19823 // learn! (other talent ranks will unlearned at learning)
19824 pet->learnSpell(spellid);
19825 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19827 // update free talent points
19828 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19831 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
19833 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
19835 if(apply)
19836 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
19837 else
19838 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
19842 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
19844 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
19845 SetFallInformation(minfo.fallTime, minfo.z);
19848 void Player::UnsummonPetTemporaryIfAny()
19850 Pet* pet = GetPet();
19851 if(!pet)
19852 return;
19854 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
19856 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
19857 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
19860 RemovePet(pet, PET_SAVE_AS_CURRENT);
19863 void Player::ResummonPetTemporaryUnSummonedIfAny()
19865 if(!m_temporaryUnsummonedPetNumber)
19866 return;
19868 // not resummon in not appropriate state
19869 if(IsPetNeedBeTemporaryUnsummoned())
19870 return;
19872 if(GetPetGUID())
19873 return;
19875 Pet* NewPet = new Pet;
19876 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
19877 delete NewPet;
19879 m_temporaryUnsummonedPetNumber = 0;
19882 bool Player::canSeeSpellClickOn(Creature const *c) const
19884 SpellClickInfoMap const& map = objmgr.mSpellClickInfoMap;
19885 for(SpellClickInfoMap::const_iterator itr = map.lower_bound(c->GetEntry()); itr != map.upper_bound(c->GetEntry()); ++itr)
19887 if(itr->second.questId == 0 || GetQuestStatus(itr->second.questId) == QUEST_STATUS_INCOMPLETE)
19888 return true;
19890 return false;
19893 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
19895 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
19896 uint8 talentGroupCount = 1;
19897 *data << uint8(talentGroupCount); // talent group count (0, 1 or 2)
19898 *data << uint8(0); // talent group index (0 or 1)
19900 if(talentGroupCount)
19902 // loop through all specs (only 1 for now)
19903 for(uint32 groups = 0; groups < talentGroupCount; ++groups)
19905 uint8 talentIdCount = 0;
19906 size_t pos = data->wpos();
19907 *data << uint8(talentIdCount); // [PH], talentIdCount
19909 // find class talent tabs (all players have 3 talent tabs)
19910 uint32 const* talentTabIds = GetTalentTabPages(getClass());
19912 for(uint32 i = 0; i < 3; ++i)
19914 uint32 talentTabId = talentTabIds[i];
19916 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
19918 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
19919 if(!talentInfo)
19920 continue;
19922 // skip another tab talents
19923 if(talentInfo->TalentTab != talentTabId)
19924 continue;
19926 // find max talent rank
19927 int32 curtalent_maxrank = -1;
19928 for(int32 k = 4; k > -1; --k)
19930 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19932 curtalent_maxrank = k;
19933 break;
19937 // not learned talent
19938 if(curtalent_maxrank < 0)
19939 continue;
19941 *data << uint32(talentInfo->TalentID); // Talent.dbc
19942 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
19944 ++talentIdCount;
19948 data->put<uint8>(pos, talentIdCount); // put real count
19950 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
19952 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
19953 *data << uint16(GetGlyph(i)); // GlyphProperties.dbc
19958 void Player::BuildPetTalentsInfoData(WorldPacket *data)
19960 uint32 unspentTalentPoints = 0;
19961 size_t pointsPos = data->wpos();
19962 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
19964 uint8 talentIdCount = 0;
19965 size_t countPos = data->wpos();
19966 *data << uint8(talentIdCount); // [PH], talentIdCount
19968 Pet *pet = GetPet();
19969 if(!pet)
19970 return;
19972 unspentTalentPoints = pet->GetFreeTalentPoints();
19974 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
19976 CreatureInfo const *ci = pet->GetCreatureInfo();
19977 if(!ci)
19978 return;
19980 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19981 if(!pet_family || pet_family->petTalentType < 0)
19982 return;
19984 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
19986 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
19987 if(!talentTabInfo)
19988 continue;
19990 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19991 continue;
19993 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
19995 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
19996 if(!talentInfo)
19997 continue;
19999 // skip another tab talents
20000 if(talentInfo->TalentTab != talentTabId)
20001 continue;
20003 // find max talent rank
20004 int32 curtalent_maxrank = -1;
20005 for(int32 k = 4; k > -1; --k)
20007 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20009 curtalent_maxrank = k;
20010 break;
20014 // not learned talent
20015 if(curtalent_maxrank < 0)
20016 continue;
20018 *data << uint32(talentInfo->TalentID); // Talent.dbc
20019 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20021 ++talentIdCount;
20024 data->put<uint8>(countPos, talentIdCount); // put real count
20026 break;
20030 void Player::SendTalentsInfoData(bool pet)
20032 WorldPacket data(SMSG_TALENTS_INFO, 50);
20033 data << uint8(pet ? 1 : 0);
20034 if(pet)
20035 BuildPetTalentsInfoData(&data);
20036 else
20037 BuildPlayerTalentsInfoData(&data);
20038 GetSession()->SendPacket(&data);
20041 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
20043 uint32 slotUsedMask = 0;
20044 size_t slotUsedMaskPos = data->wpos();
20045 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
20047 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20049 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
20051 if(!item)
20052 continue;
20054 slotUsedMask |= (1 << i);
20056 *data << uint32(item->GetEntry()); // item entry
20058 uint16 enchantmentMask = 0;
20059 size_t enchantmentMaskPos = data->wpos();
20060 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
20062 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
20064 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
20066 if(!enchId)
20067 continue;
20069 enchantmentMask |= (1 << j);
20071 *data << uint16(enchId); // enchantmentId?
20074 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
20076 *data << uint16(0); // ?
20077 *data << uint8(0); // PGUID!
20078 *data << uint32(0); // seed?
20081 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
20084 void Player::SendEquipmentSetList()
20086 uint32 count = 0;
20087 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
20088 size_t count_pos = data.wpos();
20089 data << uint32(count); // count placeholder
20090 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20092 if(itr->second.state==EQUIPMENT_SET_DELETED)
20093 continue;
20094 data.appendPackGUID(itr->second.Guid);
20095 data << uint32(itr->first);
20096 data << itr->second.Name;
20097 data << itr->second.IconName;
20098 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20099 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
20101 ++count; // client have limit but it checked at loading and set
20103 data.put<uint32>(count_pos, count);
20104 GetSession()->SendPacket(&data);
20107 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
20109 if(eqset.Guid != 0)
20111 bool found = false;
20113 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20115 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
20117 found = true;
20118 break;
20122 if(!found) // something wrong...
20124 sLog.outError("Player %s tried to save equipment set "I64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
20125 return;
20129 EquipmentSet& eqslot = m_EquipmentSets[index];
20131 EquipmentSetUpdateState old_state = eqslot.state;
20133 eqslot = eqset;
20135 if(eqset.Guid == 0)
20137 eqslot.Guid = objmgr.GenerateEquipmentSetGuid();
20139 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
20140 data << uint32(index);
20141 data.appendPackGUID(eqslot.Guid);
20142 GetSession()->SendPacket(&data);
20145 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
20148 void Player::_SaveEquipmentSets()
20150 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
20152 uint32 index = itr->first;
20153 EquipmentSet& eqset = itr->second;
20154 switch(eqset.state)
20156 case EQUIPMENT_SET_UNCHANGED:
20157 ++itr;
20158 break; // nothing do
20159 case EQUIPMENT_SET_CHANGED:
20160 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='"I64FMTD"' AND setindex='%u'",
20161 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],
20162 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);
20163 eqset.state = EQUIPMENT_SET_UNCHANGED;
20164 ++itr;
20165 break;
20166 case EQUIPMENT_SET_NEW:
20167 CharacterDatabase.PExecute("INSERT INTO character_equipmentsets VALUES ('%u', '"I64FMTD"', '%u', '%s', '%s', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
20168 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],
20169 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]);
20170 eqset.state = EQUIPMENT_SET_UNCHANGED;
20171 ++itr;
20172 break;
20173 case EQUIPMENT_SET_DELETED:
20174 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="I64FMTD, eqset.Guid);
20175 m_EquipmentSets.erase(itr++);
20176 break;
20181 void Player::DeleteEquipmentSet(uint64 setGuid)
20183 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20185 if(itr->second.Guid == setGuid)
20187 if(itr->second.state == EQUIPMENT_SET_NEW)
20188 m_EquipmentSets.erase(itr);
20189 else
20190 itr->second.state = EQUIPMENT_SET_DELETED;
20191 break;