[7160] Implement (un-)learning skill level dependent spells at skill level change.
[getmangos.git] / src / game / Player.cpp
blobad447da2fe5de98d40a518ffcb526e5f05914bb8
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 "ObjectMgr.h"
25 #include "SpellMgr.h"
26 #include "World.h"
27 #include "WorldPacket.h"
28 #include "WorldSession.h"
29 #include "UpdateMask.h"
30 #include "Player.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 "SpellAuras.h"
51 #include "Util.h"
52 #include "Transports.h"
53 #include "Weather.h"
54 #include "BattleGround.h"
55 #include "BattleGroundMgr.h"
56 #include "ArenaTeam.h"
57 #include "Chat.h"
58 #include "Database/DatabaseImpl.h"
59 #include "Spell.h"
60 #include "SocialMgr.h"
61 #include "AchievementMgr.h"
63 #include <cmath>
65 #define ZONE_UPDATE_INTERVAL 1000
67 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
68 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
69 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
71 #define SKILL_VALUE(x) PAIR32_LOPART(x)
72 #define SKILL_MAX(x) PAIR32_HIPART(x)
73 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
75 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
76 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
77 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
79 enum CharacterFlags
81 CHARACTER_FLAG_NONE = 0x00000000,
82 CHARACTER_FLAG_UNK1 = 0x00000001,
83 CHARACTER_FLAG_UNK2 = 0x00000002,
84 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
85 CHARACTER_FLAG_UNK4 = 0x00000008,
86 CHARACTER_FLAG_UNK5 = 0x00000010,
87 CHARACTER_FLAG_UNK6 = 0x00000020,
88 CHARACTER_FLAG_UNK7 = 0x00000040,
89 CHARACTER_FLAG_UNK8 = 0x00000080,
90 CHARACTER_FLAG_UNK9 = 0x00000100,
91 CHARACTER_FLAG_UNK10 = 0x00000200,
92 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
93 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
94 CHARACTER_FLAG_UNK13 = 0x00001000,
95 CHARACTER_FLAG_GHOST = 0x00002000,
96 CHARACTER_FLAG_RENAME = 0x00004000,
97 CHARACTER_FLAG_UNK16 = 0x00008000,
98 CHARACTER_FLAG_UNK17 = 0x00010000,
99 CHARACTER_FLAG_UNK18 = 0x00020000,
100 CHARACTER_FLAG_UNK19 = 0x00040000,
101 CHARACTER_FLAG_UNK20 = 0x00080000,
102 CHARACTER_FLAG_UNK21 = 0x00100000,
103 CHARACTER_FLAG_UNK22 = 0x00200000,
104 CHARACTER_FLAG_UNK23 = 0x00400000,
105 CHARACTER_FLAG_UNK24 = 0x00800000,
106 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
107 CHARACTER_FLAG_DECLINED = 0x02000000,
108 CHARACTER_FLAG_UNK27 = 0x04000000,
109 CHARACTER_FLAG_UNK28 = 0x08000000,
110 CHARACTER_FLAG_UNK29 = 0x10000000,
111 CHARACTER_FLAG_UNK30 = 0x20000000,
112 CHARACTER_FLAG_UNK31 = 0x40000000,
113 CHARACTER_FLAG_UNK32 = 0x80000000
116 // corpse reclaim times
117 #define DEATH_EXPIRE_STEP (5*MINUTE)
118 #define MAX_DEATH_COUNT 3
120 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
122 //== PlayerTaxi ================================================
124 PlayerTaxi::PlayerTaxi()
126 // Taxi nodes
127 memset(m_taximask, 0, sizeof(m_taximask));
130 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
132 // capital and taxi hub masks
133 switch(race)
135 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
136 case RACE_ORC: SetTaximaskNode(23); break; // Orc
137 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
138 case RACE_NIGHTELF: SetTaximaskNode(26);
139 SetTaximaskNode(27); break; // Night Elf
140 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
141 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
142 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
143 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
144 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
145 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
148 switch(chrClass)
150 case CLASS_DEATH_KNIGHT: // TODO: figure out initial known nodes
151 break;
154 // new continent starting masks (It will be accessible only at new map)
155 switch(Player::TeamForRace(race))
157 case ALLIANCE: SetTaximaskNode(100); break;
158 case HORDE: SetTaximaskNode(99); break;
160 // level dependent taxi hubs
161 if(level>=68)
162 SetTaximaskNode(213); //Shattered Sun Staging Area
165 void PlayerTaxi::LoadTaxiMask(const char* data)
167 Tokens tokens = StrSplit(data, " ");
169 int index;
170 Tokens::iterator iter;
171 for (iter = tokens.begin(), index = 0;
172 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
174 // load and set bits only for existed taxi nodes
175 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
179 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
181 if(all)
183 for (uint8 i=0; i<TaxiMaskSize; i++)
184 data << uint32(sTaxiNodesMask[i]); // all existed nodes
186 else
188 for (uint8 i=0; i<TaxiMaskSize; i++)
189 data << uint32(m_taximask[i]); // known nodes
193 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
195 ClearTaxiDestinations();
197 Tokens tokens = StrSplit(values," ");
199 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
201 uint32 node = uint32(atol(iter->c_str()));
202 AddTaxiDestination(node);
205 if(m_TaxiDestinations.empty())
206 return true;
208 // Check integrity
209 if(m_TaxiDestinations.size() < 2)
210 return false;
212 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
214 uint32 cost;
215 uint32 path;
216 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
217 if(!path)
218 return false;
221 // can't load taxi path without mount set (quest taxi path?)
222 if(!objmgr.GetTaxiMount(GetTaxiSource(),team))
223 return false;
225 return true;
228 std::string PlayerTaxi::SaveTaxiDestinationsToString()
230 if(m_TaxiDestinations.empty())
231 return "";
233 std::ostringstream ss;
235 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
236 ss << m_TaxiDestinations[i] << " ";
238 return ss.str();
241 uint32 PlayerTaxi::GetCurrentTaxiPath() const
243 if(m_TaxiDestinations.size() < 2)
244 return 0;
246 uint32 path;
247 uint32 cost;
249 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
251 return path;
254 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
256 ss << "'";
257 for(int i = 0; i < TaxiMaskSize; ++i)
258 ss << taxi.m_taximask[i] << " ";
259 ss << "'";
260 return ss;
263 //== Player ====================================================
265 const int32 Player::ReputationRank_Length[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
267 UpdateMask Player::updateVisualBits;
269 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this)
271 m_transport = 0;
273 m_speakTime = 0;
274 m_speakCount = 0;
276 m_objectType |= TYPEMASK_PLAYER;
277 m_objectTypeId = TYPEID_PLAYER;
279 m_valuesCount = PLAYER_END;
281 m_session = session;
283 m_divider = 0;
285 m_ExtraFlags = 0;
286 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
287 SetAcceptTicket(true);
289 // players always accept
290 if(GetSession()->GetSecurity() == SEC_PLAYER)
291 SetAcceptWhispers(true);
293 m_curSelection = 0;
294 m_lootGuid = 0;
296 m_comboTarget = 0;
297 m_comboPoints = 0;
299 m_usedTalentCount = 0;
300 m_questRewardTalentCount = 0;
302 m_regenTimer = 0;
303 m_weaponChangeTimer = 0;
305 m_zoneUpdateId = 0;
306 m_zoneUpdateTimer = 0;
308 m_areaUpdateId = 0;
310 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
312 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
313 // this must help in case next save after mass player load after server startup
314 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
316 clearResurrectRequestData();
318 m_SpellModRemoveCount = 0;
320 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
322 m_social = NULL;
324 // group is initialized in the reference constructor
325 SetGroupInvite(NULL);
326 m_groupUpdateMask = 0;
327 m_auraUpdateMask = 0;
329 duel = NULL;
331 m_GuildIdInvited = 0;
332 m_ArenaTeamIdInvited = 0;
334 m_atLoginFlags = AT_LOGIN_NONE;
336 m_dontMove = false;
338 pTrader = 0;
339 ClearTrade();
341 m_cinematic = 0;
343 PlayerTalkClass = new PlayerMenu( GetSession() );
344 m_currentBuybackSlot = BUYBACK_SLOT_START;
346 for ( int aX = 0 ; aX < 8 ; aX++ )
347 m_Tutorials[ aX ] = 0x00;
348 m_TutorialsChanged = false;
350 m_DailyQuestChanged = false;
351 m_lastDailyQuestTime = 0;
353 m_regenTimer = 0;
354 m_weaponChangeTimer = 0;
355 m_breathTimer = 0;
356 m_isunderwater = 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 = 1000;
368 m_bgBattleGroundID = 0;
369 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; j++)
371 m_bgBattleGroundQueueID[j].bgQueueType = 0;
372 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
374 m_bgTeam = 0;
376 m_logintime = time(NULL);
377 m_Last_tick = m_logintime;
378 m_WeaponProficiency = 0;
379 m_ArmorProficiency = 0;
380 m_canParry = false;
381 m_canBlock = false;
382 m_canDualWield = false;
383 m_canTitanGrip = false;
384 m_ammoDPS = 0.0f;
386 m_temporaryUnsummonedPetNumber = 0;
387 //cache for UNIT_CREATED_BY_SPELL to allow
388 //returning reagents for temporarily removed pets
389 //when dying/logging out
390 m_oldpetspell = 0;
392 ////////////////////Rest System/////////////////////
393 time_inn_enter=0;
394 inn_pos_mapid=0;
395 inn_pos_x=0;
396 inn_pos_y=0;
397 inn_pos_z=0;
398 m_rest_bonus=0;
399 rest_type=REST_TYPE_NO;
400 ////////////////////Rest System/////////////////////
402 m_mailsLoaded = false;
403 m_mailsUpdated = false;
404 unReadMails = 0;
405 m_nextMailDelivereTime = 0;
407 m_resetTalentsCost = 0;
408 m_resetTalentsTime = 0;
409 m_itemUpdateQueueBlocked = false;
411 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
412 m_forced_speed_changes[i] = 0;
414 m_stableSlots = 0;
416 /////////////////// Instance System /////////////////////
418 m_HomebindTimer = 0;
419 m_InstanceValid = true;
420 m_dungeonDifficulty = DIFFICULTY_NORMAL;
422 for (int i = 0; i < BASEMOD_END; i++)
424 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
425 m_auraBaseMod[i][PCT_MOD] = 1.0f;
428 for (int i = 0; i < MAX_COMBAT_RATING; i++)
429 m_baseRatingValue[i] = 0;
431 m_baseSpellDamage = 0;
432 m_baseSpellHealing = 0;
433 m_baseFeralAP = 0;
434 m_baseManaRegen = 0;
436 // Honor System
437 m_lastHonorUpdateTime = time(NULL);
439 // Player summoning
440 m_summon_expire = 0;
441 m_summon_mapid = 0;
442 m_summon_x = 0.0f;
443 m_summon_y = 0.0f;
444 m_summon_z = 0.0f;
446 //Default movement to run mode
447 m_unit_movement_flags = 0;
449 m_mover = NULL;
451 m_miniPet = 0;
452 m_bgAfkReportedTimer = 0;
453 m_contestedPvPTimer = 0;
455 m_declinedname = NULL;
456 m_runes = NULL;
459 Player::~Player ()
461 CleanupsBeforeDelete();
463 // it must be unloaded already in PlayerLogout and accessed only for loggined player
464 //m_social = NULL;
466 // Note: buy back item already deleted from DB when player was saved
467 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
469 if(m_items[i])
470 delete m_items[i];
472 CleanupChannels();
474 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
475 delete itr->second;
477 //all mailed items should be deleted, also all mail should be deallocated
478 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
479 delete *itr;
481 for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
482 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
484 delete PlayerTalkClass;
486 if (m_transport)
488 m_transport->RemovePassenger(this);
491 for(size_t x = 0; x < ItemSetEff.size(); x++)
492 if(ItemSetEff[x])
493 delete ItemSetEff[x];
495 // clean up player-instance binds, may unload some instance saves
496 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
497 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
498 itr->second.save->RemovePlayer(this);
500 delete m_declinedname;
501 delete m_runes;
504 void Player::CleanupsBeforeDelete()
506 if(m_uint32Values) // only for fully created Object
508 TradeCancel(false);
509 DuelComplete(DUEL_INTERUPTED);
511 Unit::CleanupsBeforeDelete();
514 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 )
516 //FIXME: outfitId not used in player creating
518 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
520 m_name = name;
522 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
523 if(!info)
525 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
526 return false;
529 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
530 m_items[i] = NULL;
532 m_race = race;
533 m_class = class_;
535 SetMapId(info->mapId);
536 Relocate(info->positionX,info->positionY,info->positionZ);
538 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
539 if(!cEntry)
541 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
542 return false;
545 uint8 powertype = cEntry->powerType;
547 //uint32 unitfield;
549 /*switch(powertype)
551 case POWER_ENERGY:
552 case POWER_MANA:
553 unitfield = 0x00000000;
554 break;
555 case POWER_RAGE:
556 unitfield = 0x00110000;
557 break;
558 case POWER_RUNIC_POWER:
559 unitfield = 0x0000EE00; //TODO: find correct unitfield here
560 break;
561 default:
562 sLog.outError("Invalid default powertype %u for player (class %u)",powertype,class_);
563 return false;
566 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
567 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
569 switch(gender)
571 case GENDER_FEMALE:
572 SetDisplayId(info->displayId_f );
573 SetNativeDisplayId(info->displayId_f );
574 break;
575 case GENDER_MALE:
576 SetDisplayId(info->displayId_m );
577 SetNativeDisplayId(info->displayId_m );
578 break;
579 default:
580 sLog.outError("Invalid gender %u for player",gender);
581 return false;
582 break;
585 setFactionForRace(m_race);
587 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
589 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
590 //SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
591 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
592 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
593 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
594 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
595 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
597 // -1 is default value
598 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
600 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
601 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
602 SetByteValue(PLAYER_BYTES_3, 0, gender);
604 SetUInt32Value( PLAYER_GUILDID, 0 );
605 SetUInt32Value( PLAYER_GUILDRANK, 0 );
606 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
608 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
609 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
610 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
611 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
612 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
613 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
614 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
616 // set starting level
617 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
618 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
619 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
621 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
623 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
624 if(gm_level > start_level)
625 start_level = gm_level;
628 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
630 InitRunes();
632 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
633 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
634 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
636 // Played time
637 m_Last_tick = time(NULL);
638 m_Played_time[0] = 0;
639 m_Played_time[1] = 0;
641 // base stats and related field values
642 InitStatsForLevel();
643 InitTaxiNodesForLevel();
644 InitGlyphsForLevel();
645 InitTalentForLevel();
646 InitPrimaryProffesions(); // to max set before any spell added
648 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
649 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
650 SetHealth(GetMaxHealth());
651 if (getPowerType()==POWER_MANA)
653 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
654 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
657 if(getPowerType() == POWER_RUNIC_POWER)
659 SetPower(POWER_RUNE, 8);
660 SetMaxPower(POWER_RUNE, 8);
661 SetPower(POWER_RUNIC_POWER, 0);
662 SetMaxPower(POWER_RUNIC_POWER, 1000);
665 // original spells
666 learnDefaultSpells();
668 // original action bar
669 std::list<uint16>::const_iterator action_itr[4];
670 for(int i=0; i<4; i++)
671 action_itr[i] = info->action[i].begin();
673 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
675 uint16 taction[4];
676 for(int i=0; i<4 ;i++)
677 taction[i] = (*action_itr[i]);
679 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
681 for(int i=0; i<4 ;i++)
682 ++action_itr[i];
685 // original items
686 CharStartOutfitEntry const* oEntry = NULL;
687 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
689 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
691 if(entry->RaceClassGender == RaceClassGender)
693 oEntry = entry;
694 break;
699 if(oEntry)
701 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
703 if(oEntry->ItemId[j] <= 0)
704 continue;
706 uint32 item_id = oEntry->ItemId[j];
709 // Hack for not existed item id in dbc 3.0.3
710 if(item_id==40582)
711 continue;
713 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
714 if(!iProto)
716 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
717 continue;
720 // max stack by default (mostly 1), 1 for infinity stackable
721 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
723 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
725 switch(iProto->Spells[0].SpellCategory)
727 case 11: // food
728 if(iProto->Stackable > 4)
729 count = 4;
730 break;
731 case 59: // drink
732 if(iProto->Stackable > 2)
733 count = 2;
734 break;
738 StoreNewItemInBestSlots(item_id, count);
742 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
743 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
745 // bags and main-hand weapon must equipped at this moment
746 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
747 // or ammo not equipped in special bag
748 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
750 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
752 uint16 eDest;
753 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
754 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
755 if( msg == EQUIP_ERR_OK )
757 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
758 EquipItem( eDest, pItem, true);
760 // move other items to more appropriate slots (ammo not equipped in special bag)
761 else
763 ItemPosCountVec sDest;
764 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
765 if( msg == EQUIP_ERR_OK )
767 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
768 pItem = StoreItem( sDest, pItem, true);
771 // if this is ammo then use it
772 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
773 if( msg == EQUIP_ERR_OK )
774 SetAmmo( pItem->GetProto()->ItemId );
778 // all item positions resolved
780 return true;
783 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
785 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
787 // attempt equip by one
788 while(titem_amount > 0)
790 uint16 eDest;
791 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
792 if( msg != EQUIP_ERR_OK )
793 break;
795 EquipNewItem( eDest, titem_id, true);
796 AutoUnequipOffhandIfNeed();
797 --titem_amount;
800 if(titem_amount == 0)
801 return true; // equipped
803 // attempt store
804 ItemPosCountVec sDest;
805 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
806 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
807 if( msg == EQUIP_ERR_OK )
809 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
810 return true; // stored
813 // item can't be added
814 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
815 return false;
818 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
820 uint32 BreathRegen = (uint32)-1;
822 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
823 data << (uint32)Type;
824 data << MaxValue;
825 data << MaxValue;
826 data << BreathRegen;
827 data << (uint8)0;
828 data << (uint32)0; // spell id
829 GetSession()->SendPacket(&data);
832 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
834 if(Type==BREATH_TIMER)
835 m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;
837 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
838 data << (uint32)Type;
839 data << CurrentValue;
840 data << MaxValue;
841 data << Regen;
842 data << (uint8)0;
843 data << (uint32)0; // spell id
844 GetSession()->SendPacket( &data );
847 void Player::StopMirrorTimer(MirrorTimerType Type)
849 if(Type==BREATH_TIMER)
850 m_breathTimer = 0;
852 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
853 data << (uint32)Type;
854 GetSession()->SendPacket( &data );
857 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
859 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
860 data << (uint64)guid;
861 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
862 data << (uint32)damage;
863 data << (uint32)0;
864 data << (uint32)0;
865 SendMessageToSet(&data, true);
867 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
869 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
871 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
872 DurabilityLossAll(0.10f,false);
873 // durability lost message
874 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
875 GetSession()->SendPacket(&data);
879 void Player::HandleDrowning()
881 if(!(m_isunderwater&~UNDERWATER_INLAVA))
882 return;
884 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
885 if(isGameMaster() || !isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
887 StopMirrorTimer(BREATH_TIMER);
888 // drop every flag _except_ LAVA - otherwise waterbreathing will prevent lava damage
889 m_isunderwater &= UNDERWATER_INLAVA;
890 return;
893 uint32 UnderWaterTime = 1*MINUTE*1000; // default length 1 min
895 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
896 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
897 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
899 if ((m_isunderwater & UNDERWATER_INWATER) && !(m_isunderwater & UNDERWATER_INLAVA) && isAlive())
901 //single trigger timer
902 if (!(m_isunderwater & UNDERWATER_WATER_TRIGGER))
904 m_isunderwater|= UNDERWATER_WATER_TRIGGER;
905 m_breathTimer = UnderWaterTime + 1000;
907 //single trigger "show Breathbar"
908 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & UNDERWATER_WATER_BREATHB))
910 m_isunderwater|= UNDERWATER_WATER_BREATHB;
911 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
913 //continuous trigger drowning "Damage"
914 if ((m_breathTimer == 0) && (m_isunderwater & UNDERWATER_INWATER))
916 //TODO: Check this formula
917 uint64 guid = GetGUID();
918 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
920 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
921 m_breathTimer = 2000;
924 //single trigger retract bar
925 else if (!(m_isunderwater & UNDERWATER_INWATER) && (m_isunderwater & UNDERWATER_WATER_TRIGGER) && (m_breathTimer > 0) && isAlive())
927 uint32 BreathRegen = 10;
928 // m_breathTimer will be reduced in ModifyMirrorTimer
929 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
930 m_isunderwater = UNDERWATER_WATER_BREATHB_RETRACTING;
932 //remove bar
933 else if ((m_breathTimer < 50) && !(m_isunderwater & UNDERWATER_INWATER) && (m_isunderwater == UNDERWATER_WATER_BREATHB_RETRACTING))
935 StopMirrorTimer(BREATH_TIMER);
936 m_isunderwater = UNDERWATER_NONE;
940 void Player::HandleLava()
942 if ((m_isunderwater & UNDERWATER_INLAVA) && isAlive())
945 * arrai: how is this supposed to work? UNDERWATER_INLAVA is always set in this scope!
946 // Single trigger Set BreathTimer
947 if (!(m_isunderwater & UNDERWATER_INLAVA))
949 m_isunderwater|= UNDERWATER_WATER_BREATHB;
950 m_breathTimer = 1000;
953 // Reset BreathTimer and still in the lava
954 if (!m_breathTimer)
956 uint64 guid = GetGUID();
957 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
959 // if not gamemaster then deal damage
960 if ( !isGameMaster() )
961 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
963 m_breathTimer = 1000;
966 else if (!isAlive()) // Disable breath timer and reset underwater flags
968 m_breathTimer = 0;
969 m_isunderwater = UNDERWATER_NONE;
973 ///The player sobers by 256 every 10 seconds
974 void Player::HandleSobering()
976 m_drunkTimer = 0;
978 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
979 SetDrunkValue(drunk);
982 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
984 if(value >= 23000)
985 return DRUNKEN_SMASHED;
986 if(value >= 12800)
987 return DRUNKEN_DRUNK;
988 if(value & 0xFFFE)
989 return DRUNKEN_TIPSY;
990 return DRUNKEN_SOBER;
993 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
995 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
997 m_drunk = newDrunkenValue;
998 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1000 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1002 // special drunk invisibility detection
1003 if(newDrunkenState >= DRUNKEN_DRUNK)
1004 m_detectInvisibilityMask |= (1<<6);
1005 else
1006 m_detectInvisibilityMask &= ~(1<<6);
1008 if(newDrunkenState == oldDrunkenState)
1009 return;
1011 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1012 data << uint64(GetGUID());
1013 data << uint32(newDrunkenState);
1014 data << uint32(itemId);
1016 SendMessageToSet(&data, true);
1019 void Player::Update( uint32 p_time )
1021 if(!IsInWorld())
1022 return;
1024 // undelivered mail
1025 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1027 SendNewMail();
1028 ++unReadMails;
1030 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1031 m_nextMailDelivereTime = 0;
1034 Unit::Update( p_time );
1036 // update player only attacks
1037 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1039 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1042 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1044 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1047 time_t now = time (NULL);
1049 UpdatePvPFlag(now);
1051 UpdateContestedPvP(p_time);
1053 UpdateDuelFlag(now);
1055 CheckDuelDistance(now);
1057 UpdateAfkReport(now);
1059 CheckExploreSystem();
1061 // Update items that have just a limited lifetime
1062 if (now>m_Last_tick)
1063 UpdateItemDuration(uint32(now- m_Last_tick));
1065 if (!m_timedquests.empty())
1067 std::set<uint32>::iterator iter = m_timedquests.begin();
1068 while (iter != m_timedquests.end())
1070 QuestStatusData& q_status = mQuestStatus[*iter];
1071 if( q_status.m_timer <= p_time )
1073 uint32 quest_id = *iter;
1074 ++iter; // current iter will be removed in FailTimedQuest
1075 FailTimedQuest( quest_id );
1077 else
1079 q_status.m_timer -= p_time;
1080 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1081 ++iter;
1086 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1088 Unit *pVictim = getVictim();
1089 if( !IsNonMeleeSpellCasted(false) && pVictim)
1091 // default combat reach 10
1092 // TODO add weapon,skill check
1094 float pldistance = ATTACK_DISTANCE;
1096 if (isAttackReady(BASE_ATTACK))
1098 if(!IsWithinDistInMap(pVictim, pldistance))
1100 setAttackTimer(BASE_ATTACK,100);
1101 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1103 SendAttackSwingNotInRange();
1104 m_swingErrorMsg = 1;
1107 //120 degrees of radiant range
1108 else if( !HasInArc( 2*M_PI/3, pVictim ))
1110 setAttackTimer(BASE_ATTACK,100);
1111 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1113 SendAttackSwingBadFacingAttack();
1114 m_swingErrorMsg = 2;
1117 else
1119 m_swingErrorMsg = 0; // reset swing error state
1121 // prevent base and off attack in same time, delay attack at 0.2 sec
1122 if(haveOffhandWeapon())
1124 uint32 off_att = getAttackTimer(OFF_ATTACK);
1125 if(off_att < ATTACK_DISPLAY_DELAY)
1126 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1128 AttackerStateUpdate(pVictim, BASE_ATTACK);
1129 resetAttackTimer(BASE_ATTACK);
1133 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1135 if(!IsWithinDistInMap(pVictim, pldistance))
1137 setAttackTimer(OFF_ATTACK,100);
1139 else if( !HasInArc( 2*M_PI/3, pVictim ))
1141 setAttackTimer(OFF_ATTACK,100);
1143 else
1145 // prevent base and off attack in same time, delay attack at 0.2 sec
1146 uint32 base_att = getAttackTimer(BASE_ATTACK);
1147 if(base_att < ATTACK_DISPLAY_DELAY)
1148 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1149 // do attack
1150 AttackerStateUpdate(pVictim, OFF_ATTACK);
1151 resetAttackTimer(OFF_ATTACK);
1155 Unit *owner = pVictim->GetOwner();
1156 Unit *u = owner ? owner : pVictim;
1157 if(u->IsPvP() && (!duel || duel->opponent != u))
1159 UpdatePvP(true);
1160 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1165 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1167 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1169 int time_inn = time(NULL)-GetTimeInnEnter();
1170 if (time_inn >= 10) //freeze update
1172 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1173 //speed collect rest bonus (section/in hour)
1174 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1175 UpdateInnerTime(time(NULL));
1180 if(m_regenTimer > 0)
1182 if(p_time >= m_regenTimer)
1183 m_regenTimer = 0;
1184 else
1185 m_regenTimer -= p_time;
1188 if (m_weaponChangeTimer > 0)
1190 if(p_time >= m_weaponChangeTimer)
1191 m_weaponChangeTimer = 0;
1192 else
1193 m_weaponChangeTimer -= p_time;
1196 if (m_zoneUpdateTimer > 0)
1198 if(p_time >= m_zoneUpdateTimer)
1200 uint32 newzone = GetZoneId();
1201 if( m_zoneUpdateId != newzone )
1202 UpdateZone(newzone); // also update area
1203 else
1205 // use area updates as well
1206 // needed for free far all arenas for example
1207 uint32 newarea = GetAreaId();
1208 if( m_areaUpdateId != newarea )
1209 UpdateArea(newarea);
1211 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1214 else
1215 m_zoneUpdateTimer -= p_time;
1218 if (isAlive())
1220 RegenerateAll();
1223 if (m_deathState == JUST_DIED)
1225 KillPlayer();
1228 if(m_nextSave > 0)
1230 if(p_time >= m_nextSave)
1232 // m_nextSave reseted in SaveToDB call
1233 SaveToDB();
1234 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1236 else
1238 m_nextSave -= p_time;
1242 //Breathtimer
1243 if(m_breathTimer > 0)
1245 if(p_time >= m_breathTimer)
1246 m_breathTimer = 0;
1247 else
1248 m_breathTimer -= p_time;
1252 //Handle Water/drowning
1253 HandleDrowning();
1255 //Handle lava
1256 HandleLava();
1258 //Handle detect stealth players
1259 if (m_DetectInvTimer > 0)
1261 if (p_time >= m_DetectInvTimer)
1263 m_DetectInvTimer = 3000;
1264 HandleStealthedUnitsDetection();
1266 else
1267 m_DetectInvTimer -= p_time;
1270 // Played time
1271 if (now > m_Last_tick)
1273 uint32 elapsed = uint32(now - m_Last_tick);
1274 m_Played_time[0] += elapsed; // Total played time
1275 m_Played_time[1] += elapsed; // Level played time
1276 m_Last_tick = now;
1279 if (m_drunk)
1281 m_drunkTimer += p_time;
1283 if (m_drunkTimer > 10000)
1284 HandleSobering();
1287 // not auto-free ghost from body in instances
1288 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1290 if(p_time >= m_deathTimer)
1292 m_deathTimer = 0;
1293 BuildPlayerRepop();
1294 RepopAtGraveyard();
1296 else
1297 m_deathTimer -= p_time;
1300 UpdateEnchantTime(p_time);
1301 UpdateHomebindTime(p_time);
1303 // group update
1304 SendUpdateToOutOfRangeGroupMembers();
1306 Pet* pet = GetPet();
1307 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1309 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1310 return;
1314 void Player::setDeathState(DeathState s)
1316 uint32 ressSpellId = 0;
1318 bool cur = isAlive();
1320 if(s == JUST_DIED && cur)
1322 // drunken state is cleared on death
1323 SetDrunkValue(0);
1324 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1325 ClearComboPoints();
1327 clearResurrectRequestData();
1329 // remove form before other mods to prevent incorrect stats calculation
1330 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1332 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1333 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1335 // remove uncontrolled pets
1336 RemoveMiniPet();
1337 RemoveGuardians();
1339 // save value before aura remove in Unit::setDeathState
1340 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1342 // passive spell
1343 if(!ressSpellId)
1344 ressSpellId = GetResurrectionSpellId();
1345 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1347 Unit::setDeathState(s);
1349 // restore resurrection spell id for player after aura remove
1350 if(s == JUST_DIED && cur && ressSpellId)
1351 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1353 if(isAlive() && !cur)
1355 //clear aura case after resurrection by another way (spells will be applied before next death)
1356 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1358 // restore default warrior stance
1359 if(getClass()== CLASS_WARRIOR)
1360 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1364 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1366 Field *fields = result->Fetch();
1368 *p_data << uint64(GetGUID());
1369 *p_data << m_name;
1371 *p_data << uint8(getRace());
1372 uint8 pClass = getClass();
1373 *p_data << uint8(pClass);
1374 *p_data << uint8(getGender());
1376 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1377 *p_data << uint8(bytes);
1378 *p_data << uint8(bytes >> 8);
1379 *p_data << uint8(bytes >> 16);
1380 *p_data << uint8(bytes >> 24);
1382 bytes = GetUInt32Value(PLAYER_BYTES_2);
1383 *p_data << uint8(bytes);
1385 *p_data << uint8(getLevel()); // player level
1386 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1387 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1388 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1389 *p_data << uint32(zoneId);
1390 *p_data << uint32(GetMapId());
1392 *p_data << GetPositionX();
1393 *p_data << GetPositionY();
1394 *p_data << GetPositionZ();
1396 // guild id
1397 *p_data << (result ? fields[13].GetUInt32() : 0);
1399 uint32 char_flags = 0;
1400 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1401 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1402 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1403 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1404 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1405 char_flags |= CHARACTER_FLAG_GHOST;
1406 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1407 char_flags |= CHARACTER_FLAG_RENAME;
1408 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1409 char_flags |= CHARACTER_FLAG_DECLINED;
1411 *p_data << uint32(char_flags); // character flags
1412 // character customize (flags?)
1413 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1414 *p_data << uint8(1); // unknown
1416 // Pets info
1418 uint32 petDisplayId = 0;
1419 uint32 petLevel = 0;
1420 uint32 petFamily = 0;
1422 // show pet at selection character in character list only for non-ghost character
1423 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1425 uint32 entry = fields[10].GetUInt32();
1426 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1427 if(cInfo)
1429 petDisplayId = fields[11].GetUInt32();
1430 petLevel = fields[12].GetUInt32();
1431 petFamily = cInfo->family;
1435 *p_data << uint32(petDisplayId);
1436 *p_data << uint32(petLevel);
1437 *p_data << uint32(petFamily);
1440 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1442 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1443 uint32 item_id = GetUInt32Value(visualbase);
1444 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1445 SpellItemEnchantmentEntry const *enchant = NULL;
1447 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1449 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1450 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1451 break;
1454 if (proto != NULL)
1456 *p_data << uint32(proto->DisplayInfoID);
1457 *p_data << uint8(proto->InventoryType);
1458 *p_data << uint32(enchant ? enchant->aura_id : 0);
1460 else
1462 *p_data << uint32(0);
1463 *p_data << uint8(0);
1464 *p_data << uint32(0); // enchant?
1467 *p_data << uint32(0); // first bag display id
1468 *p_data << uint8(0); // first bag inventory type
1469 *p_data << uint32(0); // enchant?
1472 bool Player::ToggleAFK()
1474 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1476 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1478 // afk player not allowed in battleground
1479 if(state && InBattleGround())
1480 LeaveBattleground();
1482 return state;
1485 bool Player::ToggleDND()
1487 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1489 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1492 uint8 Player::chatTag() const
1494 // it's bitmask
1495 // 0x8 - ??
1496 // 0x4 - gm
1497 // 0x2 - dnd
1498 // 0x1 - afk
1499 if(isGMChat())
1500 return 4;
1501 else if(isDND())
1502 return 3;
1503 if(isAFK())
1504 return 1;
1505 else
1506 return 0;
1509 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1511 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1513 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1514 return false;
1517 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1518 Pet* pet = GetPet();
1520 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1522 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1523 // don't let gm level > 1 either
1524 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1525 return false;
1527 // client without expansion support
1528 if(GetSession()->Expansion() < mEntry->Expansion())
1530 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1532 if(GetTransport())
1533 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1535 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1537 return false; // normal client can't teleport to this map...
1539 else
1541 sLog.outDebug("Player %s will teleported to map %u", GetName(), mapid);
1544 // if we were on a transport, leave
1545 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1547 m_transport->RemovePassenger(this);
1548 m_transport = NULL;
1549 m_movementInfo.t_x = 0.0f;
1550 m_movementInfo.t_y = 0.0f;
1551 m_movementInfo.t_z = 0.0f;
1552 m_movementInfo.t_o = 0.0f;
1553 m_movementInfo.t_time = 0;
1556 SetSemaphoreTeleport(true);
1558 // The player was ported to another map and looses the duel immediately.
1559 // We have to perform this check before the teleport, otherwise the
1560 // ObjectAccessor won't find the flag.
1561 if (duel && GetMapId()!=mapid)
1563 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1564 if (obj)
1565 DuelComplete(DUEL_FLED);
1568 // reset movement flags at teleport, because player will continue move with these flags after teleport
1569 SetUnitMovementFlags(0);
1571 if ((GetMapId() == mapid) && (!m_transport))
1573 // prepare zone change detect
1574 uint32 old_zone = GetZoneId();
1576 // near teleport
1577 if(!GetSession()->PlayerLogout())
1579 WorldPacket data;
1580 BuildTeleportAckMsg(&data, x, y, z, orientation);
1581 GetSession()->SendPacket(&data);
1582 SetPosition( x, y, z, orientation, true);
1584 else
1585 // this will be used instead of the current location in SaveToDB
1586 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1587 SetFallInformation(0, z);
1589 //BuildHeartBeatMsg(&data);
1590 //SendMessageToSet(&data, true);
1591 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1593 //same map, only remove pet if out of range
1594 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1596 if(pet->isControlled() && !pet->isTemporarySummoned() )
1597 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1598 else
1599 m_temporaryUnsummonedPetNumber = 0;
1601 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1605 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1606 CombatStop();
1608 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1610 // resummon pet
1611 if(pet && m_temporaryUnsummonedPetNumber)
1613 Pet* NewPet = new Pet;
1614 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1615 delete NewPet;
1617 m_temporaryUnsummonedPetNumber = 0;
1621 if(!GetSession()->PlayerLogout())
1623 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1624 SetSemaphoreTeleport(false);
1626 UpdateZone(GetZoneId());
1629 // new zone
1630 if(old_zone != GetZoneId())
1632 // honorless target
1633 if(pvpInfo.inHostileArea)
1634 CastSpell(this, 2479, true);
1637 else
1639 // far teleport to another map
1640 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1641 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1643 // Check enter rights before map getting to avoid creating instance copy for player
1644 // this check not dependent from map instance copy and same for all instance copies of selected map
1645 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1647 SetSemaphoreTeleport(false);
1648 return false;
1651 // If the map is not created, assume it is possible to enter it.
1652 // It will be created in the WorldPortAck.
1653 Map *map = MapManager::Instance().FindMap(mapid);
1654 if (!map || map->CanEnter(this))
1656 SetSelection(0);
1658 CombatStop();
1660 ResetContestedPvP();
1662 // remove player from battleground on far teleport (when changing maps)
1663 if(BattleGround const* bg = GetBattleGround())
1665 // Note: at battleground join battleground id set before teleport
1666 // and we already will found "current" battleground
1667 // just need check that this is targeted map or leave
1668 if(bg->GetMapId() != mapid)
1669 LeaveBattleground(false); // don't teleport to entry point
1672 // remove pet on map change
1673 if (pet)
1675 //leaving map -> delete pet right away (doing this later will cause problems)
1676 if(pet->isControlled() && !pet->isTemporarySummoned())
1677 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1678 else
1679 m_temporaryUnsummonedPetNumber = 0;
1681 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1684 // remove all dyn objects
1685 RemoveAllDynObjects();
1687 // stop spellcasting
1688 // not attempt interrupt teleportation spell at caster teleport
1689 if(!(options & TELE_TO_SPELL))
1690 if(IsNonMeleeSpellCasted(true))
1691 InterruptNonMeleeSpells(true);
1693 if(!GetSession()->PlayerLogout())
1695 // send transfer packets
1696 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1697 data << uint32(mapid);
1698 if (m_transport)
1700 data << m_transport->GetEntry() << GetMapId();
1702 GetSession()->SendPacket(&data);
1704 data.Initialize(SMSG_NEW_WORLD, (20));
1705 if (m_transport)
1707 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1709 else
1711 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1713 GetSession()->SendPacket( &data );
1714 SendSavedInstances();
1716 // remove from old map now
1717 if(oldmap) oldmap->Remove(this, false);
1720 // new final coordinates
1721 float final_x = x;
1722 float final_y = y;
1723 float final_z = z;
1724 float final_o = orientation;
1726 if(m_transport)
1728 final_x += m_movementInfo.t_x;
1729 final_y += m_movementInfo.t_y;
1730 final_z += m_movementInfo.t_z;
1731 final_o += m_movementInfo.t_o;
1734 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1735 SetFallInformation(0, final_z);
1736 // if the player is saved before worldportack (at logout for example)
1737 // this will be used instead of the current location in SaveToDB
1739 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1741 // move packet sent by client always after far teleport
1742 // SetPosition(final_x, final_y, final_z, final_o, true);
1743 SetDontMove(true);
1745 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1747 else
1748 return false;
1750 return true;
1753 void Player::AddToWorld()
1755 ///- Do not add/remove the player from the object storage
1756 ///- It will crash when updating the ObjectAccessor
1757 ///- The player should only be added when logging in
1758 Unit::AddToWorld();
1760 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1762 if(m_items[i])
1763 m_items[i]->AddToWorld();
1767 void Player::RemoveFromWorld()
1769 // cleanup
1770 if(IsInWorld())
1772 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1773 Uncharm();
1774 UnsummonAllTotems();
1775 RemoveMiniPet();
1776 RemoveGuardians();
1779 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1781 if(m_items[i])
1782 m_items[i]->RemoveFromWorld();
1785 ///- Do not add/remove the player from the object storage
1786 ///- It will crash when updating the ObjectAccessor
1787 ///- The player should only be removed when logging out
1788 Unit::RemoveFromWorld();
1791 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1793 float addRage;
1795 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1797 if(attacker)
1799 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1801 // talent who gave more rage on attack
1802 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1804 else
1806 addRage = damage/rageconversion*2.5;
1808 // Berserker Rage effect
1809 if(HasAura(18499,0))
1810 addRage *= 1.3;
1813 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1815 ModifyPower(POWER_RAGE, uint32(addRage*10));
1818 void Player::RegenerateAll()
1820 if (m_regenTimer != 0)
1821 return;
1822 uint32 regenDelay = 2000;
1824 // Not in combat or they have regeneration
1825 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1826 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1828 RegenerateHealth();
1829 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1831 Regenerate(POWER_RAGE);
1832 if(getClass() == CLASS_DEATH_KNIGHT)
1833 Regenerate(POWER_RUNIC_POWER);
1837 Regenerate( POWER_ENERGY );
1839 Regenerate( POWER_MANA );
1841 if(getClass() == CLASS_DEATH_KNIGHT)
1842 Regenerate( POWER_RUNE );
1844 m_regenTimer = regenDelay;
1847 void Player::Regenerate(Powers power)
1849 uint32 curValue = GetPower(power);
1850 uint32 maxValue = GetMaxPower(power);
1852 float addvalue = 0.0f;
1854 switch (power)
1856 case POWER_MANA:
1858 bool recentCast = IsUnderLastManaUseEffect();
1859 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1860 if (recentCast)
1862 // Mangos Updates Mana in intervals of 2s, which is correct
1863 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1865 else
1867 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1869 } break;
1870 case POWER_RAGE: // Regenerate rage
1872 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1873 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1874 } break;
1875 case POWER_ENERGY: // Regenerate energy (rogue)
1876 addvalue = 20;
1877 break;
1878 case POWER_RUNIC_POWER:
1880 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1881 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1882 } break;
1883 case POWER_RUNE:
1885 for(uint32 i = 0; i < MAX_RUNES; ++i)
1886 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1887 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1888 } break;
1889 case POWER_FOCUS:
1890 case POWER_HAPPINESS:
1891 break;
1894 // Mana regen calculated in Player::UpdateManaRegen()
1895 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1896 if(power != POWER_MANA)
1898 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1899 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1900 if ((*i)->GetModifier()->m_miscvalue == power)
1901 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1904 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1906 curValue += uint32(addvalue);
1907 if (curValue > maxValue)
1908 curValue = maxValue;
1910 else
1912 if(curValue <= uint32(addvalue))
1913 curValue = 0;
1914 else
1915 curValue -= uint32(addvalue);
1917 SetPower(power, curValue);
1920 void Player::RegenerateHealth()
1922 uint32 curValue = GetHealth();
1923 uint32 maxValue = GetMaxHealth();
1925 if (curValue >= maxValue) return;
1927 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1929 float addvalue = 0.0f;
1931 // polymorphed case
1932 if ( IsPolymorphed() )
1933 addvalue = GetMaxHealth()/3;
1934 // normal regen case (maybe partly in combat case)
1935 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1937 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1938 if (!isInCombat())
1940 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1941 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1942 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1944 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1945 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1947 if(!IsStandState())
1948 addvalue *= 1.5;
1951 // always regeneration bonus (including combat)
1952 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1954 if(addvalue < 0)
1955 addvalue = 0;
1957 ModifyHealth(int32(addvalue));
1960 bool Player::CanInteractWithNPCs(bool alive) const
1962 if(alive && !isAlive())
1963 return false;
1964 if(isInFlight())
1965 return false;
1967 return true;
1970 bool Player::IsUnderWater() const
1972 return IsInWater() &&
1973 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1976 void Player::SetInWater(bool apply)
1978 if(m_isInWater==apply)
1979 return;
1981 //define player in water by opcodes
1982 //move player's guid into HateOfflineList of those mobs
1983 //which can't swim and move guid back into ThreatList when
1984 //on surface.
1985 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1986 m_isInWater = apply;
1988 // remove auras that need water/land
1989 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1991 getHostilRefManager().updateThreatTables();
1994 void Player::SetGameMaster(bool on)
1996 if(on)
1998 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1999 setFaction(35);
2000 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2002 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2003 ResetContestedPvP();
2005 getHostilRefManager().setOnlineOfflineState(false);
2006 CombatStop();
2008 else
2010 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2011 setFactionForRace(getRace());
2012 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2014 // restore FFA PvP Server state
2015 if(sWorld.IsFFAPvPRealm())
2016 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2018 // restore FFA PvP area state, remove not allowed for GM mounts
2019 UpdateArea(m_areaUpdateId);
2021 getHostilRefManager().setOnlineOfflineState(true);
2024 ObjectAccessor::UpdateVisibilityForPlayer(this);
2027 void Player::SetGMVisible(bool on)
2029 if(on)
2031 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2033 // Reapply stealth/invisibility if active or show if not any
2034 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2035 SetVisibility(VISIBILITY_GROUP_STEALTH);
2036 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2037 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2038 else
2039 SetVisibility(VISIBILITY_ON);
2041 else
2043 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2045 SetAcceptWhispers(false);
2046 SetGameMaster(true);
2048 SetVisibility(VISIBILITY_OFF);
2052 bool Player::IsGroupVisibleFor(Player* p) const
2054 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2056 default: return IsInSameGroupWith(p);
2057 case 1: return IsInSameRaidWith(p);
2058 case 2: return GetTeam()==p->GetTeam();
2062 bool Player::IsInSameGroupWith(Player const* p) const
2064 return p==this || GetGroup() != NULL &&
2065 GetGroup() == p->GetGroup() &&
2066 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2069 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2070 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2071 void Player::UninviteFromGroup()
2073 Group* group = GetGroupInvite();
2074 if(!group)
2075 return;
2077 group->RemoveInvite(this);
2079 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2081 if(group->IsCreated())
2083 group->Disband(true);
2084 objmgr.RemoveGroup(group);
2086 else
2087 group->RemoveAllInvites();
2089 delete group;
2093 void Player::RemoveFromGroup(Group* group, uint64 guid)
2095 if(group)
2097 if (group->RemoveMember(guid, 0) <= 1)
2099 // group->Disband(); already disbanded in RemoveMember
2100 objmgr.RemoveGroup(group);
2101 delete group;
2102 // removemember sets the player's group pointer to NULL
2107 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2109 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2110 data << uint64(victim ? victim->GetGUID() : 0); // guid
2111 data << uint32(GivenXP+RestXP); // given experience
2112 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2113 if(victim)
2115 data << uint32(GivenXP); // experience without rested bonus
2116 data << float(1); // 1 - none 0 - 100% group bonus output
2118 data << uint8(0); // new 2.4.0
2119 GetSession()->SendPacket(&data);
2122 void Player::GiveXP(uint32 xp, Unit* victim)
2124 if ( xp < 1 )
2125 return;
2127 if(!isAlive())
2128 return;
2130 uint32 level = getLevel();
2132 // XP to money conversion processed in Player::RewardQuest
2133 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2134 return;
2136 // handle SPELL_AURA_MOD_XP_PCT auras
2137 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2138 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2139 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2141 // XP resting bonus for kill
2142 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2144 SendLogXPGain(xp,victim,rested_bonus_xp);
2146 uint32 curXP = GetUInt32Value(PLAYER_XP);
2147 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2148 uint32 newXP = curXP + xp + rested_bonus_xp;
2150 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2152 newXP -= nextLvlXP;
2154 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2155 GiveLevel(level + 1);
2157 level = getLevel();
2158 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2161 SetUInt32Value(PLAYER_XP, newXP);
2164 // Update player to next level
2165 // Current player experience not update (must be update by caller)
2166 void Player::GiveLevel(uint32 level)
2168 if ( level == getLevel() )
2169 return;
2171 PlayerLevelInfo info;
2172 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2174 PlayerClassLevelInfo classInfo;
2175 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2177 // send levelup info to client
2178 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2179 data << uint32(level);
2180 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2181 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2182 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2183 data << uint32(0);
2184 data << uint32(0);
2185 data << uint32(0);
2186 data << uint32(0);
2187 data << uint32(0);
2188 data << uint32(0);
2189 // end for
2190 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2191 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2193 GetSession()->SendPacket(&data);
2195 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2197 //update level, max level of skills
2198 if(getLevel()!= level)
2199 m_Played_time[1] = 0; // Level Played Time reset
2200 SetLevel(level);
2201 UpdateSkillsForLevel ();
2203 // save base values (bonuses already included in stored stats
2204 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2205 SetCreateStat(Stats(i), info.stats[i]);
2207 SetCreateHealth(classInfo.basehealth);
2208 SetCreateMana(classInfo.basemana);
2210 InitTalentForLevel();
2211 InitTaxiNodesForLevel();
2212 InitGlyphsForLevel();
2214 UpdateAllStats();
2216 // set current level health and mana/energy to maximum after applying all mods.
2217 SetHealth(GetMaxHealth());
2218 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2219 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2220 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2221 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2222 SetPower(POWER_FOCUS, 0);
2223 SetPower(POWER_HAPPINESS, 0);
2225 // give level to summoned pet
2226 Pet* pet = GetPet();
2227 if(pet && pet->getPetType()==SUMMON_PET)
2228 pet->GivePetLevel(level);
2229 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2232 void Player::InitTalentForLevel()
2234 uint32 level = getLevel();
2235 // talents base at level diff ( talents = level - 9 but some can be used already)
2236 if(level < 10)
2238 // Remove all talent points
2239 if(m_usedTalentCount > 0) // Free any used talents
2241 resetTalents(true);
2242 SetFreeTalentPoints(0);
2245 else
2247 uint32 talentPointsForLevel = CalculateTalentsPoints();
2249 // if used more that have then reset
2250 if(m_usedTalentCount > talentPointsForLevel)
2252 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2253 resetTalents(true);
2254 else
2255 SetFreeTalentPoints(0);
2257 // else update amount of free points
2258 else
2259 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2263 void Player::InitStatsForLevel(bool reapplyMods)
2265 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2266 _RemoveAllStatBonuses();
2268 PlayerClassLevelInfo classInfo;
2269 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2271 PlayerLevelInfo info;
2272 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2274 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2275 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2277 UpdateSkillsForLevel ();
2279 // set default cast time multiplier
2280 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2282 // reset size before reapply auras
2283 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2285 // save base values (bonuses already included in stored stats
2286 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2287 SetCreateStat(Stats(i), info.stats[i]);
2289 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2290 SetStat(Stats(i), info.stats[i]);
2292 SetCreateHealth(classInfo.basehealth);
2294 //set create powers
2295 SetCreateMana(classInfo.basemana);
2297 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2299 InitStatBuffMods();
2301 //reset rating fields values
2302 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2303 SetUInt32Value(index, 0);
2305 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2306 for (int i = 0; i < 7; i++)
2308 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2309 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2310 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2313 //reset attack power, damage and attack speed fields
2314 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2315 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2316 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2318 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2319 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2320 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2321 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2322 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2323 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2325 SetUInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2326 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2327 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2328 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2329 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2330 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2332 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2333 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2334 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2335 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2337 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2338 for (uint8 i = 0; i < 7; ++i)
2339 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2341 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2342 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2343 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2345 // Dodge percentage
2346 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2348 // set armor (resistance 0) to original value (create_agility*2)
2349 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2350 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2351 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2352 // set other resistance to original value (0)
2353 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2355 SetResistance(SpellSchools(i), 0);
2356 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2357 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2360 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2361 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2362 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2364 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2365 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2367 // Reset no reagent cost field
2368 for(int i = 0; i < 3; i++)
2369 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2370 // Init data for form but skip reapply item mods for form
2371 InitDataForForm(reapplyMods);
2373 // save new stats
2374 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2375 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2377 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2379 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2380 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2382 // cleanup unit flags (will be re-applied if need at aura load).
2383 RemoveFlag( UNIT_FIELD_FLAGS,
2384 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2385 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2386 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2387 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2388 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2389 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2391 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2392 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2394 SetByteValue(UNIT_FIELD_BYTES_1, 2, 0x00); // one form stealth modified bytes
2395 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2397 // restore if need some important flags
2398 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2400 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2401 _ApplyAllStatBonuses();
2403 // set current level health and mana/energy to maximum after applying all mods.
2404 SetHealth(GetMaxHealth());
2405 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2406 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2407 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2408 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2409 SetPower(POWER_FOCUS, 0);
2410 SetPower(POWER_HAPPINESS, 0);
2411 SetPower(POWER_RUNIC_POWER, 0);
2414 void Player::SendInitialSpells()
2416 uint16 spellCount = 0;
2418 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2419 data << uint8(0);
2421 size_t countPos = data.wpos();
2422 data << uint16(spellCount); // spell count placeholder
2424 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2426 if(itr->second->state == PLAYERSPELL_REMOVED)
2427 continue;
2429 if(!itr->second->active || itr->second->disabled)
2430 continue;
2432 data << uint16(itr->first);
2433 data << uint16(0); // it's not slot id
2435 spellCount +=1;
2438 data.put<uint16>(countPos,spellCount); // write real count value
2440 uint16 spellCooldowns = m_spellCooldowns.size();
2441 data << uint16(spellCooldowns);
2442 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2444 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2445 if(!sEntry)
2446 continue;
2448 data << uint16(itr->first);
2450 time_t cooldown = 0;
2451 time_t curTime = time(NULL);
2452 if(itr->second.end > curTime)
2453 cooldown = (itr->second.end-curTime)*1000;
2455 data << uint16(itr->second.itemid); // cast item id
2456 data << uint16(sEntry->Category); // spell category
2457 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2459 data << uint32(0); // cooldown
2460 data << uint32(cooldown); // category cooldown
2462 else
2464 data << uint32(cooldown); // cooldown
2465 data << uint32(0); // category cooldown
2469 GetSession()->SendPacket(&data);
2471 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2474 void Player::RemoveMail(uint32 id)
2476 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2478 if ((*itr)->messageID == id)
2480 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2481 m_mail.erase(itr);
2482 return;
2487 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2489 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2490 data << (uint32) mailId;
2491 data << (uint32) mailAction;
2492 data << (uint32) mailError;
2493 if ( mailError == MAIL_ERR_BAG_FULL )
2494 data << (uint32) equipError;
2495 else if( mailAction == MAIL_ITEM_TAKEN )
2497 data << (uint32) item_guid; // item guid low?
2498 data << (uint32) item_count; // item count?
2500 GetSession()->SendPacket(&data);
2503 void Player::SendNewMail()
2505 // deliver undelivered mail
2506 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2507 data << (uint32) 0;
2508 GetSession()->SendPacket(&data);
2511 void Player::UpdateNextMailTimeAndUnreads()
2513 // calculate next delivery time (min. from non-delivered mails
2514 // and recalculate unReadMail
2515 time_t cTime = time(NULL);
2516 m_nextMailDelivereTime = 0;
2517 unReadMails = 0;
2518 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2520 if((*itr)->deliver_time > cTime)
2522 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2523 m_nextMailDelivereTime = (*itr)->deliver_time;
2525 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2526 ++unReadMails;
2530 void Player::AddNewMailDeliverTime(time_t deliver_time)
2532 if(deliver_time <= time(NULL)) // ready now
2534 ++unReadMails;
2535 SendNewMail();
2537 else // not ready and no have ready mails
2539 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2540 m_nextMailDelivereTime = deliver_time;
2544 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2546 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2547 if (!spellInfo)
2549 // do character spell book cleanup (all characters)
2550 if(!IsInWorld() && !learning) // spell load case
2552 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2553 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2555 else
2556 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2558 return false;
2561 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2563 // do character spell book cleanup (all characters)
2564 if(!IsInWorld() && !learning) // spell load case
2566 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2567 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2569 else
2570 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2572 return false;
2575 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2577 bool dependent_set = false;
2578 bool disabled_case = false;
2579 bool superceded_old = false;
2581 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2582 if (itr != m_spells.end())
2584 uint32 next_active_spell_id = 0;
2585 // fix activate state for non-stackable low rank (and find next spell for !active case)
2586 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2588 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2589 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2591 if(HasSpell(next_itr->second))
2593 // high rank already known so this must !active
2594 active = false;
2595 next_active_spell_id = next_itr->second;
2596 break;
2601 // not do anything if already known in expected state
2602 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2603 itr->second->dependent == dependent && itr->second->disabled == disabled)
2604 return false;
2606 // dependent spell known as not dependent, overwrite state
2607 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2609 itr->second->dependent = dependent;
2610 if (itr->second->state != PLAYERSPELL_NEW)
2611 itr->second->state = PLAYERSPELL_CHANGED;
2612 dependent_set = true;
2615 // update active state for known spell
2616 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2618 itr->second->active = active;
2620 // !IsInWorld() && !learning == explicitly load from DB and then exist in it already and set correctly
2621 if(!IsInWorld() && !learning && !dependent_set)
2622 itr->second->state = PLAYERSPELL_UNCHANGED;
2623 else if(itr->second->state != PLAYERSPELL_NEW)
2624 itr->second->state = PLAYERSPELL_CHANGED;
2626 if(active)
2628 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2629 CastSpell (this,spell_id,true);
2631 else if(IsInWorld())
2633 if(next_active_spell_id)
2635 // update spell ranks in spellbook and action bar
2636 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2637 data << uint16(spell_id);
2638 data << uint16(next_active_spell_id);
2639 GetSession()->SendPacket( &data );
2641 else
2643 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2644 data << uint16(spell_id);
2645 GetSession()->SendPacket(&data);
2649 return active; // learn (show in spell book if active now)
2652 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2654 if(itr->second->state != PLAYERSPELL_NEW)
2655 itr->second->state = PLAYERSPELL_CHANGED;
2656 itr->second->disabled = disabled;
2658 if(disabled)
2659 return false;
2661 disabled_case = true;
2663 else switch(itr->second->state)
2665 case PLAYERSPELL_UNCHANGED: // known saved spell
2666 return false;
2667 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2669 delete itr->second;
2670 m_spells.erase(itr);
2671 state = PLAYERSPELL_CHANGED;
2672 break; // need re-add
2674 default: // known not saved yet spell (new or modified)
2676 // can be in case spell loading but learned at some previous spell loading
2677 if(!IsInWorld() && !learning && !dependent_set)
2678 itr->second->state = PLAYERSPELL_UNCHANGED;
2680 return false;
2685 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2687 // talent: unlearn all other talent ranks (high and low)
2688 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2690 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2692 for(int i=0; i <5; ++i)
2694 // skip learning spell and no rank spell case
2695 uint32 rankSpellId = talentInfo->RankID[i];
2696 if(!rankSpellId || rankSpellId==spell_id)
2697 continue;
2699 // skip unknown ranks
2700 if(!HasSpell(rankSpellId))
2701 continue;
2703 removeSpell(rankSpellId);
2707 // non talent spell: learn low ranks (recursive call)
2708 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2710 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2711 addSpell(prev_spell,active,true,true,disabled);
2712 else // at normal learning
2713 learnSpell(prev_spell,true);
2716 PlayerSpell *newspell = new PlayerSpell;
2717 newspell->state = state;
2718 newspell->active = active;
2719 newspell->dependent = dependent;
2720 newspell->disabled = disabled;
2722 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2723 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2725 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2727 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2728 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2729 if(!i_spellInfo) continue;
2731 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2733 if(itr->second->active)
2735 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2737 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2739 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2740 data << uint16(itr->first);
2741 data << uint16(spell_id);
2742 GetSession()->SendPacket( &data );
2745 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2746 itr->second->active = false;
2747 if(itr->second->state != PLAYERSPELL_NEW)
2748 itr->second->state = PLAYERSPELL_CHANGED;
2749 superceded_old = true; // new spell replace old in action bars and spell book.
2751 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2753 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2755 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2756 data << uint16(spell_id);
2757 data << uint16(itr->first);
2758 GetSession()->SendPacket( &data );
2761 // mark new spell as disable (not learned yet for client and will not learned)
2762 newspell->active = false;
2763 if(newspell->state != PLAYERSPELL_NEW)
2764 newspell->state = PLAYERSPELL_CHANGED;
2771 m_spells[spell_id] = newspell;
2773 // return false if spell disabled
2774 if (newspell->disabled)
2775 return false;
2778 uint32 talentCost = GetTalentSpellCost(spell_id);
2780 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2781 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2782 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2784 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2785 CastSpell(this, spell_id, true);
2787 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2788 else if (IsPassiveSpell(spell_id))
2790 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2791 CastSpell(this, spell_id, true);
2793 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2795 CastSpell(this, spell_id, true);
2796 return false;
2799 // update used talent points count
2800 m_usedTalentCount += talentCost;
2802 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2803 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2805 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2806 SetFreePrimaryProffesions(freeProfs-1);
2809 // add dependent skills
2810 uint16 maxskill = GetMaxSkillValueForLevel();
2812 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2814 if(spellLearnSkill)
2816 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2817 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2819 if(skill_value < spellLearnSkill->value)
2820 skill_value = spellLearnSkill->value;
2822 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2824 if(skill_max_value < new_skill_max_value)
2825 skill_max_value = new_skill_max_value;
2827 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2829 else
2831 // not ranked skills
2832 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2833 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2835 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2837 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2838 if(!pSkill)
2839 continue;
2841 if(HasSkill(pSkill->id))
2842 continue;
2844 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2845 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2846 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2848 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2850 case SKILL_RANGE_LANGUAGE:
2851 SetSkill(pSkill->id, 300, 300 );
2852 break;
2853 case SKILL_RANGE_LEVEL:
2854 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2855 break;
2856 case SKILL_RANGE_MONO:
2857 SetSkill(pSkill->id, 1, 1 );
2858 break;
2859 default:
2860 break;
2866 // learn dependent spells
2867 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2868 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2870 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2872 if(!itr->second.autoLearned)
2874 if(!IsInWorld() || !itr->second.active) // at spells loading, no output, but allow save
2875 addSpell(itr->second.spell,itr->second.active,true,true,false);
2876 else // at normal learning
2877 learnSpell(itr->second.spell,true);
2881 if(IsInWorld())
2883 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL);
2884 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS);
2887 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2888 return active && !disabled && !superceded_old;
2891 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
2893 bool need_cast = false;
2895 switch(spellInfo->Id)
2897 // some spells not have stance data expacted cast at form change or present
2898 case 5420: need_cast = (m_form == FORM_TREE); break;
2899 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
2900 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
2901 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
2902 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
2903 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
2904 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
2905 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
2906 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2907 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2908 // another spells have proper stance data
2909 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
2912 //Check CasterAuraStates
2913 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
2916 void Player::learnSpell(uint32 spell_id, bool dependent)
2918 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2920 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2921 bool active = disabled ? itr->second->active : true;
2923 bool learning = addSpell(spell_id,active,true,dependent,false);
2925 // learn all disabled higher ranks (recursive)
2926 if(disabled)
2928 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2929 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2931 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2932 if (iter != m_spells.end() && iter->second->disabled)
2933 learnSpell(i->second,false);
2937 // prevent duplicated entires in spell book, also not send if not in world (loading)
2938 if(!learning || !IsInWorld ())
2939 return;
2941 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2942 data << uint32(spell_id);
2943 GetSession()->SendPacket(&data);
2946 void Player::removeSpell(uint32 spell_id, bool disabled)
2948 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2949 if (itr == m_spells.end())
2950 return;
2952 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2953 return;
2955 // unlearn non talent higher ranks (recursive)
2956 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2957 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2958 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2959 removeSpell(itr2->second,disabled);
2961 bool cur_active = itr->second->active;
2962 bool cur_dependent = itr->second->dependent;
2964 if (disabled)
2966 itr->second->disabled = disabled;
2967 if(itr->second->state != PLAYERSPELL_NEW)
2968 itr->second->state = PLAYERSPELL_CHANGED;
2970 else
2972 if(itr->second->state == PLAYERSPELL_NEW)
2974 delete itr->second;
2975 m_spells.erase(itr);
2977 else
2978 itr->second->state = PLAYERSPELL_REMOVED;
2981 RemoveAurasDueToSpell(spell_id);
2983 // remove pet auras
2984 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2985 RemovePetAura(petSpell);
2987 // free talent points
2988 uint32 talentCosts = GetTalentSpellCost(spell_id);
2989 if(talentCosts > 0)
2991 if(talentCosts < m_usedTalentCount)
2992 m_usedTalentCount -= talentCosts;
2993 else
2994 m_usedTalentCount = 0;
2997 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2998 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3000 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
3001 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3002 SetFreePrimaryProffesions(freeProfs);
3005 // remove dependent skill
3006 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3007 if(spellLearnSkill)
3009 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3010 if(!prev_spell) // first rank, remove skill
3011 SetSkill(spellLearnSkill->skill,0,0);
3012 else
3014 // search prev. skill setting by spell ranks chain
3015 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3016 while(!prevSkill && prev_spell)
3018 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3019 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3022 if(!prevSkill) // not found prev skill setting, remove skill
3023 SetSkill(spellLearnSkill->skill,0,0);
3024 else // set to prev. skill setting values
3026 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3027 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3029 if(skill_value > prevSkill->value)
3030 skill_value = prevSkill->value;
3032 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3034 if(skill_max_value > new_skill_max_value)
3035 skill_max_value = new_skill_max_value;
3037 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3042 else
3044 // not ranked skills
3045 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3046 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3048 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3050 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3051 if(!pSkill)
3052 continue;
3054 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3055 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3056 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
3058 // not reset skills for professions and racial abilities
3059 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3060 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3061 continue;
3063 SetSkill(pSkill->id, 0, 0 );
3068 // remove dependent spells
3069 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3070 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3072 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3073 removeSpell(itr2->second.spell, disabled);
3075 // activate lesser rank in spellbook/action bar, and cast it if need
3076 bool prev_activate = false;
3078 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3080 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3082 // if talent then lesser rank also talen and need learn
3083 if(talentCosts)
3084 learnSpell (prev_id,false);
3085 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3086 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3088 // need manually update dependence state (learn spell ignore like attempts)
3089 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3090 if (prev_itr != m_spells.end())
3092 if(prev_itr->second->dependent != cur_dependent)
3094 prev_itr->second->dependent = cur_dependent;
3095 if(prev_itr->second->state != PLAYERSPELL_NEW)
3096 prev_itr->second->state = PLAYERSPELL_CHANGED;
3099 // now re-learn if need re-activate
3100 if(cur_active && !prev_itr->second->active)
3102 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3104 // downgrade spell ranks in spellbook and action bar
3105 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
3106 data << uint16(spell_id);
3107 data << uint16(prev_id);
3108 GetSession()->SendPacket( &data );
3109 prev_activate = true;
3116 // remove from spell book if not replaced by lesser rank
3117 if(!prev_activate)
3119 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3120 data << uint16(spell_id);
3121 GetSession()->SendPacket(&data);
3125 void Player::RemoveArenaSpellCooldowns()
3127 // remove cooldowns on spells that has < 15 min CD
3128 SpellCooldowns::iterator itr, next;
3129 // iterate spell cooldowns
3130 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3132 next = itr;
3133 ++next;
3134 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3135 // check if spellentry is present and if the cooldown is less than 15 mins
3136 if( entry &&
3137 entry->RecoveryTime <= 15 * MINUTE * 1000 &&
3138 entry->CategoryRecoveryTime <= 15 * MINUTE * 1000 )
3140 // notify player
3141 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3142 data << uint32(itr->first);
3143 data << GetGUID();
3144 GetSession()->SendPacket(&data);
3145 // remove cooldown
3146 m_spellCooldowns.erase(itr);
3151 void Player::RemoveAllSpellCooldown()
3153 if(!m_spellCooldowns.empty())
3155 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3157 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3158 data << uint32(itr->first);
3159 data << uint64(GetGUID());
3160 GetSession()->SendPacket(&data);
3162 m_spellCooldowns.clear();
3166 void Player::_LoadSpellCooldowns(QueryResult *result)
3168 m_spellCooldowns.clear();
3170 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3172 if(result)
3174 time_t curTime = time(NULL);
3178 Field *fields = result->Fetch();
3180 uint32 spell_id = fields[0].GetUInt32();
3181 uint32 item_id = fields[1].GetUInt32();
3182 time_t db_time = (time_t)fields[2].GetUInt64();
3184 if(!sSpellStore.LookupEntry(spell_id))
3186 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3187 continue;
3190 // skip outdated cooldown
3191 if(db_time <= curTime)
3192 continue;
3194 AddSpellCooldown(spell_id, item_id, db_time);
3196 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3198 while( result->NextRow() );
3200 delete result;
3204 void Player::_SaveSpellCooldowns()
3206 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3208 time_t curTime = time(NULL);
3210 // remove outdated and save active
3211 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3213 if(itr->second.end <= curTime)
3214 m_spellCooldowns.erase(itr++);
3215 else
3217 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));
3218 ++itr;
3223 uint32 Player::resetTalentsCost() const
3225 // The first time reset costs 1 gold
3226 if(m_resetTalentsCost < 1*GOLD)
3227 return 1*GOLD;
3228 // then 5 gold
3229 else if(m_resetTalentsCost < 5*GOLD)
3230 return 5*GOLD;
3231 // After that it increases in increments of 5 gold
3232 else if(m_resetTalentsCost < 10*GOLD)
3233 return 10*GOLD;
3234 else
3236 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3237 if(months > 0)
3239 // This cost will be reduced by a rate of 5 gold per month
3240 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3241 // to a minimum of 10 gold.
3242 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3244 else
3246 // After that it increases in increments of 5 gold
3247 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3248 // until it hits a cap of 50 gold.
3249 if(new_cost > 50*GOLD)
3250 new_cost = 50*GOLD;
3251 return new_cost;
3256 bool Player::resetTalents(bool no_cost)
3258 // not need after this call
3259 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3261 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3262 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3265 uint32 talentPointsForLevel = CalculateTalentsPoints();
3267 if (m_usedTalentCount == 0)
3269 SetFreeTalentPoints(talentPointsForLevel);
3270 return false;
3273 uint32 cost = 0;
3275 if(!no_cost)
3277 cost = resetTalentsCost();
3279 if (GetMoney() < cost)
3281 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3282 return false;
3286 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3288 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3290 if (!talentInfo) continue;
3292 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3294 if(!talentTabInfo)
3295 continue;
3297 // unlearn only talents for character class
3298 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3299 // to prevent unexpected lost normal learned spell skip another class talents
3300 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3301 continue;
3303 for (int j = 0; j < 5; j++)
3305 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3307 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3309 ++itr;
3310 continue;
3313 // remove learned spells (all ranks)
3314 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3316 // unlearn if first rank is talent or learned by talent
3317 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3319 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3320 itr = GetSpellMap().begin();
3321 continue;
3323 else
3324 ++itr;
3329 SetFreeTalentPoints(talentPointsForLevel);
3331 if(!no_cost)
3333 ModifyMoney(-(int32)cost);
3335 m_resetTalentsCost = cost;
3336 m_resetTalentsTime = time(NULL);
3339 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3340 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3342 return true;
3345 bool Player::_removeSpell(uint16 spell_id)
3347 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3348 if (itr != m_spells.end())
3350 delete itr->second;
3351 m_spells.erase(itr);
3352 return true;
3354 return false;
3357 Mail* Player::GetMail(uint32 id)
3359 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3361 if ((*itr)->messageID == id)
3363 return (*itr);
3366 return NULL;
3369 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3371 if(target == this)
3373 Object::_SetCreateBits(updateMask, target);
3375 else
3377 for(uint16 index = 0; index < m_valuesCount; index++)
3379 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3380 updateMask->SetBit(index);
3385 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3387 if(target == this)
3389 Object::_SetUpdateBits(updateMask, target);
3391 else
3393 Object::_SetUpdateBits(updateMask, target);
3394 *updateMask &= updateVisualBits;
3398 void Player::InitVisibleBits()
3400 updateVisualBits.SetCount(PLAYER_END);
3402 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3403 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3404 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3405 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3406 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3407 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3408 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3409 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3410 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3411 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3412 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3413 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3414 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3415 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3416 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3417 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3418 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3419 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3420 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3421 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3422 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3423 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3424 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3425 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3426 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3427 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3428 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3429 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3430 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3431 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3432 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3433 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3434 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3435 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3436 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3437 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3438 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3439 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3440 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3441 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3442 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3443 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3444 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3445 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3446 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3447 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3448 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3449 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3450 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3451 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3452 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3453 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3454 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3455 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3456 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3458 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3459 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3460 updateVisualBits.SetBit(PLAYER_FLAGS);
3461 updateVisualBits.SetBit(PLAYER_GUILDID);
3462 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3463 updateVisualBits.SetBit(PLAYER_BYTES);
3464 updateVisualBits.SetBit(PLAYER_BYTES_2);
3465 updateVisualBits.SetBit(PLAYER_BYTES_3);
3466 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3467 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3469 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3470 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3471 updateVisualBits.SetBit(i);
3473 // Players visible items are not inventory stuff
3474 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3476 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3478 // item creator
3479 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3480 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3482 // item entry
3483 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3485 // item enchantments
3486 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3487 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3489 // random properties
3490 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3491 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3492 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3495 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3498 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3500 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3502 if(m_items[i] == NULL)
3503 continue;
3505 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3508 if(target == this)
3510 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3512 if(m_items[i] == NULL)
3513 continue;
3515 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3517 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3519 if(m_items[i] == NULL)
3520 continue;
3522 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3526 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3529 void Player::DestroyForPlayer( Player *target ) const
3531 Unit::DestroyForPlayer( target );
3533 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3535 if(m_items[i] == NULL)
3536 continue;
3538 m_items[i]->DestroyForPlayer( target );
3541 if(target == this)
3543 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3545 if(m_items[i] == NULL)
3546 continue;
3548 m_items[i]->DestroyForPlayer( target );
3550 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3552 if(m_items[i] == NULL)
3553 continue;
3555 m_items[i]->DestroyForPlayer( target );
3560 bool Player::HasSpell(uint32 spell) const
3562 PlayerSpellMap::const_iterator itr = m_spells.find((uint16)spell);
3563 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled);
3566 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3568 if (!trainer_spell)
3569 return TRAINER_SPELL_RED;
3571 if (!trainer_spell->learned_spell)
3572 return TRAINER_SPELL_RED;
3574 // known spell
3575 if(HasSpell(trainer_spell->learned_spell))
3576 return TRAINER_SPELL_GRAY;
3578 // check race/class requirement
3579 if(!IsSpellFitByClassAndRace(trainer_spell->learned_spell))
3580 return TRAINER_SPELL_RED;
3582 // check level requirement
3583 if(getLevel() < trainer_spell->reqlevel)
3584 return TRAINER_SPELL_RED;
3586 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learned_spell))
3588 // check prev.rank requirement
3589 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3590 return TRAINER_SPELL_RED;
3592 // check additional spell requirement
3593 if(spell_chain->req && !HasSpell(spell_chain->req))
3594 return TRAINER_SPELL_RED;
3597 // check skill requirement
3598 if(trainer_spell->reqskill && GetBaseSkillValue(trainer_spell->reqskill) < trainer_spell->reqskillvalue)
3599 return TRAINER_SPELL_RED;
3601 // exist, already checked at loading
3602 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learned_spell);
3604 // secondary prof. or not prof. spell
3605 uint32 skill = spell->EffectMiscValue[1];
3607 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3608 return TRAINER_SPELL_GREEN;
3610 // check primary prof. limit
3611 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3612 return TRAINER_SPELL_RED;
3614 return TRAINER_SPELL_GREEN;
3617 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3619 uint32 guid = GUID_LOPART(playerguid);
3621 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3622 // bones will be deleted by corpse/bones deleting thread shortly
3623 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3625 // remove from guild
3626 uint32 guildId = GetGuildIdFromDB(playerguid);
3627 if(guildId != 0)
3629 Guild* guild = objmgr.GetGuildById(guildId);
3630 if(guild)
3631 guild->DelMember(guid);
3634 // remove from arena teams
3635 LeaveAllArenaTeams(playerguid);
3637 // the player was uninvited already on logout so just remove from group
3638 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3639 if(resultGroup)
3641 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3642 delete resultGroup;
3643 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3644 if(group)
3646 RemoveFromGroup(group, playerguid);
3650 // remove signs from petitions (also remove petitions if owner);
3651 RemovePetitionsAndSigns(playerguid, 10);
3653 // return back all mails with COD and Item 0 1 2 3 4 5 6
3654 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);
3655 if(resultMail)
3659 Field *fields = resultMail->Fetch();
3661 uint32 mail_id = fields[0].GetUInt32();
3662 uint16 mailTemplateId= fields[1].GetUInt16();
3663 uint32 sender = fields[2].GetUInt32();
3664 std::string subject = fields[3].GetCppString();
3665 uint32 itemTextId = fields[4].GetUInt32();
3666 uint32 money = fields[5].GetUInt32();
3667 bool has_items = fields[6].GetBool();
3669 //we can return mail now
3670 //so firstly delete the old one
3671 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3673 MailItemsInfo mi;
3674 if(has_items)
3676 // data needs to be at first place for Item::LoadFromDB
3677 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);
3678 if(resultItems)
3682 Field *fields2 = resultItems->Fetch();
3684 uint32 item_guidlow = fields2[1].GetUInt32();
3685 uint32 item_template = fields2[2].GetUInt32();
3687 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3688 if(!itemProto)
3690 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3691 continue;
3694 Item *pItem = NewItemOrBag(itemProto);
3695 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3697 pItem->FSetState(ITEM_REMOVED);
3698 pItem->SaveToDB(); // it also deletes item object !
3699 continue;
3702 mi.AddItem(item_guidlow, item_template, pItem);
3704 while (resultItems->NextRow());
3706 delete resultItems;
3710 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3712 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3714 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3716 while (resultMail->NextRow());
3718 delete resultMail;
3721 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3722 // Get guids of character's pets, will deleted in transaction
3723 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3725 // NOW we can finally clear other DB data related to character
3726 CharacterDatabase.BeginTransaction();
3727 if (resultPets)
3731 Field *fields3 = resultPets->Fetch();
3732 uint32 petguidlow = fields3[0].GetUInt32();
3733 Pet::DeleteFromDB(petguidlow);
3734 } while (resultPets->NextRow());
3735 delete resultPets;
3738 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3739 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3740 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3741 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3742 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3743 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3744 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3745 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3746 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3747 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3748 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3749 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3750 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3751 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3752 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3753 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3754 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3755 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3756 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3757 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3758 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3759 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3760 CharacterDatabase.CommitTransaction();
3762 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3763 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3766 void Player::SetMovement(PlayerMovementType pType)
3768 WorldPacket data;
3769 switch(pType)
3771 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3772 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3773 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3774 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3775 default:
3776 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3777 return;
3779 data.append(GetPackGUID());
3780 data << uint32(0);
3781 GetSession()->SendPacket( &data );
3784 /* Preconditions:
3785 - a resurrectable corpse must not be loaded for the player (only bones)
3786 - the player must be in world
3788 void Player::BuildPlayerRepop()
3790 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3791 data.append(GetPackGUID());
3792 GetSession()->SendPacket(&data);
3794 if(getRace() == RACE_NIGHTELF)
3795 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)
3796 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3798 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3799 // there must be SMSG.STOP_MIRROR_TIMER
3800 // there we must send 888 opcode
3802 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3803 if(GetCorpse())
3805 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3806 assert(false);
3809 // create a corpse and place it at the player's location
3810 CreateCorpse();
3811 Corpse *corpse = GetCorpse();
3812 if(!corpse)
3814 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3815 return;
3817 GetMap()->Add(corpse);
3819 // convert player body to ghost
3820 SetHealth( 1 );
3822 SetMovement(MOVE_WATER_WALK);
3823 if(!GetSession()->isLogingOut())
3824 SetMovement(MOVE_UNROOT);
3826 // BG - remove insignia related
3827 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3829 SendCorpseReclaimDelay();
3831 // to prevent cheating
3832 corpse->ResetGhostTime();
3834 StopMirrorTimers(); //disable timers(bars)
3836 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3838 SetByteValue(UNIT_FIELD_BYTES_1, 3, PLAYER_STATE_FLAG_ALWAYS_STAND);
3841 void Player::SendDelayResponse(const uint32 ml_seconds)
3843 //FIXME: is this delay time arg really need? 50msec by default in code
3844 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3845 data << (uint32)time(NULL);
3846 data << (uint32)0;
3847 GetSession()->SendPacket( &data );
3850 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3852 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3853 data << uint32(-1);
3854 data << float(0);
3855 data << float(0);
3856 data << float(0);
3857 GetSession()->SendPacket(&data);
3859 // speed change, land walk
3861 // remove death flag + set aura
3862 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3863 if(getRace() == RACE_NIGHTELF)
3864 RemoveAurasDueToSpell(20584); // speed bonuses
3865 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3867 setDeathState(ALIVE);
3869 SetMovement(MOVE_LAND_WALK);
3870 SetMovement(MOVE_UNROOT);
3872 m_deathTimer = 0;
3874 // set health/powers (0- will be set in caller)
3875 if(restore_percent>0.0f)
3877 SetHealth(uint32(GetMaxHealth()*restore_percent));
3878 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3879 SetPower(POWER_RAGE, 0);
3880 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3883 // update visibility
3884 ObjectAccessor::UpdateVisibilityForPlayer(this);
3886 // some items limited to specific map
3887 DestroyZoneLimitedItem( true, GetZoneId());
3889 if(!applySickness)
3890 return;
3892 //Characters from level 1-10 are not affected by resurrection sickness.
3893 //Characters from level 11-19 will suffer from one minute of sickness
3894 //for each level they are above 10.
3895 //Characters level 20 and up suffer from ten minutes of sickness.
3896 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3898 if(int32(getLevel()) >= startLevel)
3900 // set resurrection sickness
3901 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3903 // not full duration
3904 if(int32(getLevel()) < startLevel+9)
3906 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3908 for(int i =0; i < 3; ++i)
3910 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3912 Aur->SetAuraDuration(delta*1000);
3913 Aur->SendAuraUpdate(false);
3920 void Player::KillPlayer()
3922 SetMovement(MOVE_ROOT);
3924 StopMirrorTimers(); //disable timers(bars)
3926 setDeathState(CORPSE);
3927 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3929 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3930 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3932 // 6 minutes until repop at graveyard
3933 m_deathTimer = 6*MINUTE*1000;
3935 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3937 // don't create corpse at this moment, player might be falling
3939 // update visibility
3940 ObjectAccessor::UpdateObjectVisibility(this);
3943 void Player::CreateCorpse()
3945 // prevent existence 2 corpse for player
3946 SpawnCorpseBones();
3948 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3950 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3951 SetPvPDeath(false);
3953 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this, GetMapId(), GetPositionX(),
3954 GetPositionY(), GetPositionZ(), GetOrientation()))
3956 delete corpse;
3957 return;
3960 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3961 _pb = GetUInt32Value(PLAYER_BYTES);
3962 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3964 uint8 race = (uint8)(_uf);
3965 uint8 skin = (uint8)(_pb);
3966 uint8 face = (uint8)(_pb >> 8);
3967 uint8 hairstyle = (uint8)(_pb >> 16);
3968 uint8 haircolor = (uint8)(_pb >> 24);
3969 uint8 facialhair = (uint8)(_pb2);
3971 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3972 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3974 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3975 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3977 uint32 flags = CORPSE_FLAG_UNK2;
3978 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3979 flags |= CORPSE_FLAG_HIDE_HELM;
3980 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3981 flags |= CORPSE_FLAG_HIDE_CLOAK;
3982 if(InBattleGround())
3983 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3984 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3986 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3988 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
3990 uint32 iDisplayID;
3991 uint16 iIventoryType;
3992 uint32 _cfi;
3993 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
3995 if(m_items[i])
3997 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
3998 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4000 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4001 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4005 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4006 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4007 assert(entry);
4008 if(entry->map_type != MAP_BATTLEGROUND)
4009 corpse->SaveToDB();
4011 // register for player, but not show
4012 ObjectAccessor::Instance().AddCorpse(corpse);
4015 void Player::SpawnCorpseBones()
4017 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4018 SaveToDB(); // prevent loading as ghost without corpse
4021 Corpse* Player::GetCorpse() const
4023 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4026 void Player::DurabilityLossAll(double percent, bool inventory)
4028 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
4029 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4030 DurabilityLoss(pItem,percent);
4032 if(inventory)
4034 // bags not have durability
4035 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4037 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
4038 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4039 DurabilityLoss(pItem,percent);
4041 // keys not have durability
4042 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4044 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4045 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4046 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
4047 if(Item* pItem = GetItemByPos( i, j ))
4048 DurabilityLoss(pItem,percent);
4052 void Player::DurabilityLoss(Item* item, double percent)
4054 if(!item )
4055 return;
4057 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4059 if(!pMaxDurability)
4060 return;
4062 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4064 if(pDurabilityLoss < 1 )
4065 pDurabilityLoss = 1;
4067 DurabilityPointsLoss(item,pDurabilityLoss);
4070 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4072 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
4073 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4074 DurabilityPointsLoss(pItem,points);
4076 if(inventory)
4078 // bags not have durability
4079 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4081 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
4082 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4083 DurabilityPointsLoss(pItem,points);
4085 // keys not have durability
4086 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4088 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4089 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4090 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
4091 if(Item* pItem = GetItemByPos( i, j ))
4092 DurabilityPointsLoss(pItem,points);
4096 void Player::DurabilityPointsLoss(Item* item, int32 points)
4098 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4099 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4100 int32 pNewDurability = pOldDurability - points;
4102 if (pNewDurability < 0)
4103 pNewDurability = 0;
4104 else if (pNewDurability > pMaxDurability)
4105 pNewDurability = pMaxDurability;
4107 if (pOldDurability != pNewDurability)
4109 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4110 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4111 _ApplyItemMods(item,item->GetSlot(), false);
4113 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4115 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4116 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4117 _ApplyItemMods(item,item->GetSlot(), true);
4119 item->SetState(ITEM_CHANGED, this);
4123 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4125 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4126 DurabilityPointsLoss(pItem,1);
4129 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4131 uint32 TotalCost = 0;
4132 // equipped, backpack, bags itself
4133 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
4134 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4136 // bank, buyback and keys not repaired
4138 // items in inventory bags
4139 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
4140 for(int i = 0; i < MAX_BAG_SIZE; i++)
4141 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4142 return TotalCost;
4145 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4147 Item* item = GetItemByPos(pos);
4149 uint32 TotalCost = 0;
4150 if(!item)
4151 return TotalCost;
4153 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4154 if(!maxDurability)
4155 return TotalCost;
4157 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4159 if(cost)
4161 uint32 LostDurability = maxDurability - curDurability;
4162 if(LostDurability>0)
4164 ItemPrototype const *ditemProto = item->GetProto();
4166 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4167 if(!dcost)
4169 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4170 return TotalCost;
4173 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4174 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4175 if(!dQualitymodEntry)
4177 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4178 return TotalCost;
4181 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4182 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4184 costs = uint32(costs * discountMod);
4186 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4187 costs = 1;
4189 if (guildBank)
4191 if (GetGuildId()==0)
4193 DEBUG_LOG("You are not member of a guild");
4194 return TotalCost;
4197 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4198 if (!pGuild)
4199 return TotalCost;
4201 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4203 DEBUG_LOG("You do not have rights to withdraw for repairs");
4204 return TotalCost;
4207 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4209 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4210 return TotalCost;
4213 if (pGuild->GetGuildBankMoney() < costs)
4215 DEBUG_LOG("There is not enough money in bank");
4216 return TotalCost;
4219 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4220 TotalCost = costs;
4222 else if (GetMoney() < costs)
4224 DEBUG_LOG("You do not have enough money");
4225 return TotalCost;
4227 else
4228 ModifyMoney( -int32(costs) );
4232 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4233 item->SetState(ITEM_CHANGED, this);
4235 // reapply mods for total broken and repaired item if equipped
4236 if(IsEquipmentPos(pos) && !curDurability)
4237 _ApplyItemMods(item,pos & 255, true);
4238 return TotalCost;
4241 void Player::RepopAtGraveyard()
4243 // note: this can be called also when the player is alive
4244 // for example from WorldSession::HandleMovementOpcodes
4246 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4248 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4249 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4251 ResurrectPlayer(0.5f);
4252 SpawnCorpseBones();
4255 WorldSafeLocsEntry const *ClosestGrave = NULL;
4257 // Special handle for battleground maps
4258 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
4260 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4261 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4262 else
4263 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4265 // stop countdown until repop
4266 m_deathTimer = 0;
4268 // if no grave found, stay at the current location
4269 // and don't show spirit healer location
4270 if(ClosestGrave)
4272 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4273 if(isDead()) // not send if alive, because it used in TeleportTo()
4275 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4276 data << ClosestGrave->map_id;
4277 data << ClosestGrave->x;
4278 data << ClosestGrave->y;
4279 data << ClosestGrave->z;
4280 GetSession()->SendPacket(&data);
4285 void Player::JoinedChannel(Channel *c)
4287 m_channels.push_back(c);
4290 void Player::LeftChannel(Channel *c)
4292 m_channels.remove(c);
4295 void Player::CleanupChannels()
4297 while(!m_channels.empty())
4299 Channel* ch = *m_channels.begin();
4300 m_channels.erase(m_channels.begin()); // remove from player's channel list
4301 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4302 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4303 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4306 sLog.outDebug("Player: channels cleaned up!");
4309 void Player::UpdateLocalChannels(uint32 newZone )
4311 if(m_channels.empty())
4312 return;
4314 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4315 if(!current_zone)
4316 return;
4318 ChannelMgr* cMgr = channelMgr(GetTeam());
4319 if(!cMgr)
4320 return;
4322 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4324 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4326 next = i; ++next;
4328 // skip non built-in channels
4329 if(!(*i)->IsConstant())
4330 continue;
4332 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4333 if(!ch)
4334 continue;
4336 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4337 continue;
4339 // new channel
4340 char new_channel_name_buf[100];
4341 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4342 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4344 if((*i)!=new_channel)
4346 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4348 // leave old channel
4349 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4350 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4351 LeftChannel(*i); // remove from player's channel list
4352 cMgr->LeftChannel(name); // delete if empty
4355 sLog.outDebug("Player: channels cleaned up!");
4358 void Player::LeaveLFGChannel()
4360 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4362 if((*i)->IsLFG())
4364 (*i)->Leave(GetGUID());
4365 break;
4370 void Player::UpdateDefense()
4372 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4374 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4376 // update dependent from defense skill part
4377 UpdateDefenseBonusesMod();
4381 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4383 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4385 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4386 return;
4389 float val = 1.0f;
4391 switch(modType)
4393 case FLAT_MOD:
4394 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4395 break;
4396 case PCT_MOD:
4397 if(amount <= -100.0f)
4398 amount = -200.0f;
4400 val = (100.0f + amount) / 100.0f;
4401 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4402 break;
4405 if(!CanModifyStats())
4406 return;
4408 switch(modGroup)
4410 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4411 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4412 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4413 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4414 default: break;
4418 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4420 if(modGroup >= BASEMOD_END || modType > MOD_END)
4422 sLog.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4423 return 0.0f;
4426 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4427 return 0.0f;
4429 return m_auraBaseMod[modGroup][modType];
4432 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4434 if(modGroup >= BASEMOD_END)
4436 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4437 return 0.0f;
4440 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4441 return 0.0f;
4443 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4446 uint32 Player::GetShieldBlockValue() const
4448 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4450 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH) * 0.5f - 10;
4452 value = (value < 0) ? 0 : value;
4454 return uint32(value);
4457 float Player::GetMeleeCritFromAgility()
4459 uint32 level = getLevel();
4460 uint32 pclass = getClass();
4462 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4464 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4465 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4466 if (critBase==NULL || critRatio==NULL)
4467 return 0.0f;
4469 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4470 return crit*100.0f;
4473 float Player::GetDodgeFromAgility()
4475 // Table for base dodge values
4476 float dodge_base[MAX_CLASSES] = {
4477 0.0075f, // Warrior
4478 0.00652f, // Paladin
4479 -0.0545f, // Hunter
4480 -0.0059f, // Rogue
4481 0.03183f, // Priest
4482 0.0114f, // DK
4483 0.0167f, // Shaman
4484 0.034575f, // Mage
4485 0.02011f, // Warlock
4486 0.0f, // ??
4487 -0.0187f // Druid
4489 // Crit/agility to dodge/agility coefficient multipliers
4490 float crit_to_dodge[MAX_CLASSES] = {
4491 1.1f, // Warrior
4492 1.0f, // Paladin
4493 1.6f, // Hunter
4494 2.0f, // Rogue
4495 1.0f, // Priest
4496 1.0f, // DK?
4497 1.0f, // Shaman
4498 1.0f, // Mage
4499 1.0f, // Warlock
4500 0.0f, // ??
4501 1.7f // Druid
4504 uint32 level = getLevel();
4505 uint32 pclass = getClass();
4507 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4509 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4510 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4511 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4512 return 0.0f;
4514 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4515 return dodge*100.0f;
4518 float Player::GetSpellCritFromIntellect()
4520 uint32 level = getLevel();
4521 uint32 pclass = getClass();
4523 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4525 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4526 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4527 if (critBase==NULL || critRatio==NULL)
4528 return 0.0f;
4530 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4531 return crit*100.0f;
4534 float Player::GetRatingCoefficient(CombatRating cr) const
4536 uint32 level = getLevel();
4538 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4540 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4541 if (Rating == NULL)
4542 return 1.0f; // By default use minimum coefficient (not must be called)
4544 return Rating->ratio;
4547 float Player::GetRatingBonusValue(CombatRating cr) const
4549 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4552 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4554 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4555 if (melee>25.0f) melee = 25.0f;
4556 return uint32 (melee * damage /100.0f);
4559 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4561 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4562 if (ranged>25.0f) ranged=25.0f;
4563 return uint32 (ranged * damage /100.0f);
4566 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4568 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4569 // In wow script resilience limited to 25%
4570 if (spell>25.0f)
4571 spell = 25.0f;
4572 return uint32 (spell * damage / 100.0f);
4575 uint32 Player::GetDotDamageReduction(uint32 damage) const
4577 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4578 // Dot resilience not limited (limit it by 100%)
4579 if (spellDot > 100.0f)
4580 spellDot = 100.0f;
4581 return uint32 (spellDot * damage / 100.0f);
4584 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4586 switch (attType)
4588 case BASE_ATTACK:
4589 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4590 case OFF_ATTACK:
4591 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4592 default:
4593 break;
4595 return 0.0f;
4598 float Player::OCTRegenHPPerSpirit()
4600 uint32 level = getLevel();
4601 uint32 pclass = getClass();
4603 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4605 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4606 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4607 if (baseRatio==NULL || moreRatio==NULL)
4608 return 0.0f;
4610 // Formula from PaperDollFrame script
4611 float spirit = GetStat(STAT_SPIRIT);
4612 float baseSpirit = spirit;
4613 if (baseSpirit>50) baseSpirit = 50;
4614 float moreSpirit = spirit - baseSpirit;
4615 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4616 return regen;
4619 float Player::OCTRegenMPPerSpirit()
4621 uint32 level = getLevel();
4622 uint32 pclass = getClass();
4624 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4626 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4627 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4628 if (moreRatio==NULL)
4629 return 0.0f;
4631 // Formula get from PaperDollFrame script
4632 float spirit = GetStat(STAT_SPIRIT);
4633 float regen = spirit * moreRatio->ratio;
4634 return regen;
4637 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4639 m_baseRatingValue[cr]+=(apply ? value : -value);
4641 int32 amount = uint32(m_baseRatingValue[cr]);
4642 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4643 // stat used stored in miscValueB for this aura
4644 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4645 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4646 if ((*i)->GetMiscValue() & (1<<cr))
4647 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4648 if (amount < 0)
4649 amount = 0;
4650 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4652 float RatingCoeffecient = GetRatingCoefficient(cr);
4653 float RatingChange = 0.0f;
4655 bool affectStats = CanModifyStats();
4657 switch (cr)
4659 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4660 case CR_DEFENSE_SKILL:
4661 UpdateDefenseBonusesMod();
4662 break;
4663 case CR_DODGE:
4664 UpdateDodgePercentage();
4665 break;
4666 case CR_PARRY:
4667 UpdateParryPercentage();
4668 break;
4669 case CR_BLOCK:
4670 UpdateBlockPercentage();
4671 break;
4672 case CR_HIT_MELEE:
4673 UpdateMeleeHitChances();
4674 break;
4675 case CR_HIT_RANGED:
4676 UpdateRangedHitChances();
4677 break;
4678 case CR_HIT_SPELL:
4679 UpdateSpellHitChances();
4680 break;
4681 case CR_CRIT_MELEE:
4682 if(affectStats)
4684 UpdateCritPercentage(BASE_ATTACK);
4685 UpdateCritPercentage(OFF_ATTACK);
4687 break;
4688 case CR_CRIT_RANGED:
4689 if(affectStats)
4690 UpdateCritPercentage(RANGED_ATTACK);
4691 break;
4692 case CR_CRIT_SPELL:
4693 if(affectStats)
4694 UpdateAllSpellCritChances();
4695 break;
4696 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4697 case CR_HIT_TAKEN_RANGED:
4698 break;
4699 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4700 break;
4701 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4702 case CR_CRIT_TAKEN_RANGED:
4703 break;
4704 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4705 break;
4706 case CR_HASTE_MELEE:
4707 RatingChange = value / RatingCoeffecient;
4708 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4709 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4710 break;
4711 case CR_HASTE_RANGED:
4712 RatingChange = value / RatingCoeffecient;
4713 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4714 break;
4715 case CR_HASTE_SPELL:
4716 RatingChange = value / RatingCoeffecient;
4717 ApplyCastTimePercentMod(RatingChange,apply);
4718 break;
4719 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4720 case CR_WEAPON_SKILL_OFFHAND:
4721 case CR_WEAPON_SKILL_RANGED:
4722 break;
4723 case CR_EXPERTISE:
4724 if(affectStats)
4726 UpdateExpertise(BASE_ATTACK);
4727 UpdateExpertise(OFF_ATTACK);
4729 break;
4733 void Player::SetRegularAttackTime()
4735 for(int i = 0; i < MAX_ATTACK; ++i)
4737 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4738 if(tmpitem && !tmpitem->IsBroken())
4740 ItemPrototype const *proto = tmpitem->GetProto();
4741 if(proto->Delay)
4742 SetAttackTime(WeaponAttackType(i), proto->Delay);
4743 else
4744 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4749 //skill+step, checking for max value
4750 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4752 if(!skill_id)
4753 return false;
4755 uint16 i=0;
4756 for (; i < PLAYER_MAX_SKILLS; i++)
4757 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4758 break;
4760 if(i>=PLAYER_MAX_SKILLS)
4761 return false;
4763 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4764 uint32 value = SKILL_VALUE(data);
4765 uint32 max = SKILL_MAX(data);
4767 if ((!max) || (!value) || (value >= max))
4768 return false;
4770 if (value*512 < max*urand(0,512))
4772 uint32 new_value = value+step;
4773 if(new_value > max)
4774 new_value = max;
4776 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4777 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4778 return true;
4781 return false;
4784 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4786 if ( SkillValue >= GrayLevel )
4787 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4788 if ( SkillValue >= GreenLevel )
4789 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4790 if ( SkillValue >= YellowLevel )
4791 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4792 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4795 bool Player::UpdateCraftSkill(uint32 spellid)
4797 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4799 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4800 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4802 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4804 if(_spell_idx->second->skillId)
4806 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4808 // Alchemy Discoveries here
4809 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4810 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4812 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4813 learnSpell(discoveredSpell,false);
4816 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4818 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4819 _spell_idx->second->max_value,
4820 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4821 _spell_idx->second->min_value),
4822 craft_skill_gain);
4825 return false;
4828 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4830 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4832 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4834 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4835 switch (SkillId)
4837 case SKILL_HERBALISM:
4838 case SKILL_LOCKPICKING:
4839 case SKILL_JEWELCRAFTING:
4840 case SKILL_INSCRIPTION:
4841 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4842 case SKILL_SKINNING:
4843 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4844 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4845 else
4846 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4847 case SKILL_MINING:
4848 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4849 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4850 else
4851 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4853 return false;
4856 bool Player::UpdateFishingSkill()
4858 sLog.outDebug("UpdateFishingSkill");
4860 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4862 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4864 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4866 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4869 // levels sync. with spell requirement for skill levels to learn
4870 // bonus abilities in sSkillLineAbilityStore
4871 // Used only to avoid scan DBC at each skill grow
4872 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
4874 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4876 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4877 if ( !SkillId )
4878 return false;
4880 if(Chance <= 0) // speedup in 0 chance case
4882 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4883 return false;
4886 uint16 i=0;
4887 for (; i < PLAYER_MAX_SKILLS; i++)
4888 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4889 if ( i >= PLAYER_MAX_SKILLS )
4890 return false;
4892 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4893 uint16 SkillValue = SKILL_VALUE(data);
4894 uint16 MaxValue = SKILL_MAX(data);
4896 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4897 return false;
4899 int32 Roll = irand(1,1000);
4901 if ( Roll <= Chance )
4903 uint32 new_value = SkillValue+step;
4904 if(new_value > MaxValue)
4905 new_value = MaxValue;
4907 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4908 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
4910 if((SkillValue < *bsl && new_value >= *bsl))
4912 learnSkillRewardedSpells( SkillId, new_value);
4913 break;
4916 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4917 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4918 return true;
4921 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4922 return false;
4925 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4927 // no skill gain in pvp
4928 Unit *pVictim = getVictim();
4929 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4930 return;
4932 if(IsInFeralForm())
4933 return; // always maximized SKILL_FERAL_COMBAT in fact
4935 if(m_form == FORM_TREE)
4936 return; // use weapon but not skill up
4938 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4940 switch(attType)
4942 case BASE_ATTACK:
4944 Item *tmpitem = GetWeaponForAttack(attType,true);
4946 if (!tmpitem)
4947 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4948 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4949 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4950 break;
4952 case OFF_ATTACK:
4953 case RANGED_ATTACK:
4955 Item *tmpitem = GetWeaponForAttack(attType,true);
4956 if (tmpitem)
4957 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4958 break;
4961 UpdateAllCritPercentages();
4964 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
4966 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4967 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4968 uint32 moblevel = pVictim->getLevelForTarget(this);
4969 if(moblevel < greylevel)
4970 return;
4972 if (moblevel > plevel + 5)
4973 moblevel = plevel + 5;
4975 uint32 lvldif = moblevel - greylevel;
4976 if(lvldif < 3)
4977 lvldif = 3;
4979 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4980 if(skilldif <= 0)
4981 return;
4983 float chance = float(3 * lvldif * skilldif) / plevel;
4984 if(!defence)
4986 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4987 chance *= 0.1f * GetStat(STAT_INTELLECT);
4990 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4992 if(roll_chance_f(chance))
4994 if(defence)
4995 UpdateDefense();
4996 else
4997 UpdateWeaponSkill(attType);
4999 else
5000 return;
5003 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5005 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5006 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5008 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5009 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5010 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5012 if(talent) // permanent bonus stored in high part
5013 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5014 else // temporary/item bonus stored in low part
5015 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5016 return;
5020 void Player::UpdateSkillsForLevel()
5022 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5023 uint32 maxSkill = GetMaxSkillValueForLevel();
5025 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5027 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5028 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5030 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5032 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5033 if(!pSkill)
5034 continue;
5036 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5037 continue;
5039 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5040 uint32 max = SKILL_MAX(data);
5041 uint32 val = SKILL_VALUE(data);
5043 /// update only level dependent max skill values
5044 if(max!=1)
5046 /// miximize skill always
5047 if(alwaysMaxSkill)
5048 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5049 /// update max skill value if current max skill not maximized
5050 else if(max != maxconfskill)
5051 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5056 void Player::UpdateSkillsToMaxSkillsForLevel()
5058 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5059 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5061 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5062 if( IsProfessionOrRidingSkill(pskill))
5063 continue;
5064 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5066 uint32 max = SKILL_MAX(data);
5068 if(max > 1)
5069 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5071 if(pskill == SKILL_DEFENSE)
5072 UpdateDefenseBonusesMod();
5076 // This functions sets a skill line value (and adds if doesn't exist yet)
5077 // To "remove" a skill line, set it's values to zero
5078 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5080 if(!id)
5081 return;
5083 uint16 i=0;
5084 for (; i < PLAYER_MAX_SKILLS; i++)
5085 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5087 if(i<PLAYER_MAX_SKILLS) //has skill
5089 if(currVal)
5091 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5092 learnSkillRewardedSpells(id, currVal);
5093 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
5095 else //remove
5097 // clear skill fields
5098 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5099 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5100 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5102 // remove spells that depend on this skill when removing the skill
5103 learnSkillRewardedSpells(id, 0);
5106 else if(currVal) //add
5108 for (i=0; i < PLAYER_MAX_SKILLS; i++)
5109 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5111 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5112 if(!pSkill)
5114 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5115 return;
5117 // enable unlearn button for primary professions only
5118 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5119 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5120 else
5121 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5122 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5123 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
5125 // apply skill bonuses
5126 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5128 // temporary bonuses
5129 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5130 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
5131 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5132 (*i)->ApplyModifier(true);
5134 // permanent bonuses
5135 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5136 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
5137 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5138 (*i)->ApplyModifier(true);
5140 // Learn all spells for skill
5141 learnSkillRewardedSpells(id, currVal);
5142 return;
5147 bool Player::HasSkill(uint32 skill) const
5149 if(!skill)return false;
5150 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5152 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5154 return true;
5157 return false;
5160 uint16 Player::GetSkillValue(uint32 skill) const
5162 if(!skill)
5163 return 0;
5165 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5167 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5169 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5171 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5172 result += SKILL_TEMP_BONUS(bonus);
5173 result += SKILL_PERM_BONUS(bonus);
5174 return result < 0 ? 0 : result;
5177 return 0;
5180 uint16 Player::GetMaxSkillValue(uint32 skill) const
5182 if(!skill)return 0;
5183 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5185 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5187 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5189 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5190 result += SKILL_TEMP_BONUS(bonus);
5191 result += SKILL_PERM_BONUS(bonus);
5192 return result < 0 ? 0 : result;
5195 return 0;
5198 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5200 if(!skill)return 0;
5201 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5203 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5205 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5208 return 0;
5211 uint16 Player::GetBaseSkillValue(uint32 skill) const
5213 if(!skill)return 0;
5214 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5216 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5218 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5219 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5220 return result < 0 ? 0 : result;
5223 return 0;
5226 uint16 Player::GetPureSkillValue(uint32 skill) const
5228 if(!skill)return 0;
5229 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5231 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5233 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5236 return 0;
5239 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5241 if(!skill)
5242 return 0;
5244 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5246 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5248 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5252 return 0;
5255 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5257 if(!skill)
5258 return 0;
5260 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5262 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5264 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5268 return 0;
5271 void Player::SendInitialActionButtons()
5273 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5275 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5276 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5278 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5279 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5281 data << uint16(itr->second.action);
5282 data << uint8(itr->second.misc);
5283 data << uint8(itr->second.type);
5285 else
5287 data << uint32(0);
5291 GetSession()->SendPacket( &data );
5292 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5295 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5297 if(button >= MAX_ACTION_BUTTONS)
5299 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5300 return;
5303 // check cheating with adding non-known spells to action bar
5304 if(type==ACTION_BUTTON_SPELL)
5306 if(!sSpellStore.LookupEntry(action))
5308 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5309 return;
5312 if(!HasSpell(action))
5314 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5315 return;
5319 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5321 if (buttonItr==m_actionButtons.end())
5322 { // just add new button
5323 m_actionButtons[button] = ActionButton(action,type,misc);
5325 else
5326 { // change state of current button
5327 ActionButtonUpdateState uState = buttonItr->second.uState;
5328 buttonItr->second = ActionButton(action,type,misc);
5329 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5332 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5335 void Player::removeActionButton(uint8 button)
5337 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5338 if (buttonItr==m_actionButtons.end())
5339 return;
5341 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5342 m_actionButtons.erase(buttonItr); // new and not saved
5343 else
5344 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5346 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5349 void Player::SetDontMove(bool dontMove)
5351 m_dontMove = dontMove;
5354 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5356 // prevent crash when a bad coord is sent by the client
5357 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5359 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5360 return false;
5363 Map *m = GetMap();
5365 const float old_x = GetPositionX();
5366 const float old_y = GetPositionY();
5367 const float old_z = GetPositionZ();
5368 const float old_r = GetOrientation();
5370 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5372 if (teleport || old_x != x || old_y != y || old_z != z)
5373 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5374 else
5375 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5377 // move and update visible state if need
5378 m->PlayerRelocation(this, x, y, z, orientation);
5380 // reread after Map::Relocation
5381 m = GetMap();
5382 x = GetPositionX();
5383 y = GetPositionY();
5384 z = GetPositionZ();
5386 // group update
5387 if(GetGroup() && (old_x != x || old_y != y))
5388 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5391 // code block for underwater state update
5392 UpdateUnderwaterState(m, x, y, z);
5394 CheckExploreSystem();
5396 return true;
5399 void Player::SaveRecallPosition()
5401 m_recallMap = GetMapId();
5402 m_recallX = GetPositionX();
5403 m_recallY = GetPositionY();
5404 m_recallZ = GetPositionZ();
5405 m_recallO = GetOrientation();
5408 void Player::SendMessageToSet(WorldPacket *data, bool self)
5410 GetMap()->MessageBroadcast(this, data, self);
5413 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5415 GetMap()->MessageDistBroadcast(this, data, dist, self);
5418 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5420 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5423 void Player::SendDirectMessage(WorldPacket *data)
5425 GetSession()->SendPacket(data);
5428 void Player::CheckExploreSystem()
5430 if (!isAlive())
5431 return;
5433 if (isInFlight())
5434 return;
5436 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5437 if(areaFlag==0xffff)
5438 return;
5439 int offset = areaFlag / 32;
5441 if(offset >= 128)
5443 sLog.outError("ERROR: 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);
5444 return;
5447 uint32 val = (uint32)(1 << (areaFlag % 32));
5448 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5450 if( !(currFields & val) )
5452 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5454 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5456 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5457 if(!p)
5459 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5461 else if(p->area_level > 0)
5463 uint32 area = p->ID;
5464 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5466 SendExplorationExperience(area,0);
5468 else
5470 int32 diff = int32(getLevel()) - p->area_level;
5471 uint32 XP = 0;
5472 if (diff < -5)
5474 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5476 else if (diff > 5)
5478 int32 exploration_percent = (100-((diff-5)*5));
5479 if (exploration_percent > 100)
5480 exploration_percent = 100;
5481 else if (exploration_percent < 0)
5482 exploration_percent = 0;
5484 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5486 else
5488 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5491 GiveXP( XP, NULL );
5492 SendExplorationExperience(area,XP);
5494 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5499 uint32 Player::TeamForRace(uint8 race)
5501 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5502 if(!rEntry)
5504 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5505 return ALLIANCE;
5508 switch(rEntry->TeamID)
5510 case 7: return ALLIANCE;
5511 case 1: return HORDE;
5514 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5515 return ALLIANCE;
5518 uint32 Player::getFactionForRace(uint8 race)
5520 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5521 if(!rEntry)
5523 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5524 return 0;
5527 return rEntry->FactionID;
5530 void Player::setFactionForRace(uint8 race)
5532 m_team = TeamForRace(race);
5533 setFaction( getFactionForRace(race) );
5536 void Player::UpdateReputation() const
5538 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5540 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5542 SendFactionState(&(itr->second));
5546 void Player::SendFactionState(FactionState const* faction) const
5548 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5550 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5551 data << (float) 0; // unk 2.4.0
5552 data << (uint8) 0; // wotlk 8634
5553 data << (uint32) 1; // count
5554 // for
5555 data << (uint32) faction->ReputationListID;
5556 data << (uint32) faction->Standing;
5557 // end for
5558 GetSession()->SendPacket(&data);
5562 void Player::SendInitialReputations()
5564 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5565 data << uint32 (0x00000080);
5567 RepListID a = 0;
5569 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5571 // fill in absent fields
5572 for (; a != itr->first; a++)
5574 data << uint8 (0x00);
5575 data << uint32 (0x00000000);
5578 // fill in encountered data
5579 data << uint8 (itr->second.Flags);
5580 data << uint32 (itr->second.Standing);
5582 ++a;
5585 // fill in absent fields
5586 for (; a != 128; a++)
5588 data << uint8 (0x00);
5589 data << uint32 (0x00000000);
5592 GetSession()->SendPacket(&data);
5595 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5597 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5598 if (itr != m_factions.end())
5599 return &itr->second;
5601 return NULL;
5604 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5606 // not allow declare war to own faction
5607 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5608 return;
5610 // already set
5611 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5612 return;
5614 if( atWar )
5615 faction->Flags |= FACTION_FLAG_AT_WAR;
5616 else
5617 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5619 faction->Changed = true;
5622 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5624 // always invisible or hidden faction can't be inactive
5625 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5626 return;
5628 // already set
5629 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5630 return;
5632 if(inactive)
5633 faction->Flags |= FACTION_FLAG_INACTIVE;
5634 else
5635 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5637 faction->Changed = true;
5640 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5642 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5644 if(!factionTemplateEntry)
5645 return;
5647 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5650 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5652 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5653 if(!factionEntry)
5654 return;
5656 if(factionEntry->reputationListID < 0)
5657 return;
5659 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5660 if (itr == m_factions.end())
5661 return;
5663 SetFactionVisible(&itr->second);
5666 void Player::SetFactionVisible(FactionState* faction)
5668 // always invisible or hidden faction can't be make visible
5669 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5670 return;
5672 // already set
5673 if(faction->Flags & FACTION_FLAG_VISIBLE)
5674 return;
5676 faction->Flags |= FACTION_FLAG_VISIBLE;
5677 faction->Changed = true;
5679 if(!m_session->PlayerLoading())
5681 // make faction visible in reputation list at client
5682 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5683 data << faction->ReputationListID;
5684 GetSession()->SendPacket(&data);
5688 void Player::SetInitialFactions()
5690 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5692 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5694 if( factionEntry && (factionEntry->reputationListID >= 0))
5696 FactionState newFaction;
5697 newFaction.ID = factionEntry->ID;
5698 newFaction.ReputationListID = factionEntry->reputationListID;
5699 newFaction.Standing = 0;
5700 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5701 newFaction.Changed = true;
5703 m_factions[newFaction.ReputationListID] = newFaction;
5708 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5710 if (!factionEntry)
5711 return 0;
5713 uint32 raceMask = getRaceMask();
5714 uint32 classMask = getClassMask();
5715 for (int i=0; i < 4; i++)
5717 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5718 (factionEntry->BaseRepClassMask[i]==0 ||
5719 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5720 return factionEntry->ReputationFlags[i];
5722 return 0;
5725 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5727 if (!factionEntry)
5728 return 0;
5730 uint32 raceMask = getRaceMask();
5731 uint32 classMask = getClassMask();
5732 for (int i=0; i < 4; i++)
5734 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5735 (factionEntry->BaseRepClassMask[i]==0 ||
5736 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5737 return factionEntry->BaseRepValue[i];
5740 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5741 return 0;
5744 int32 Player::GetReputation(uint32 faction_id) const
5746 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5748 if (!factionEntry)
5750 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5751 return 0;
5754 return GetReputation(factionEntry);
5757 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5759 // Faction without recorded reputation. Just ignore.
5760 if(!factionEntry)
5761 return 0;
5763 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5764 if (itr != m_factions.end())
5765 return GetBaseReputation(factionEntry) + itr->second.Standing;
5767 return 0;
5770 ReputationRank Player::GetReputationRank(uint32 faction) const
5772 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5773 if(!factionEntry)
5774 return MIN_REPUTATION_RANK;
5776 return GetReputationRank(factionEntry);
5779 ReputationRank Player::ReputationToRank(int32 standing) const
5781 int32 Limit = Reputation_Cap + 1;
5782 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5784 Limit -= ReputationRank_Length[i];
5785 if (standing >= Limit )
5786 return ReputationRank(i);
5788 return MIN_REPUTATION_RANK;
5791 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5793 int32 Reputation = GetReputation(factionEntry);
5794 return ReputationToRank(Reputation);
5797 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5799 int32 Reputation = GetBaseReputation(factionEntry);
5800 return ReputationToRank(Reputation);
5803 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5805 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5807 if(!factionTemplateEntry)
5809 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5810 return false;
5813 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5815 // Faction without recorded reputation. Just ignore.
5816 if(!factionEntry)
5817 return false;
5819 return ModifyFactionReputation(factionEntry, DeltaReputation);
5822 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5824 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5825 if (flist)
5827 bool res = false;
5828 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5830 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5831 if(factionEntryCalc)
5832 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5834 return res;
5836 else
5837 return ModifyOneFactionReputation(factionEntry, standing);
5840 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5842 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5843 if (itr != m_factions.end())
5845 int32 BaseRep = GetBaseReputation(factionEntry);
5846 int32 new_rep = BaseRep + itr->second.Standing + standing;
5848 if (new_rep > Reputation_Cap)
5849 new_rep = Reputation_Cap;
5850 else
5851 if (new_rep < Reputation_Bottom)
5852 new_rep = Reputation_Bottom;
5854 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5855 SetFactionAtWar(&itr->second,true);
5857 itr->second.Standing = new_rep - BaseRep;
5858 itr->second.Changed = true;
5860 SetFactionVisible(&itr->second);
5862 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
5864 if(uint32 questid = GetQuestSlotQuestId(i))
5866 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5867 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5869 QuestStatusData& q_status = mQuestStatus[questid];
5870 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5872 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5873 if ( CanCompleteQuest( questid ) )
5874 CompleteQuest( questid );
5876 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5878 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5879 IncompleteQuest( questid );
5884 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5885 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5886 SendFactionState(&(itr->second));
5888 return true;
5890 return false;
5893 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5895 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5897 if(!factionTemplateEntry)
5899 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5900 return false;
5903 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5905 // Faction without recorded reputation. Just ignore.
5906 if(!factionEntry)
5907 return false;
5909 return SetFactionReputation(factionEntry, standing);
5912 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5914 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5915 if (flist)
5917 bool res = false;
5918 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5920 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5921 if(factionEntryCalc)
5922 res = SetOneFactionReputation(factionEntryCalc, standing);
5924 return res;
5926 else
5927 return SetOneFactionReputation(factionEntry, standing);
5930 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5932 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5933 if (itr != m_factions.end())
5935 if (standing > Reputation_Cap)
5936 standing = Reputation_Cap;
5937 else
5938 if (standing < Reputation_Bottom)
5939 standing = Reputation_Bottom;
5941 int32 BaseRep = GetBaseReputation(factionEntry);
5942 itr->second.Standing = standing - BaseRep;
5943 itr->second.Changed = true;
5945 SetFactionVisible(&itr->second);
5947 if(ReputationToRank(standing) <= REP_HOSTILE)
5948 SetFactionAtWar(&itr->second,true);
5950 SendFactionState(&(itr->second));
5951 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5952 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5953 return true;
5955 return false;
5958 //Calculate total reputation percent player gain with quest/creature level
5959 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5961 // for grey creature kill received 20%, in other case 100.
5962 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5964 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5966 percent += rep > 0 ? repMod : -repMod;
5968 if(percent <=0)
5969 return 0;
5971 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5974 //Calculates how many reputation points player gains in victim's enemy factions
5975 void Player::RewardReputation(Unit *pVictim, float rate)
5977 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5978 return;
5980 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5982 if(!Rep)
5983 return;
5985 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5987 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5988 donerep1 = int32(donerep1*rate);
5989 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5990 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
5991 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5992 ModifyFactionReputation(factionEntry1, donerep1);
5994 // Wiki: Team factions value divided by 2
5995 if(Rep->is_teamaward1)
5997 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5998 if(team1_factionEntry)
5999 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
6003 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
6005 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
6006 donerep2 = int32(donerep2*rate);
6007 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
6008 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
6009 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
6010 ModifyFactionReputation(factionEntry2, donerep2);
6012 // Wiki: Team factions value divided by 2
6013 if(Rep->is_teamaward2)
6015 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
6016 if(team2_factionEntry)
6017 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
6022 //Calculate how many reputation points player gain with the quest
6023 void Player::RewardReputation(Quest const *pQuest)
6025 // quest reputation reward/loss
6026 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
6028 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
6030 int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
6031 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
6032 if(factionEntry)
6033 ModifyFactionReputation(factionEntry, rep);
6037 // TODO: implement reputation spillover
6040 void Player::UpdateArenaFields(void)
6042 /* arena calcs go here */
6045 void Player::UpdateHonorFields()
6047 /// called when rewarding honor and at each save
6048 uint64 now = time(NULL);
6049 uint64 today = uint64(time(NULL) / DAY) * DAY;
6051 if(m_lastHonorUpdateTime < today)
6053 uint64 yesterday = today - DAY;
6055 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
6057 // update yesterday's contribution
6058 if(m_lastHonorUpdateTime >= yesterday )
6060 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
6062 // this is the first update today, reset today's contribution
6063 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
6064 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
6066 else
6068 // no honor/kills yesterday or today, reset
6069 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
6070 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
6074 m_lastHonorUpdateTime = now;
6077 ///Calculate the amount of honor gained based on the victim
6078 ///and the size of the group for which the honor is divided
6079 ///An exact honor value can also be given (overriding the calcs)
6080 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
6082 // do not reward honor in arenas, but enable onkill spellproc
6083 if(InArena())
6085 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
6086 return false;
6088 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
6089 return false;
6091 return true;
6094 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6095 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
6096 return false;
6098 uint64 victim_guid = 0;
6099 uint32 victim_rank = 0;
6101 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6102 UpdateHonorFields();
6104 if(honor <= 0)
6106 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
6107 return false;
6109 victim_guid = uVictim->GetGUID();
6111 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6113 Player *pVictim = (Player *)uVictim;
6115 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6116 return false;
6118 float f = 1; //need for total kills (?? need more info)
6119 uint32 k_grey = 0;
6120 uint32 k_level = getLevel();
6121 uint32 v_level = pVictim->getLevel();
6124 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6125 // [0] Just name
6126 // [1..14] Alliance honor titles and player name
6127 // [15..28] Horde honor titles and player name
6128 // [29..38] Other title and player name
6129 // [39+] Nothing
6130 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6131 // Get Killer titles, CharTitlesEntry::bit_index
6132 // Ranks:
6133 // title[1..14] -> rank[5..18]
6134 // title[15..28] -> rank[5..18]
6135 // title[other] -> 0
6136 if (victim_title == 0)
6137 victim_guid = 0; // Don't show HK: <rank> message, only log.
6138 else if (victim_title < 15)
6139 victim_rank = victim_title + 4;
6140 else if (victim_title < 29)
6141 victim_rank = victim_title - 14 + 4;
6142 else
6143 victim_guid = 0; // Don't show HK: <rank> message, only log.
6146 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6148 if(v_level<=k_grey)
6149 return false;
6151 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6153 int32 v_rank =1; //need more info
6155 honor = ((f * diff_level * (190 + v_rank*10))/6);
6156 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6158 // count the number of playerkills in one day
6159 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6160 // and those in a lifetime
6161 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6163 else
6165 Creature *cVictim = (Creature *)uVictim;
6167 if (!cVictim->isRacialLeader())
6168 return false;
6170 honor = 100; // ??? need more info
6171 victim_rank = 19; // HK: Leader
6175 if (uVictim != NULL)
6177 honor *= sWorld.getRate(RATE_HONOR);
6179 if(groupsize > 1)
6180 honor /= groupsize;
6182 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6185 // honor - for show honor points in log
6186 // victim_guid - for show victim name in log
6187 // victim_rank [1..4] HK: <dishonored rank>
6188 // victim_rank [5..19] HK: <alliance\horde rank>
6189 // victim_rank [0,20+] HK: <>
6190 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6191 data << (uint32) honor;
6192 data << (uint64) victim_guid;
6193 data << (uint32) victim_rank;
6195 GetSession()->SendPacket(&data);
6197 // add honor points
6198 ModifyHonorPoints(int32(honor));
6200 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6201 return true;
6204 void Player::ModifyHonorPoints( int32 value )
6206 if(value < 0)
6208 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6209 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6210 else
6211 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6213 else
6214 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6217 void Player::ModifyArenaPoints( int32 value )
6219 if(value < 0)
6221 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6222 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6223 else
6224 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6226 else
6227 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6230 uint32 Player::GetGuildIdFromDB(uint64 guid)
6232 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6233 if(!result)
6234 return 0;
6236 uint32 id = result->Fetch()[0].GetUInt32();
6237 delete result;
6238 return id;
6241 uint32 Player::GetRankFromDB(uint64 guid)
6243 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6244 if( result )
6246 uint32 v = result->Fetch()[0].GetUInt32();
6247 delete result;
6248 return v;
6250 else
6251 return 0;
6254 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6256 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);
6257 if(!result)
6258 return 0;
6260 uint32 id = (*result)[0].GetUInt32();
6261 delete result;
6262 return id;
6265 uint32 Player::GetZoneIdFromDB(uint64 guid)
6267 uint32 guidLow = GUID_LOPART(guid);
6268 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6269 if (!result)
6270 return 0;
6271 Field* fields = result->Fetch();
6272 uint32 zone = fields[0].GetUInt32();
6273 delete result;
6275 if (!zone)
6277 // stored zone is zero, use generic and slow zone detection
6278 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6279 if( !result )
6280 return 0;
6281 fields = result->Fetch();
6282 uint32 map = fields[0].GetUInt32();
6283 float posx = fields[1].GetFloat();
6284 float posy = fields[2].GetFloat();
6285 float posz = fields[3].GetFloat();
6286 delete result;
6288 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6290 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6293 return zone;
6296 void Player::UpdateArea(uint32 newArea)
6298 // FFA_PVP flags are area and not zone id dependent
6299 // so apply them accordingly
6300 m_areaUpdateId = newArea;
6302 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6304 if(area && (area->flags & AREA_FLAG_ARENA))
6306 if(!isGameMaster())
6307 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6309 else
6311 // remove ffa flag only if not ffapvp realm
6312 // removal in sanctuaries and capitals is handled in zone update
6313 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6314 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6317 UpdateAreaDependentAuras(newArea);
6320 void Player::UpdateZone(uint32 newZone)
6322 m_zoneUpdateId = newZone;
6323 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6325 // zone changed, so area changed as well, update it
6326 UpdateArea(GetAreaId());
6328 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6329 if(!zone)
6330 return;
6332 if (sWorld.getConfig(CONFIG_WEATHER))
6334 Weather *wth = sWorld.FindWeather(zone->ID);
6335 if(wth)
6337 wth->SendWeatherUpdateToPlayer(this);
6339 else
6341 if(!sWorld.AddWeather(zone->ID))
6343 // send fine weather packet to remove old zone's weather
6344 Weather::SendFineWeatherUpdateToPlayer(this);
6349 pvpInfo.inHostileArea =
6350 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6351 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6352 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6353 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6355 if(pvpInfo.inHostileArea) // in hostile area
6357 if(!IsPvP() || pvpInfo.endTimer != 0)
6358 UpdatePvP(true, true);
6360 else // in friendly area
6362 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6363 pvpInfo.endTimer = time(0); // start toggle-off
6366 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6368 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6369 if(sWorld.IsFFAPvPRealm())
6370 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6372 else
6374 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6377 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6379 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6380 SetRestType(REST_TYPE_IN_CITY);
6381 InnEnter(time(0),GetMapId(),0,0,0);
6383 if(sWorld.IsFFAPvPRealm())
6384 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6386 else // anywhere else
6388 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6390 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6392 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6394 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6395 SetRestType(REST_TYPE_NO);
6397 if(sWorld.IsFFAPvPRealm())
6398 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6401 else // not in tavern (leave city then)
6403 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6404 SetRestType(REST_TYPE_NO);
6406 // Set player to FFA PVP when not in rested environment.
6407 if(sWorld.IsFFAPvPRealm())
6408 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6413 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6414 // if player resurrected at teleport this will be applied in resurrect code
6415 if(isAlive())
6416 DestroyZoneLimitedItem( true, newZone );
6418 // recent client version not send leave/join channel packets for built-in local channels
6419 UpdateLocalChannels( newZone );
6421 // group update
6422 if(GetGroup())
6423 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6425 UpdateZoneDependentAuras(newZone);
6428 //If players are too far way of duel flag... then player loose the duel
6429 void Player::CheckDuelDistance(time_t currTime)
6431 if(!duel)
6432 return;
6434 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6435 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6436 if(!obj)
6437 return;
6439 if(duel->outOfBound == 0)
6441 if(!IsWithinDistInMap(obj, 50))
6443 duel->outOfBound = currTime;
6445 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6446 GetSession()->SendPacket(&data);
6449 else
6451 if(IsWithinDistInMap(obj, 40))
6453 duel->outOfBound = 0;
6455 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6456 GetSession()->SendPacket(&data);
6458 else if(currTime >= (duel->outOfBound+10))
6460 DuelComplete(DUEL_FLED);
6465 void Player::DuelComplete(DuelCompleteType type)
6467 // duel not requested
6468 if(!duel)
6469 return;
6471 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6472 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6473 GetSession()->SendPacket(&data);
6474 duel->opponent->GetSession()->SendPacket(&data);
6476 if(type != DUEL_INTERUPTED)
6478 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6479 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6480 data << duel->opponent->GetName();
6481 data << GetName();
6482 SendMessageToSet(&data,true);
6485 // cool-down duel spell
6486 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6488 data<<GetGUID();
6489 data<<uint8(0x0);
6491 data<<(uint32)7266;
6492 data<<uint32(0x0);
6493 GetSession()->SendPacket(&data);
6494 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6495 data<<duel->opponent->GetGUID();
6496 data<<uint8(0x0);
6497 data<<(uint32)7266;
6498 data<<uint32(0x0);
6499 duel->opponent->GetSession()->SendPacket(&data);*/
6501 //Remove Duel Flag object
6502 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6503 if(obj)
6504 duel->initiator->RemoveGameObject(obj,true);
6506 /* remove auras */
6507 std::vector<uint32> auras2remove;
6508 AuraMap const& vAuras = duel->opponent->GetAuras();
6509 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6511 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6512 auras2remove.push_back(i->second->GetId());
6515 for(size_t i=0; i<auras2remove.size(); i++)
6516 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6518 auras2remove.clear();
6519 AuraMap const& auras = GetAuras();
6520 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6522 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6523 auras2remove.push_back(i->second->GetId());
6525 for(size_t i=0; i<auras2remove.size(); i++)
6526 RemoveAurasDueToSpell(auras2remove[i]);
6528 // cleanup combo points
6529 if(GetComboTarget()==duel->opponent->GetGUID())
6530 ClearComboPoints();
6531 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6532 ClearComboPoints();
6534 if(duel->opponent->GetComboTarget()==GetGUID())
6535 duel->opponent->ClearComboPoints();
6536 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6537 duel->opponent->ClearComboPoints();
6539 //cleanups
6540 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6541 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6542 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6543 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6545 delete duel->opponent->duel;
6546 duel->opponent->duel = NULL;
6547 delete duel;
6548 duel = NULL;
6551 //---------------------------------------------------------//
6553 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6555 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6556 return;
6558 // not apply/remove mods for broken item
6559 if(item->IsBroken())
6560 return;
6562 ItemPrototype const *proto = item->GetProto();
6564 if(!proto)
6565 return;
6567 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6569 uint32 attacktype = Player::GetAttackBySlot(slot);
6570 if(attacktype < MAX_ATTACK)
6571 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6573 _ApplyItemBonuses(proto,slot,apply);
6575 if( slot==EQUIPMENT_SLOT_RANGED )
6576 _ApplyAmmoBonuses();
6578 ApplyItemEquipSpell(item,apply);
6579 ApplyEnchantment(item, apply);
6581 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6582 CorrectMetaGemEnchants(slot, apply);
6584 sLog.outDebug("_ApplyItemMods complete.");
6587 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6589 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6590 return;
6592 for (int i = 0; i < 10; i++)
6594 uint32 statType = 0;
6595 int32 val = 0;
6597 if(proto->ScalingStatDistribution)
6599 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6601 statType = ssd->StatMod[i];
6603 if(uint32 modifier = ssd->Modifier[i])
6605 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6606 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6608 uint32 multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6609 val = (multiplier * modifier) / 10000;
6614 else
6616 statType = proto->ItemStat[i].ItemStatType;
6617 val = proto->ItemStat[i].ItemStatValue;
6620 if(val == 0)
6621 continue;
6623 switch (statType)
6625 case ITEM_MOD_MANA:
6626 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6627 break;
6628 case ITEM_MOD_HEALTH: // modify HP
6629 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6630 break;
6631 case ITEM_MOD_AGILITY: // modify agility
6632 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6633 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6634 break;
6635 case ITEM_MOD_STRENGTH: //modify strength
6636 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6637 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6638 break;
6639 case ITEM_MOD_INTELLECT: //modify intellect
6640 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6641 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6642 break;
6643 case ITEM_MOD_SPIRIT: //modify spirit
6644 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6645 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6646 break;
6647 case ITEM_MOD_STAMINA: //modify stamina
6648 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6649 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6650 break;
6651 case ITEM_MOD_DEFENSE_SKILL_RATING:
6652 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6653 break;
6654 case ITEM_MOD_DODGE_RATING:
6655 ApplyRatingMod(CR_DODGE, int32(val), apply);
6656 break;
6657 case ITEM_MOD_PARRY_RATING:
6658 ApplyRatingMod(CR_PARRY, int32(val), apply);
6659 break;
6660 case ITEM_MOD_BLOCK_RATING:
6661 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6662 break;
6663 case ITEM_MOD_HIT_MELEE_RATING:
6664 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6665 break;
6666 case ITEM_MOD_HIT_RANGED_RATING:
6667 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6668 break;
6669 case ITEM_MOD_HIT_SPELL_RATING:
6670 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6671 break;
6672 case ITEM_MOD_CRIT_MELEE_RATING:
6673 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6674 break;
6675 case ITEM_MOD_CRIT_RANGED_RATING:
6676 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6677 break;
6678 case ITEM_MOD_CRIT_SPELL_RATING:
6679 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6680 break;
6681 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6682 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6683 break;
6684 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6685 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6686 break;
6687 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6688 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6689 break;
6690 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6691 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6692 break;
6693 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6694 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6695 break;
6696 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6697 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6698 break;
6699 case ITEM_MOD_HASTE_MELEE_RATING:
6700 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6701 break;
6702 case ITEM_MOD_HASTE_RANGED_RATING:
6703 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6704 break;
6705 case ITEM_MOD_HASTE_SPELL_RATING:
6706 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6707 break;
6708 case ITEM_MOD_HIT_RATING:
6709 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6710 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6711 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6712 break;
6713 case ITEM_MOD_CRIT_RATING:
6714 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6715 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6716 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6717 break;
6718 case ITEM_MOD_HIT_TAKEN_RATING:
6719 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6720 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6721 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6722 break;
6723 case ITEM_MOD_CRIT_TAKEN_RATING:
6724 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6725 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6726 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6727 break;
6728 case ITEM_MOD_RESILIENCE_RATING:
6729 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6730 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6731 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6732 break;
6733 case ITEM_MOD_HASTE_RATING:
6734 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6735 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6736 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6737 break;
6738 case ITEM_MOD_EXPERTISE_RATING:
6739 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6740 break;
6741 case ITEM_MOD_ATTACK_POWER:
6742 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6743 break;
6744 case ITEM_MOD_RANGED_ATTACK_POWER:
6745 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6746 break;
6747 case ITEM_MOD_FERAL_ATTACK_POWER:
6748 ApplyFeralAPBonus(int32(val), apply);
6749 break;
6750 case ITEM_MOD_SPELL_HEALING_DONE:
6751 ApplySpellHealingBonus(int32(val), apply);
6752 break;
6753 case ITEM_MOD_SPELL_DAMAGE_DONE:
6754 ApplySpellDamageBonus(int32(val), apply);
6755 break;
6756 case ITEM_MOD_MANA_REGENERATION:
6757 ApplyManaRegenBonus(int32(val), apply);
6758 break;
6759 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6760 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6761 break;
6762 case ITEM_MOD_SPELL_POWER:
6763 ApplySpellHealingBonus(int32(val), apply);
6764 ApplySpellDamageBonus(int32(val), apply);
6765 break;
6769 if (proto->Armor)
6770 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6772 if (proto->Block)
6773 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6775 if (proto->HolyRes)
6776 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6778 if (proto->FireRes)
6779 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6781 if (proto->NatureRes)
6782 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6784 if (proto->FrostRes)
6785 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6787 if (proto->ShadowRes)
6788 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6790 if (proto->ArcaneRes)
6791 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6793 WeaponAttackType attType = BASE_ATTACK;
6794 float damage = 0.0f;
6796 if( slot == EQUIPMENT_SLOT_RANGED && (
6797 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6798 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6800 attType = RANGED_ATTACK;
6802 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6804 attType = OFF_ATTACK;
6807 if (proto->Damage[0].DamageMin > 0 )
6809 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6810 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6811 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6814 if (proto->Damage[0].DamageMax > 0 )
6816 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6817 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6820 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6821 return;
6823 if (proto->Delay)
6825 if(slot == EQUIPMENT_SLOT_RANGED)
6826 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6827 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6828 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6829 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6830 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6833 if(CanModifyStats() && (damage || proto->Delay))
6834 UpdateDamagePhysical(attType);
6837 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6839 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6840 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6841 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6843 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6844 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6845 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6847 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6848 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6849 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6852 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6854 // generic not weapon specific case processes in aura code
6855 if(aura->GetSpellProto()->EquippedItemClass == -1)
6856 return;
6858 BaseModGroup mod = BASEMOD_END;
6859 switch(attackType)
6861 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6862 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6863 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6864 default: return;
6867 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6869 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6873 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6875 // ignore spell mods for not wands
6876 Modifier const* modifier = aura->GetModifier();
6877 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6878 return;
6880 // generic not weapon specific case processes in aura code
6881 if(aura->GetSpellProto()->EquippedItemClass == -1)
6882 return;
6884 UnitMods unitMod = UNIT_MOD_END;
6885 switch(attackType)
6887 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6888 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6889 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6890 default: return;
6893 UnitModifierType unitModType = TOTAL_VALUE;
6894 switch(modifier->m_auraname)
6896 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6897 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6898 default: return;
6901 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6903 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6907 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6909 if(!item)
6910 return;
6912 ItemPrototype const *proto = item->GetProto();
6913 if(!proto)
6914 return;
6916 for (int i = 0; i < 5; i++)
6918 _Spell const& spellData = proto->Spells[i];
6920 // no spell
6921 if(!spellData.SpellId )
6922 continue;
6924 // wrong triggering type
6925 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6926 continue;
6928 // check if it is valid spell
6929 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6930 if(!spellproto)
6931 continue;
6933 ApplyEquipSpell(spellproto,item,apply,form_change);
6937 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6939 if(apply)
6941 // Cannot be used in this stance/form
6942 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6943 return;
6945 if(form_change) // check aura active state from other form
6947 bool found = false;
6948 for (int k=0; k < 3; ++k)
6950 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6951 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6953 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6955 found = true;
6956 break;
6959 if(found)
6960 break;
6963 if(found) // and skip re-cast already active aura at form change
6964 return;
6967 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6969 CastSpell(this,spellInfo,true,item);
6971 else
6973 if(form_change) // check aura compatibility
6975 // Cannot be used in this stance/form
6976 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6977 return; // and remove only not compatible at form change
6980 if(item)
6981 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6982 else
6983 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6987 void Player::UpdateEquipSpellsAtFormChange()
6989 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6991 if(m_items[i] && !m_items[i]->IsBroken())
6993 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6994 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6998 // item set bonuses not dependent from item broken state
6999 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
7001 ItemSetEffect* eff = ItemSetEff[setindex];
7002 if(!eff)
7003 continue;
7005 for(uint32 y=0;y<8; ++y)
7007 SpellEntry const* spellInfo = eff->spells[y];
7008 if(!spellInfo)
7009 continue;
7011 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
7012 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
7017 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
7019 if(!item || item->IsBroken())
7020 return;
7022 ItemPrototype const *proto = item->GetProto();
7023 if(!proto)
7024 return;
7026 if (!Target || Target == this )
7027 return;
7029 for (int i = 0; i < 5; i++)
7031 _Spell const& spellData = proto->Spells[i];
7033 // no spell
7034 if(!spellData.SpellId )
7035 continue;
7037 // wrong triggering type
7038 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7039 continue;
7041 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7042 if(!spellInfo)
7044 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7045 continue;
7048 // not allow proc extra attack spell at extra attack
7049 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7050 return;
7052 float chance = spellInfo->procChance;
7054 if(spellData.SpellPPMRate)
7056 uint32 WeaponSpeed = GetAttackTime(attType);
7057 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7059 else if(chance > 100.0f)
7061 chance = GetWeaponProcChance();
7064 if (roll_chance_f(chance))
7065 CastSpell(Target, spellInfo->Id, true, item);
7068 // item combat enchantments
7069 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7071 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7072 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7073 if(!pEnchant) continue;
7074 for (int s=0;s<3;s++)
7076 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7077 continue;
7079 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7080 if (!spellInfo)
7082 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7083 continue;
7086 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7087 if (roll_chance_f(chance))
7089 if(IsPositiveSpell(pEnchant->spellid[s]))
7090 CastSpell(this, pEnchant->spellid[s], true, item);
7091 else
7092 CastSpell(Target, pEnchant->spellid[s], true, item);
7098 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7100 ItemPrototype const* proto = item->GetProto();
7101 // special learning case
7102 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7104 uint32 learn_spell_id = proto->Spells[0].SpellId;
7105 uint32 learning_spell_id = proto->Spells[1].SpellId;
7107 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7108 if(!spellInfo)
7110 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7111 SendEquipError(EQUIP_ERR_NONE,item,NULL);
7112 return;
7115 Spell *spell = new Spell(this, spellInfo, false);
7116 spell->m_CastItem = item;
7117 spell->m_cast_count = cast_count; //set count of casts
7118 spell->m_currentBasePoints[0] = learning_spell_id;
7119 spell->prepare(&targets);
7120 return;
7123 // use triggered flag only for items with many spell casts and for not first cast
7124 int count = 0;
7126 // item spells casted at use
7127 for(int i = 0; i < 5; ++i)
7129 _Spell const& spellData = proto->Spells[i];
7131 // no spell
7132 if(!spellData.SpellId)
7133 continue;
7135 // wrong triggering type
7136 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7137 continue;
7139 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7140 if(!spellInfo)
7142 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7143 continue;
7146 Spell *spell = new Spell(this, spellInfo, (count > 0));
7147 spell->m_CastItem = item;
7148 spell->m_cast_count = cast_count; // set count of casts
7149 spell->m_glyphIndex = glyphIndex; // glyph index
7150 spell->prepare(&targets);
7152 ++count;
7155 // Item enchantments spells casted at use
7156 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7158 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7159 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7160 if(!pEnchant) continue;
7161 for (int s=0;s<3;s++)
7163 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7164 continue;
7166 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7167 if (!spellInfo)
7169 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7170 continue;
7173 Spell *spell = new Spell(this, spellInfo, (count > 0));
7174 spell->m_CastItem = item;
7175 spell->m_cast_count = cast_count; // set count of casts
7176 spell->m_glyphIndex = glyphIndex; // glyph index
7177 spell->prepare(&targets);
7179 ++count;
7184 void Player::_RemoveAllItemMods()
7186 sLog.outDebug("_RemoveAllItemMods start.");
7188 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7190 if(m_items[i])
7192 ItemPrototype const *proto = m_items[i]->GetProto();
7193 if(!proto)
7194 continue;
7196 // item set bonuses not dependent from item broken state
7197 if(proto->ItemSet)
7198 RemoveItemsSetItem(this,proto);
7200 if(m_items[i]->IsBroken())
7201 continue;
7203 ApplyItemEquipSpell(m_items[i],false);
7204 ApplyEnchantment(m_items[i], false);
7208 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7210 if(m_items[i])
7212 if(m_items[i]->IsBroken())
7213 continue;
7214 ItemPrototype const *proto = m_items[i]->GetProto();
7215 if(!proto)
7216 continue;
7218 uint32 attacktype = Player::GetAttackBySlot(i);
7219 if(attacktype < MAX_ATTACK)
7220 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7222 _ApplyItemBonuses(proto,i, false);
7224 if( i == EQUIPMENT_SLOT_RANGED )
7225 _ApplyAmmoBonuses();
7229 sLog.outDebug("_RemoveAllItemMods complete.");
7232 void Player::_ApplyAllItemMods()
7234 sLog.outDebug("_ApplyAllItemMods start.");
7236 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7238 if(m_items[i])
7240 if(m_items[i]->IsBroken())
7241 continue;
7243 ItemPrototype const *proto = m_items[i]->GetProto();
7244 if(!proto)
7245 continue;
7247 uint32 attacktype = Player::GetAttackBySlot(i);
7248 if(attacktype < MAX_ATTACK)
7249 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7251 _ApplyItemBonuses(proto,i, true);
7253 if( i == EQUIPMENT_SLOT_RANGED )
7254 _ApplyAmmoBonuses();
7258 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7260 if(m_items[i])
7262 ItemPrototype const *proto = m_items[i]->GetProto();
7263 if(!proto)
7264 continue;
7266 // item set bonuses not dependent from item broken state
7267 if(proto->ItemSet)
7268 AddItemsSetItem(this,m_items[i]);
7270 if(m_items[i]->IsBroken())
7271 continue;
7273 ApplyItemEquipSpell(m_items[i],true);
7274 ApplyEnchantment(m_items[i], true);
7278 sLog.outDebug("_ApplyAllItemMods complete.");
7281 void Player::_ApplyAmmoBonuses()
7283 // check ammo
7284 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7285 if(!ammo_id)
7286 return;
7288 float currentAmmoDPS;
7290 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7291 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7292 currentAmmoDPS = 0.0f;
7293 else
7294 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7296 if(currentAmmoDPS == GetAmmoDPS())
7297 return;
7299 m_ammoDPS = currentAmmoDPS;
7301 if(CanModifyStats())
7302 UpdateDamagePhysical(RANGED_ATTACK);
7305 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7307 if(!ammo_proto)
7308 return false;
7310 // check ranged weapon
7311 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7312 if(!weapon || weapon->IsBroken() )
7313 return false;
7315 ItemPrototype const* weapon_proto = weapon->GetProto();
7316 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7317 return false;
7319 // check ammo ws. weapon compatibility
7320 switch(weapon_proto->SubClass)
7322 case ITEM_SUBCLASS_WEAPON_BOW:
7323 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7324 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7325 return false;
7326 break;
7327 case ITEM_SUBCLASS_WEAPON_GUN:
7328 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7329 return false;
7330 break;
7331 default:
7332 return false;
7335 return true;
7338 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7339 Called by remove insignia spell effect */
7340 void Player::RemovedInsignia(Player* looterPlr)
7342 if (!GetBattleGroundId())
7343 return;
7345 // If not released spirit, do it !
7346 if(m_deathTimer > 0)
7348 m_deathTimer = 0;
7349 BuildPlayerRepop();
7350 RepopAtGraveyard();
7353 Corpse *corpse = GetCorpse();
7354 if (!corpse)
7355 return;
7357 // We have to convert player corpse to bones, not to be able to resurrect there
7358 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7359 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7360 if (!bones)
7361 return;
7363 // Now we must make bones lootable, and send player loot
7364 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7366 // We store the level of our player in the gold field
7367 // We retrieve this information at Player::SendLoot()
7368 bones->loot.gold = getLevel();
7369 bones->lootRecipient = looterPlr;
7370 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7373 /*Loot type MUST be
7374 1-corpse, go
7375 2-skinning
7376 3-Fishing
7379 void Player::SendLootRelease( uint64 guid )
7381 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7382 data << uint64(guid) << uint8(1);
7383 SendDirectMessage( &data );
7386 void Player::SendLoot(uint64 guid, LootType loot_type)
7388 Loot *loot = 0;
7389 PermissionTypes permission = ALL_PERMISSION;
7391 sLog.outDebug("Player::SendLoot");
7392 if (IS_GAMEOBJECT_GUID(guid))
7394 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7395 GameObject *go =
7396 ObjectAccessor::GetGameObject(*this, guid);
7398 // not check distance for GO in case owned GO (fishing bobber case, for example)
7399 // And permit out of range GO with no owner in case fishing hole
7400 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7402 SendLootRelease(guid);
7403 return;
7406 loot = &go->loot;
7408 if(go->getLootState() == GO_READY)
7410 uint32 lootid = go->GetLootId();
7412 if(lootid)
7414 sLog.outDebug(" if(lootid)");
7415 loot->clear();
7416 loot->FillLoot(lootid, LootTemplates_Gameobject, this);
7419 if(loot_type == LOOT_FISHING)
7420 go->getFishLoot(loot);
7422 go->SetLootState(GO_ACTIVATED);
7425 else if (IS_ITEM_GUID(guid))
7427 Item *item = GetItemByGuid( guid );
7429 if (!item)
7431 SendLootRelease(guid);
7432 return;
7435 if(loot_type == LOOT_DISENCHANTING)
7437 loot = &item->loot;
7439 if(!item->m_lootGenerated)
7441 item->m_lootGenerated = true;
7442 loot->clear();
7443 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this);
7446 else if(loot_type == LOOT_PROSPECTING)
7448 loot = &item->loot;
7450 if(!item->m_lootGenerated)
7452 item->m_lootGenerated = true;
7453 loot->clear();
7454 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this);
7457 else if(loot_type == LOOT_MILLING)
7459 loot = &item->loot;
7461 if(!item->m_lootGenerated)
7463 item->m_lootGenerated = true;
7464 loot->clear();
7465 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this);
7468 else
7470 loot = &item->loot;
7472 if(!item->m_lootGenerated)
7474 item->m_lootGenerated = true;
7475 loot->clear();
7476 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this);
7478 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7482 else if (IS_CORPSE_GUID(guid)) // remove insignia
7484 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7486 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7488 SendLootRelease(guid);
7489 return;
7492 loot = &bones->loot;
7494 if (!bones->lootForBody)
7496 bones->lootForBody = true;
7497 uint32 pLevel = bones->loot.gold;
7498 bones->loot.clear();
7499 // It may need a better formula
7500 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7501 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7504 if (bones->lootRecipient != this)
7505 permission = NONE_PERMISSION;
7507 else
7509 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7511 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7512 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7514 SendLootRelease(guid);
7515 return;
7518 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7520 SendLootRelease(guid);
7521 return;
7524 loot = &creature->loot;
7526 if(loot_type == LOOT_PICKPOCKETING)
7528 if ( !creature->lootForPickPocketed )
7530 creature->lootForPickPocketed = true;
7531 loot->clear();
7533 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7534 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this);
7536 // Generate extra money for pick pocket loot
7537 const uint32 a = urand(0, creature->getLevel()/2);
7538 const uint32 b = urand(0, getLevel()/2);
7539 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7542 else
7544 // the player whose group may loot the corpse
7545 Player *recipient = creature->GetLootRecipient();
7546 if (!recipient)
7548 creature->SetLootRecipient(this);
7549 recipient = this;
7552 if (creature->lootForPickPocketed)
7554 creature->lootForPickPocketed = false;
7555 loot->clear();
7558 if(!creature->lootForBody)
7560 creature->lootForBody = true;
7561 loot->clear();
7563 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7564 loot->FillLoot(lootid, LootTemplates_Creature, recipient);
7566 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7568 if(Group* group = recipient->GetGroup())
7570 group->UpdateLooterGuid(creature,true);
7572 switch (group->GetLootMethod())
7574 case GROUP_LOOT:
7575 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7576 group->GroupLoot(recipient->GetGUID(), loot, creature);
7577 break;
7578 case NEED_BEFORE_GREED:
7579 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7580 break;
7581 case MASTER_LOOT:
7582 group->MasterLoot(recipient->GetGUID(), loot, creature);
7583 break;
7584 default:
7585 break;
7590 // possible only if creature->lootForBody && loot->empty() at spell cast check
7591 if (loot_type == LOOT_SKINNING)
7593 loot->clear();
7594 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this);
7596 // set group rights only for loot_type != LOOT_SKINNING
7597 else
7599 if(Group* group = GetGroup())
7601 if( group == recipient->GetGroup() )
7603 if(group->GetLootMethod() == FREE_FOR_ALL)
7604 permission = ALL_PERMISSION;
7605 else if(group->GetLooterGuid() == GetGUID())
7607 if(group->GetLootMethod() == MASTER_LOOT)
7608 permission = MASTER_PERMISSION;
7609 else
7610 permission = ALL_PERMISSION;
7612 else
7613 permission = GROUP_PERMISSION;
7615 else
7616 permission = NONE_PERMISSION;
7618 else if(recipient == this)
7619 permission = ALL_PERMISSION;
7620 else
7621 permission = NONE_PERMISSION;
7626 SetLootGUID(guid);
7628 QuestItemList *q_list = 0;
7629 if (permission != NONE_PERMISSION)
7631 QuestItemMap const& lootPlayerQuestItems = loot->GetPlayerQuestItems();
7632 QuestItemMap::const_iterator itr = lootPlayerQuestItems.find(GetGUIDLow());
7633 if (itr == lootPlayerQuestItems.end())
7634 q_list = loot->FillQuestLoot(this);
7635 else
7636 q_list = itr->second;
7639 QuestItemList *ffa_list = 0;
7640 if (permission != NONE_PERMISSION)
7642 QuestItemMap const& lootPlayerFFAItems = loot->GetPlayerFFAItems();
7643 QuestItemMap::const_iterator itr = lootPlayerFFAItems.find(GetGUIDLow());
7644 if (itr == lootPlayerFFAItems.end())
7645 ffa_list = loot->FillFFALoot(this);
7646 else
7647 ffa_list = itr->second;
7650 QuestItemList *conditional_list = 0;
7651 if (permission != NONE_PERMISSION)
7653 QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = loot->GetPlayerNonQuestNonFFAConditionalItems();
7654 QuestItemMap::const_iterator itr = lootPlayerNonQuestNonFFAConditionalItems.find(GetGUIDLow());
7655 if (itr == lootPlayerNonQuestNonFFAConditionalItems.end())
7656 conditional_list = loot->FillNonQuestNonFFAConditionalLoot(this);
7657 else
7658 conditional_list = itr->second;
7661 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7662 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA || loot_type == LOOT_MILLING)
7663 loot_type = LOOT_SKINNING;
7665 if(loot_type == LOOT_FISHINGHOLE)
7666 loot_type = LOOT_FISHING;
7668 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7670 data << uint64(guid);
7671 data << uint8(loot_type);
7672 data << LootView(*loot, q_list, ffa_list, conditional_list, this, permission);
7674 SendDirectMessage(&data);
7676 // add 'this' player as one of the players that are looting 'loot'
7677 if (permission != NONE_PERMISSION)
7678 loot->AddLooter(GetGUID());
7680 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7681 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7684 void Player::SendNotifyLootMoneyRemoved()
7686 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7687 GetSession()->SendPacket( &data );
7690 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7692 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7693 data << uint8(lootSlot);
7694 GetSession()->SendPacket( &data );
7697 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7699 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7700 data << Field;
7701 data << Value;
7702 GetSession()->SendPacket(&data);
7705 void Player::SendInitWorldStates()
7707 // data depends on zoneid/mapid...
7708 BattleGround* bg = GetBattleGround();
7709 uint16 NumberOfFields = 0;
7710 uint32 mapid = GetMapId();
7711 uint32 zoneid = GetZoneId();
7712 uint32 areaid = GetAreaId();
7713 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7714 // may be exist better way to do this...
7715 switch(zoneid)
7717 case 0:
7718 case 1:
7719 case 4:
7720 case 8:
7721 case 10:
7722 case 11:
7723 case 12:
7724 case 36:
7725 case 38:
7726 case 40:
7727 case 41:
7728 case 51:
7729 case 267:
7730 case 1519:
7731 case 1537:
7732 case 2257:
7733 case 2918:
7734 NumberOfFields = 8;
7735 break;
7736 case 139:
7737 NumberOfFields = 41;
7738 break;
7739 case 1377:
7740 NumberOfFields = 15;
7741 break;
7742 case 2597:
7743 NumberOfFields = 83;
7744 break;
7745 case 3277:
7746 NumberOfFields = 16;
7747 break;
7748 case 3358:
7749 case 3820:
7750 NumberOfFields = 40;
7751 break;
7752 case 3483:
7753 NumberOfFields = 27;
7754 break;
7755 case 3518:
7756 NumberOfFields = 39;
7757 break;
7758 case 3519:
7759 NumberOfFields = 38;
7760 break;
7761 case 3521:
7762 NumberOfFields = 37;
7763 break;
7764 case 3698:
7765 case 3702:
7766 case 3968:
7767 NumberOfFields = 11;
7768 break;
7769 case 3703:
7770 NumberOfFields = 11;
7771 break;
7772 default:
7773 NumberOfFields = 12;
7774 break;
7777 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7778 data << uint32(mapid); // mapid
7779 data << uint32(zoneid); // zone id
7780 data << uint32(areaid); // area id, new 2.1.0
7781 data << uint16(NumberOfFields); // count of uint64 blocks
7782 data << uint32(0x8d8) << uint32(0x0); // 1
7783 data << uint32(0x8d7) << uint32(0x0); // 2
7784 data << uint32(0x8d6) << uint32(0x0); // 3
7785 data << uint32(0x8d5) << uint32(0x0); // 4
7786 data << uint32(0x8d4) << uint32(0x0); // 5
7787 data << uint32(0x8d3) << uint32(0x0); // 6
7788 // 7 1 - Arena season in progress, 0 - end of season
7789 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7790 // 8 Arena season id
7791 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7792 if(mapid == 530) // Outland
7794 data << uint32(0x9bf) << uint32(0x0); // 7
7795 data << uint32(0x9bd) << uint32(0xF); // 8
7796 data << uint32(0x9bb) << uint32(0xF); // 9
7798 switch(zoneid)
7800 case 1:
7801 case 11:
7802 case 12:
7803 case 38:
7804 case 40:
7805 case 51:
7806 case 1519:
7807 case 1537:
7808 case 2257:
7809 break;
7810 case 2597: // AV
7811 data << uint32(0x7ae) << uint32(0x1); // 7
7812 data << uint32(0x532) << uint32(0x1); // 8
7813 data << uint32(0x531) << uint32(0x0); // 9
7814 data << uint32(0x52e) << uint32(0x0); // 10
7815 data << uint32(0x571) << uint32(0x0); // 11
7816 data << uint32(0x570) << uint32(0x0); // 12
7817 data << uint32(0x567) << uint32(0x1); // 13
7818 data << uint32(0x566) << uint32(0x1); // 14
7819 data << uint32(0x550) << uint32(0x1); // 15
7820 data << uint32(0x544) << uint32(0x0); // 16
7821 data << uint32(0x536) << uint32(0x0); // 17
7822 data << uint32(0x535) << uint32(0x1); // 18
7823 data << uint32(0x518) << uint32(0x0); // 19
7824 data << uint32(0x517) << uint32(0x0); // 20
7825 data << uint32(0x574) << uint32(0x0); // 21
7826 data << uint32(0x573) << uint32(0x0); // 22
7827 data << uint32(0x572) << uint32(0x0); // 23
7828 data << uint32(0x56f) << uint32(0x0); // 24
7829 data << uint32(0x56e) << uint32(0x0); // 25
7830 data << uint32(0x56d) << uint32(0x0); // 26
7831 data << uint32(0x56c) << uint32(0x0); // 27
7832 data << uint32(0x56b) << uint32(0x0); // 28
7833 data << uint32(0x56a) << uint32(0x1); // 29
7834 data << uint32(0x569) << uint32(0x1); // 30
7835 data << uint32(0x568) << uint32(0x1); // 13
7836 data << uint32(0x565) << uint32(0x0); // 32
7837 data << uint32(0x564) << uint32(0x0); // 33
7838 data << uint32(0x563) << uint32(0x0); // 34
7839 data << uint32(0x562) << uint32(0x0); // 35
7840 data << uint32(0x561) << uint32(0x0); // 36
7841 data << uint32(0x560) << uint32(0x0); // 37
7842 data << uint32(0x55f) << uint32(0x0); // 38
7843 data << uint32(0x55e) << uint32(0x0); // 39
7844 data << uint32(0x55d) << uint32(0x0); // 40
7845 data << uint32(0x3c6) << uint32(0x4); // 41
7846 data << uint32(0x3c4) << uint32(0x6); // 42
7847 data << uint32(0x3c2) << uint32(0x4); // 43
7848 data << uint32(0x516) << uint32(0x1); // 44
7849 data << uint32(0x515) << uint32(0x0); // 45
7850 data << uint32(0x3b6) << uint32(0x6); // 46
7851 data << uint32(0x55c) << uint32(0x0); // 47
7852 data << uint32(0x55b) << uint32(0x0); // 48
7853 data << uint32(0x55a) << uint32(0x0); // 49
7854 data << uint32(0x559) << uint32(0x0); // 50
7855 data << uint32(0x558) << uint32(0x0); // 51
7856 data << uint32(0x557) << uint32(0x0); // 52
7857 data << uint32(0x556) << uint32(0x0); // 53
7858 data << uint32(0x555) << uint32(0x0); // 54
7859 data << uint32(0x554) << uint32(0x1); // 55
7860 data << uint32(0x553) << uint32(0x1); // 56
7861 data << uint32(0x552) << uint32(0x1); // 57
7862 data << uint32(0x551) << uint32(0x1); // 58
7863 data << uint32(0x54f) << uint32(0x0); // 59
7864 data << uint32(0x54e) << uint32(0x0); // 60
7865 data << uint32(0x54d) << uint32(0x1); // 61
7866 data << uint32(0x54c) << uint32(0x0); // 62
7867 data << uint32(0x54b) << uint32(0x0); // 63
7868 data << uint32(0x545) << uint32(0x0); // 64
7869 data << uint32(0x543) << uint32(0x1); // 65
7870 data << uint32(0x542) << uint32(0x0); // 66
7871 data << uint32(0x540) << uint32(0x0); // 67
7872 data << uint32(0x53f) << uint32(0x0); // 68
7873 data << uint32(0x53e) << uint32(0x0); // 69
7874 data << uint32(0x53d) << uint32(0x0); // 70
7875 data << uint32(0x53c) << uint32(0x0); // 71
7876 data << uint32(0x53b) << uint32(0x0); // 72
7877 data << uint32(0x53a) << uint32(0x1); // 73
7878 data << uint32(0x539) << uint32(0x0); // 74
7879 data << uint32(0x538) << uint32(0x0); // 75
7880 data << uint32(0x537) << uint32(0x0); // 76
7881 data << uint32(0x534) << uint32(0x0); // 77
7882 data << uint32(0x533) << uint32(0x0); // 78
7883 data << uint32(0x530) << uint32(0x0); // 79
7884 data << uint32(0x52f) << uint32(0x0); // 80
7885 data << uint32(0x52d) << uint32(0x1); // 81
7886 break;
7887 case 3277: // WS
7888 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7889 bg->FillInitialWorldStates(data);
7890 else
7892 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7893 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7894 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7895 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7896 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7897 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7898 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7899 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7901 break;
7902 case 3358: // AB
7903 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7904 bg->FillInitialWorldStates(data);
7905 else
7907 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7908 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7909 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7910 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7911 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7912 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7913 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7914 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7915 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7916 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7917 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7918 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7919 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7920 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7921 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7922 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7923 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7924 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7925 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7926 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7927 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7928 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7929 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7930 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7931 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7932 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7933 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7934 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7935 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7936 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7937 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7938 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7940 break;
7941 case 3820: // EY
7942 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7943 bg->FillInitialWorldStates(data);
7944 else
7946 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7947 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7948 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7949 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7950 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7951 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7952 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7953 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7954 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7955 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7956 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7957 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7958 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7959 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7960 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7961 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7962 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7963 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7964 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7965 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7966 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7967 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7968 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7969 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7970 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7971 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7972 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7973 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7974 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7975 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7976 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7977 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7978 // and some more ... unknown
7980 break;
7981 case 3483: // Hellfire Peninsula
7982 data << uint32(0x9ba) << uint32(0x1); // 10
7983 data << uint32(0x9b9) << uint32(0x1); // 11
7984 data << uint32(0x9b5) << uint32(0x0); // 12
7985 data << uint32(0x9b4) << uint32(0x1); // 13
7986 data << uint32(0x9b3) << uint32(0x0); // 14
7987 data << uint32(0x9b2) << uint32(0x0); // 15
7988 data << uint32(0x9b1) << uint32(0x1); // 16
7989 data << uint32(0x9b0) << uint32(0x0); // 17
7990 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7991 data << uint32(0x9ac) << uint32(0x0); // 19
7992 data << uint32(0x9a8) << uint32(0x0); // 20
7993 data << uint32(0x9a7) << uint32(0x0); // 21
7994 data << uint32(0x9a6) << uint32(0x1); // 22
7995 break;
7996 case 3519: // Terokkar Forest
7997 data << uint32(0xa41) << uint32(0x0); // 10
7998 data << uint32(0xa40) << uint32(0x14); // 11
7999 data << uint32(0xa3f) << uint32(0x0); // 12
8000 data << uint32(0xa3e) << uint32(0x0); // 13
8001 data << uint32(0xa3d) << uint32(0x5); // 14
8002 data << uint32(0xa3c) << uint32(0x0); // 15
8003 data << uint32(0xa87) << uint32(0x0); // 16
8004 data << uint32(0xa86) << uint32(0x0); // 17
8005 data << uint32(0xa85) << uint32(0x0); // 18
8006 data << uint32(0xa84) << uint32(0x0); // 19
8007 data << uint32(0xa83) << uint32(0x0); // 20
8008 data << uint32(0xa82) << uint32(0x0); // 21
8009 data << uint32(0xa81) << uint32(0x0); // 22
8010 data << uint32(0xa80) << uint32(0x0); // 23
8011 data << uint32(0xa7e) << uint32(0x0); // 24
8012 data << uint32(0xa7d) << uint32(0x0); // 25
8013 data << uint32(0xa7c) << uint32(0x0); // 26
8014 data << uint32(0xa7b) << uint32(0x0); // 27
8015 data << uint32(0xa7a) << uint32(0x0); // 28
8016 data << uint32(0xa79) << uint32(0x0); // 29
8017 data << uint32(0x9d0) << uint32(0x5); // 30
8018 data << uint32(0x9ce) << uint32(0x0); // 31
8019 data << uint32(0x9cd) << uint32(0x0); // 32
8020 data << uint32(0x9cc) << uint32(0x0); // 33
8021 data << uint32(0xa88) << uint32(0x0); // 34
8022 data << uint32(0xad0) << uint32(0x0); // 35
8023 data << uint32(0xacf) << uint32(0x1); // 36
8024 break;
8025 case 3521: // Zangarmarsh
8026 data << uint32(0x9e1) << uint32(0x0); // 10
8027 data << uint32(0x9e0) << uint32(0x0); // 11
8028 data << uint32(0x9df) << uint32(0x0); // 12
8029 data << uint32(0xa5d) << uint32(0x1); // 13
8030 data << uint32(0xa5c) << uint32(0x0); // 14
8031 data << uint32(0xa5b) << uint32(0x1); // 15
8032 data << uint32(0xa5a) << uint32(0x0); // 16
8033 data << uint32(0xa59) << uint32(0x1); // 17
8034 data << uint32(0xa58) << uint32(0x0); // 18
8035 data << uint32(0xa57) << uint32(0x0); // 19
8036 data << uint32(0xa56) << uint32(0x0); // 20
8037 data << uint32(0xa55) << uint32(0x1); // 21
8038 data << uint32(0xa54) << uint32(0x0); // 22
8039 data << uint32(0x9e7) << uint32(0x0); // 23
8040 data << uint32(0x9e6) << uint32(0x0); // 24
8041 data << uint32(0x9e5) << uint32(0x0); // 25
8042 data << uint32(0xa00) << uint32(0x0); // 26
8043 data << uint32(0x9ff) << uint32(0x1); // 27
8044 data << uint32(0x9fe) << uint32(0x0); // 28
8045 data << uint32(0x9fd) << uint32(0x0); // 29
8046 data << uint32(0x9fc) << uint32(0x1); // 30
8047 data << uint32(0x9fb) << uint32(0x0); // 31
8048 data << uint32(0xa62) << uint32(0x0); // 32
8049 data << uint32(0xa61) << uint32(0x1); // 33
8050 data << uint32(0xa60) << uint32(0x1); // 34
8051 data << uint32(0xa5f) << uint32(0x0); // 35
8052 break;
8053 case 3698: // Nagrand Arena
8054 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
8055 bg->FillInitialWorldStates(data);
8056 else
8058 data << uint32(0xa0f) << uint32(0x0); // 7
8059 data << uint32(0xa10) << uint32(0x0); // 8
8060 data << uint32(0xa11) << uint32(0x0); // 9 show
8062 break;
8063 case 3702: // Blade's Edge Arena
8064 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8065 bg->FillInitialWorldStates(data);
8066 else
8068 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8069 data << uint32(0x9f1) << uint32(0x0); // 8 green
8070 data << uint32(0x9f3) << uint32(0x0); // 9 show
8072 break;
8073 case 3968: // Ruins of Lordaeron
8074 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8075 bg->FillInitialWorldStates(data);
8076 else
8078 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8079 data << uint32(0xbb9) << uint32(0x0); // 8 green
8080 data << uint32(0xbba) << uint32(0x0); // 9 show
8082 break;
8083 case 3703: // Shattrath City
8084 break;
8085 default:
8086 data << uint32(0x914) << uint32(0x0); // 7
8087 data << uint32(0x913) << uint32(0x0); // 8
8088 data << uint32(0x912) << uint32(0x0); // 9
8089 data << uint32(0x915) << uint32(0x0); // 10
8090 break;
8092 GetSession()->SendPacket(&data);
8095 uint32 Player::GetXPRestBonus(uint32 xp)
8097 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8099 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8100 rested_bonus = xp;
8102 SetRestBonus( GetRestBonus() - rested_bonus);
8104 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8105 return rested_bonus;
8108 void Player::SetBindPoint(uint64 guid)
8110 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8111 data << uint64(guid);
8112 GetSession()->SendPacket( &data );
8115 void Player::SendTalentWipeConfirm(uint64 guid)
8117 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8118 data << uint64(guid);
8119 data << uint32(resetTalentsCost());
8120 GetSession()->SendPacket( &data );
8123 void Player::SendPetSkillWipeConfirm()
8125 Pet* pet = GetPet();
8126 if(!pet)
8127 return;
8128 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8129 data << pet->GetGUID();
8130 data << uint32(pet->resetTalentsCost());
8131 GetSession()->SendPacket( &data );
8134 /*********************************************************/
8135 /*** STORAGE SYSTEM ***/
8136 /*********************************************************/
8138 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8140 assert(i < 3);
8141 if(i < 2 && item)
8143 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8144 return;
8145 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8146 if(charges == 0)
8147 return;
8148 if(charges > 1)
8149 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8150 else if(charges <= 1)
8152 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8153 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8158 void Player::SetSheath( uint32 sheathed )
8160 switch (sheathed)
8162 case SHEATH_STATE_UNARMED: // no prepared weapon
8163 SetVirtualItemSlot(0,NULL);
8164 SetVirtualItemSlot(1,NULL);
8165 SetVirtualItemSlot(2,NULL);
8166 break;
8167 case SHEATH_STATE_MELEE: // prepared melee weapon
8169 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
8170 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
8171 SetVirtualItemSlot(2,NULL);
8172 }; break;
8173 case SHEATH_STATE_RANGED: // prepared ranged weapon
8174 SetVirtualItemSlot(0,NULL);
8175 SetVirtualItemSlot(1,NULL);
8176 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
8177 break;
8178 default:
8179 SetVirtualItemSlot(0,NULL);
8180 SetVirtualItemSlot(1,NULL);
8181 SetVirtualItemSlot(2,NULL);
8182 break;
8184 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
8187 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8189 uint8 pClass = getClass();
8191 uint8 slots[4];
8192 slots[0] = NULL_SLOT;
8193 slots[1] = NULL_SLOT;
8194 slots[2] = NULL_SLOT;
8195 slots[3] = NULL_SLOT;
8196 switch( proto->InventoryType )
8198 case INVTYPE_HEAD:
8199 slots[0] = EQUIPMENT_SLOT_HEAD;
8200 break;
8201 case INVTYPE_NECK:
8202 slots[0] = EQUIPMENT_SLOT_NECK;
8203 break;
8204 case INVTYPE_SHOULDERS:
8205 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8206 break;
8207 case INVTYPE_BODY:
8208 slots[0] = EQUIPMENT_SLOT_BODY;
8209 break;
8210 case INVTYPE_CHEST:
8211 slots[0] = EQUIPMENT_SLOT_CHEST;
8212 break;
8213 case INVTYPE_ROBE:
8214 slots[0] = EQUIPMENT_SLOT_CHEST;
8215 break;
8216 case INVTYPE_WAIST:
8217 slots[0] = EQUIPMENT_SLOT_WAIST;
8218 break;
8219 case INVTYPE_LEGS:
8220 slots[0] = EQUIPMENT_SLOT_LEGS;
8221 break;
8222 case INVTYPE_FEET:
8223 slots[0] = EQUIPMENT_SLOT_FEET;
8224 break;
8225 case INVTYPE_WRISTS:
8226 slots[0] = EQUIPMENT_SLOT_WRISTS;
8227 break;
8228 case INVTYPE_HANDS:
8229 slots[0] = EQUIPMENT_SLOT_HANDS;
8230 break;
8231 case INVTYPE_FINGER:
8232 slots[0] = EQUIPMENT_SLOT_FINGER1;
8233 slots[1] = EQUIPMENT_SLOT_FINGER2;
8234 break;
8235 case INVTYPE_TRINKET:
8236 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8237 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8238 break;
8239 case INVTYPE_CLOAK:
8240 slots[0] = EQUIPMENT_SLOT_BACK;
8241 break;
8242 case INVTYPE_WEAPON:
8244 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8246 // suggest offhand slot only if know dual wielding
8247 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8248 if(CanDualWield())
8249 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8250 break;
8252 case INVTYPE_SHIELD:
8253 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8254 break;
8255 case INVTYPE_RANGED:
8256 slots[0] = EQUIPMENT_SLOT_RANGED;
8257 break;
8258 case INVTYPE_2HWEAPON:
8259 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8260 if (CanDualWield() && CanTitanGrip())
8261 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8262 break;
8263 case INVTYPE_TABARD:
8264 slots[0] = EQUIPMENT_SLOT_TABARD;
8265 break;
8266 case INVTYPE_WEAPONMAINHAND:
8267 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8268 break;
8269 case INVTYPE_WEAPONOFFHAND:
8270 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8271 break;
8272 case INVTYPE_HOLDABLE:
8273 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8274 break;
8275 case INVTYPE_THROWN:
8276 slots[0] = EQUIPMENT_SLOT_RANGED;
8277 break;
8278 case INVTYPE_RANGEDRIGHT:
8279 slots[0] = EQUIPMENT_SLOT_RANGED;
8280 break;
8281 case INVTYPE_BAG:
8282 slots[0] = INVENTORY_SLOT_BAG_1;
8283 slots[1] = INVENTORY_SLOT_BAG_2;
8284 slots[2] = INVENTORY_SLOT_BAG_3;
8285 slots[3] = INVENTORY_SLOT_BAG_4;
8286 break;
8287 case INVTYPE_RELIC:
8289 switch(proto->SubClass)
8291 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8292 if (pClass == CLASS_PALADIN)
8293 slots[0] = EQUIPMENT_SLOT_RANGED;
8294 break;
8295 case ITEM_SUBCLASS_ARMOR_IDOL:
8296 if (pClass == CLASS_DRUID)
8297 slots[0] = EQUIPMENT_SLOT_RANGED;
8298 break;
8299 case ITEM_SUBCLASS_ARMOR_TOTEM:
8300 if (pClass == CLASS_SHAMAN)
8301 slots[0] = EQUIPMENT_SLOT_RANGED;
8302 break;
8303 case ITEM_SUBCLASS_ARMOR_MISC:
8304 if (pClass == CLASS_WARLOCK)
8305 slots[0] = EQUIPMENT_SLOT_RANGED;
8306 break;
8307 case ITEM_SUBCLASS_ARMOR_SIGIL:
8308 if (pClass == CLASS_DEATH_KNIGHT)
8309 slots[0] = EQUIPMENT_SLOT_RANGED;
8310 break;
8312 break;
8314 default :
8315 return NULL_SLOT;
8318 if( slot != NULL_SLOT )
8320 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8322 for (int i = 0; i < 4; i++)
8324 if ( slots[i] == slot )
8325 return slot;
8329 else
8331 // search free slot at first
8332 for (int i = 0; i < 4; i++)
8334 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8336 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8337 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8338 return slots[i];
8342 // if not found free and can swap return first appropriate from used
8343 for (int i = 0; i < 4; i++)
8345 if ( slots[i] != NULL_SLOT && swap )
8346 return slots[i];
8350 // no free position
8351 return NULL_SLOT;
8354 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8356 Item *pItem;
8357 uint32 tempcount = 0;
8359 uint8 res = EQUIP_ERR_OK;
8361 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
8363 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8364 if( pItem && pItem->GetEntry() == item )
8366 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8367 if(ires==EQUIP_ERR_OK)
8369 tempcount += pItem->GetCount();
8370 if( tempcount >= count )
8371 return EQUIP_ERR_OK;
8373 else
8374 res = ires;
8377 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
8379 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8380 if( pItem && pItem->GetEntry() == item )
8382 tempcount += pItem->GetCount();
8383 if( tempcount >= count )
8384 return EQUIP_ERR_OK;
8387 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8389 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8390 if( pItem && pItem->GetEntry() == item )
8392 tempcount += pItem->GetCount();
8393 if( tempcount >= count )
8394 return EQUIP_ERR_OK;
8397 Bag *pBag;
8398 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8400 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8401 if( pBag )
8403 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8405 pItem = GetItemByPos( i, j );
8406 if( pItem && pItem->GetEntry() == item )
8408 tempcount += pItem->GetCount();
8409 if( tempcount >= count )
8410 return EQUIP_ERR_OK;
8416 // not found req. item count and have unequippable items
8417 return res;
8420 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8422 uint32 count = 0;
8423 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8425 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8426 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8427 count += pItem->GetCount();
8429 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8431 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8432 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8433 count += pItem->GetCount();
8435 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8437 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8438 if( pBag )
8439 count += pBag->GetItemCount(item,skipItem);
8442 if(skipItem && skipItem->GetProto()->GemProperties)
8444 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8446 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8447 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8448 count += pItem->GetGemCountWithID(item);
8452 if(inBankAlso)
8454 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8456 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8457 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8458 count += pItem->GetCount();
8460 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8462 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8463 if( pBag )
8464 count += pBag->GetItemCount(item,skipItem);
8467 if(skipItem && skipItem->GetProto()->GemProperties)
8469 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8471 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8472 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8473 count += pItem->GetGemCountWithID(item);
8478 return count;
8481 Item* Player::GetItemByGuid( uint64 guid ) const
8483 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8485 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8486 if( pItem && pItem->GetGUID() == guid )
8487 return pItem;
8489 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8491 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8492 if( pItem && pItem->GetGUID() == guid )
8493 return pItem;
8496 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8498 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8499 if( pBag )
8501 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8503 Item* pItem = pBag->GetItemByPos( j );
8504 if( pItem && pItem->GetGUID() == guid )
8505 return pItem;
8509 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8511 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8512 if( pBag )
8514 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8516 Item* pItem = pBag->GetItemByPos( j );
8517 if( pItem && pItem->GetGUID() == guid )
8518 return pItem;
8523 return NULL;
8526 Item* Player::GetItemByPos( uint16 pos ) const
8528 uint8 bag = pos >> 8;
8529 uint8 slot = pos & 255;
8530 return GetItemByPos( bag, slot );
8533 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8535 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8536 return m_items[slot];
8537 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8538 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8540 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8541 if ( pBag )
8542 return pBag->GetItemByPos(slot);
8544 return NULL;
8547 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8549 uint16 slot;
8550 switch (attackType)
8552 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8553 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8554 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8555 default: return NULL;
8558 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8559 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8560 return NULL;
8562 if(!useable)
8563 return item;
8565 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8566 return NULL;
8568 return item;
8571 Item* Player::GetShield(bool useable) const
8573 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8574 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8575 return NULL;
8577 if(!useable)
8578 return item;
8580 if( item->IsBroken())
8581 return NULL;
8583 return item;
8586 uint32 Player::GetAttackBySlot( uint8 slot )
8588 switch(slot)
8590 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8591 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8592 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8593 default: return MAX_ATTACK;
8597 bool Player::HasBankBagSlot( uint8 slot ) const
8599 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8600 if( slot < maxslot )
8601 return true;
8602 return false;
8605 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8607 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8608 return true;
8609 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8610 return true;
8611 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8612 return true;
8613 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8614 return true;
8615 return false;
8618 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8620 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8621 return true;
8622 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8623 return true;
8624 return false;
8627 bool Player::IsBankPos( uint8 bag, uint8 slot )
8629 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8630 return true;
8631 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8632 return true;
8633 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8634 return true;
8635 return false;
8638 bool Player::IsBagPos( uint16 pos )
8640 uint8 bag = pos >> 8;
8641 uint8 slot = pos & 255;
8642 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8643 return true;
8644 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8645 return true;
8646 return false;
8649 bool Player::IsValidPos( uint8 bag, uint8 slot )
8651 // post selected
8652 if(bag == NULL_BAG)
8653 return true;
8655 if (bag == INVENTORY_SLOT_BAG_0)
8657 // any post selected
8658 if (slot == NULL_SLOT)
8659 return true;
8661 // equipment
8662 if (slot < EQUIPMENT_SLOT_END)
8663 return true;
8665 // bag equip slots
8666 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8667 return true;
8669 // backpack slots
8670 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8671 return true;
8673 // keyring slots
8674 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8675 return true;
8677 // bank main slots
8678 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8679 return true;
8681 // bank bag slots
8682 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8683 return true;
8685 return false;
8688 // bag content slots
8689 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8691 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8692 if(!pBag)
8693 return false;
8695 // any post selected
8696 if (slot == NULL_SLOT)
8697 return true;
8699 return slot < pBag->GetBagSize();
8702 // bank bag content slots
8703 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8705 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8706 if(!pBag)
8707 return false;
8709 // any post selected
8710 if (slot == NULL_SLOT)
8711 return true;
8713 return slot < pBag->GetBagSize();
8716 // where this?
8717 return false;
8721 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8723 uint32 tempcount = 0;
8724 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8726 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8727 if( pItem && pItem->GetEntry() == item )
8729 tempcount += pItem->GetCount();
8730 if( tempcount >= count )
8731 return true;
8734 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8736 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8737 if( pItem && pItem->GetEntry() == item )
8739 tempcount += pItem->GetCount();
8740 if( tempcount >= count )
8741 return true;
8744 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8746 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8748 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8750 Item* pItem = GetItemByPos( i, j );
8751 if( pItem && pItem->GetEntry() == item )
8753 tempcount += pItem->GetCount();
8754 if( tempcount >= count )
8755 return true;
8761 if(inBankAlso)
8763 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8765 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8766 if( pItem && pItem->GetEntry() == item )
8768 tempcount += pItem->GetCount();
8769 if( tempcount >= count )
8770 return true;
8773 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8775 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8777 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8779 Item* pItem = GetItemByPos( i, j );
8780 if( pItem && pItem->GetEntry() == item )
8782 tempcount += pItem->GetCount();
8783 if( tempcount >= count )
8784 return true;
8791 return false;
8794 Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
8796 Item *pItem;
8797 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8799 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8800 if( pItem && pItem->GetEntry() == item )
8801 return pItem;
8804 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8805 if (pProto && pProto->GemProperties)
8807 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8809 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8810 if( pItem && pItem->GetProto()->Socket[0].Color )
8812 if (pItem->GetGemCountWithID(item) > 0 )
8813 return pItem;
8818 return NULL;
8821 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8823 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8824 if( !pProto )
8826 if(no_space_count)
8827 *no_space_count = count;
8828 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8831 // no maximum
8832 if(pProto->MaxCount <= 0)
8833 return EQUIP_ERR_OK;
8835 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8837 if (curcount + count > uint32(pProto->MaxCount))
8839 if(no_space_count)
8840 *no_space_count = count +curcount - pProto->MaxCount;
8841 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8844 return EQUIP_ERR_OK;
8847 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8849 Item *pItem;
8850 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8852 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8853 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8854 return true;
8856 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8858 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8859 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8860 return true;
8862 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8864 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8866 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8868 pItem = GetItemByPos( i, j );
8869 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8870 return true;
8874 return false;
8877 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8879 Item* pItem2 = GetItemByPos( bag, slot );
8881 // ignore move item (this slot will be empty at move)
8882 if(pItem2==pSrcItem)
8883 pItem2 = NULL;
8885 uint32 need_space;
8887 // empty specific slot - check item fit to slot
8888 if( !pItem2 || swap )
8890 if( bag == INVENTORY_SLOT_BAG_0 )
8892 // keyring case
8893 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8894 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8896 // vanitypet case (disabled until proper implement)
8897 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS*/))
8898 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8900 // currencytoken case (disabled until proper implement)
8901 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS*/))
8902 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8904 // guestbag case (disabled until proper implement)
8905 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS*/))
8906 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8908 // prevent cheating
8909 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8910 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8912 else
8914 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8915 if( !pBag )
8916 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8918 ItemPrototype const* pBagProto = pBag->GetProto();
8919 if( !pBagProto )
8920 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8922 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8923 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8926 // non empty stack with space
8927 need_space = pProto->GetMaxStackSize();
8929 // non empty slot, check item type
8930 else
8932 // check item type
8933 if(pItem2->GetEntry() != pProto->ItemId)
8934 return EQUIP_ERR_ITEM_CANT_STACK;
8936 // check free space
8937 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8938 return EQUIP_ERR_ITEM_CANT_STACK;
8940 // free stack space or infinity
8941 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8944 if(need_space > count)
8945 need_space = count;
8947 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8948 if(!newPosition.isContainedIn(dest))
8950 dest.push_back(newPosition);
8951 count -= need_space;
8953 return EQUIP_ERR_OK;
8956 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
8958 // skip specific bag already processed in first called _CanStoreItem_InBag
8959 if(bag==skip_bag)
8960 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8962 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8963 if( !pBag )
8964 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8966 ItemPrototype const* pBagProto = pBag->GetProto();
8967 if( !pBagProto )
8968 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8970 // specialized bag mode or non-specilized
8971 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8972 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8974 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8975 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8977 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8979 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8980 if(j==skip_slot)
8981 continue;
8983 Item* pItem2 = GetItemByPos( bag, j );
8985 // ignore move item (this slot will be empty at move)
8986 if(pItem2==pSrcItem)
8987 pItem2 = NULL;
8989 // if merge skip empty, if !merge skip non-empty
8990 if((pItem2!=NULL)!=merge)
8991 continue;
8993 if( pItem2 )
8995 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8997 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8998 if(need_space > count)
8999 need_space = count;
9001 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9002 if(!newPosition.isContainedIn(dest))
9004 dest.push_back(newPosition);
9005 count -= need_space;
9007 if(count==0)
9008 return EQUIP_ERR_OK;
9012 else
9014 uint32 need_space = pProto->GetMaxStackSize();
9015 if(need_space > count)
9016 need_space = count;
9018 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9019 if(!newPosition.isContainedIn(dest))
9021 dest.push_back(newPosition);
9022 count -= need_space;
9024 if(count==0)
9025 return EQUIP_ERR_OK;
9029 return EQUIP_ERR_OK;
9032 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
9034 for(uint32 j = slot_begin; j < slot_end; j++)
9036 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9037 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
9038 continue;
9040 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
9042 // ignore move item (this slot will be empty at move)
9043 if(pItem2==pSrcItem)
9044 pItem2 = NULL;
9046 // if merge skip empty, if !merge skip non-empty
9047 if((pItem2!=NULL)!=merge)
9048 continue;
9050 if( pItem2 )
9052 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9054 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9055 if(need_space > count)
9056 need_space = count;
9057 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9058 if(!newPosition.isContainedIn(dest))
9060 dest.push_back(newPosition);
9061 count -= need_space;
9063 if(count==0)
9064 return EQUIP_ERR_OK;
9068 else
9070 uint32 need_space = pProto->GetMaxStackSize();
9071 if(need_space > count)
9072 need_space = count;
9074 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9075 if(!newPosition.isContainedIn(dest))
9077 dest.push_back(newPosition);
9078 count -= need_space;
9080 if(count==0)
9081 return EQUIP_ERR_OK;
9085 return EQUIP_ERR_OK;
9088 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9090 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9092 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
9093 if( !pProto )
9095 if(no_space_count)
9096 *no_space_count = count;
9097 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9100 if(pItem && pItem->IsBindedNotWith(GetGUID()))
9102 if(no_space_count)
9103 *no_space_count = count;
9104 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9107 // check count of items (skip for auto move for same player from bank)
9108 uint32 no_similar_count = 0; // can't store this amount similar items
9109 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9110 if(res!=EQUIP_ERR_OK)
9112 if(count==no_similar_count)
9114 if(no_space_count)
9115 *no_space_count = no_similar_count;
9116 return res;
9118 count -= no_similar_count;
9121 // in specific slot
9122 if( bag != NULL_BAG && slot != NULL_SLOT )
9124 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9125 if(res!=EQUIP_ERR_OK)
9127 if(no_space_count)
9128 *no_space_count = count + no_similar_count;
9129 return res;
9132 if(count==0)
9134 if(no_similar_count==0)
9135 return EQUIP_ERR_OK;
9137 if(no_space_count)
9138 *no_space_count = count + no_similar_count;
9139 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9143 // not specific slot or have space for partly store only in specific slot
9145 // in specific bag
9146 if( bag != NULL_BAG )
9148 // search stack in bag for merge to
9149 if( pProto->Stackable != 1 )
9151 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9153 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9154 if(res!=EQUIP_ERR_OK)
9156 if(no_space_count)
9157 *no_space_count = count + no_similar_count;
9158 return res;
9161 if(count==0)
9163 if(no_similar_count==0)
9164 return EQUIP_ERR_OK;
9166 if(no_space_count)
9167 *no_space_count = count + no_similar_count;
9168 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9171 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9172 if(res!=EQUIP_ERR_OK)
9174 if(no_space_count)
9175 *no_space_count = count + no_similar_count;
9176 return res;
9179 if(count==0)
9181 if(no_similar_count==0)
9182 return EQUIP_ERR_OK;
9184 if(no_space_count)
9185 *no_space_count = count + no_similar_count;
9186 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9189 else // equipped bag
9191 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9192 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9193 if(res!=EQUIP_ERR_OK)
9194 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9196 if(res!=EQUIP_ERR_OK)
9198 if(no_space_count)
9199 *no_space_count = count + no_similar_count;
9200 return res;
9203 if(count==0)
9205 if(no_similar_count==0)
9206 return EQUIP_ERR_OK;
9208 if(no_space_count)
9209 *no_space_count = count + no_similar_count;
9210 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9215 // search free slot in bag for place to
9216 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9218 // search free slot - keyring case
9219 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9221 uint32 keyringSize = GetMaxKeyringSize();
9222 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9223 if(res!=EQUIP_ERR_OK)
9225 if(no_space_count)
9226 *no_space_count = count + no_similar_count;
9227 return res;
9230 if(count==0)
9232 if(no_similar_count==0)
9233 return EQUIP_ERR_OK;
9235 if(no_space_count)
9236 *no_space_count = count + no_similar_count;
9237 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9240 /* until proper implementation
9241 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9243 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9244 if(res!=EQUIP_ERR_OK)
9246 if(no_space_count)
9247 *no_space_count = count + no_similar_count;
9248 return res;
9251 if(count==0)
9253 if(no_similar_count==0)
9254 return EQUIP_ERR_OK;
9256 if(no_space_count)
9257 *no_space_count = count + no_similar_count;
9258 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9262 /* until proper implementation
9263 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9265 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9266 if(res!=EQUIP_ERR_OK)
9268 if(no_space_count)
9269 *no_space_count = count + no_similar_count;
9270 return res;
9273 if(count==0)
9275 if(no_similar_count==0)
9276 return EQUIP_ERR_OK;
9278 if(no_space_count)
9279 *no_space_count = count + no_similar_count;
9280 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9284 /* until proper implementation
9285 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9287 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9288 if(res!=EQUIP_ERR_OK)
9290 if(no_space_count)
9291 *no_space_count = count + no_similar_count;
9292 return res;
9295 if(count==0)
9297 if(no_similar_count==0)
9298 return EQUIP_ERR_OK;
9300 if(no_space_count)
9301 *no_space_count = count + no_similar_count;
9302 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9307 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9308 if(res!=EQUIP_ERR_OK)
9310 if(no_space_count)
9311 *no_space_count = count + no_similar_count;
9312 return res;
9315 if(count==0)
9317 if(no_similar_count==0)
9318 return EQUIP_ERR_OK;
9320 if(no_space_count)
9321 *no_space_count = count + no_similar_count;
9322 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9325 else // equipped bag
9327 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9328 if(res!=EQUIP_ERR_OK)
9329 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9331 if(res!=EQUIP_ERR_OK)
9333 if(no_space_count)
9334 *no_space_count = count + no_similar_count;
9335 return res;
9338 if(count==0)
9340 if(no_similar_count==0)
9341 return EQUIP_ERR_OK;
9343 if(no_space_count)
9344 *no_space_count = count + no_similar_count;
9345 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9350 // not specific bag or have space for partly store only in specific bag
9352 // search stack for merge to
9353 if( pProto->Stackable != 1 )
9355 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9356 if(res!=EQUIP_ERR_OK)
9358 if(no_space_count)
9359 *no_space_count = count + no_similar_count;
9360 return res;
9363 if(count==0)
9365 if(no_similar_count==0)
9366 return EQUIP_ERR_OK;
9368 if(no_space_count)
9369 *no_space_count = count + no_similar_count;
9370 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9373 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9374 if(res!=EQUIP_ERR_OK)
9376 if(no_space_count)
9377 *no_space_count = count + no_similar_count;
9378 return res;
9381 if(count==0)
9383 if(no_similar_count==0)
9384 return EQUIP_ERR_OK;
9386 if(no_space_count)
9387 *no_space_count = count + no_similar_count;
9388 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9391 if( pProto->BagFamily )
9393 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9395 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9396 if(res!=EQUIP_ERR_OK)
9397 continue;
9399 if(count==0)
9401 if(no_similar_count==0)
9402 return EQUIP_ERR_OK;
9404 if(no_space_count)
9405 *no_space_count = count + no_similar_count;
9406 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9411 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9413 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9414 if(res!=EQUIP_ERR_OK)
9415 continue;
9417 if(count==0)
9419 if(no_similar_count==0)
9420 return EQUIP_ERR_OK;
9422 if(no_space_count)
9423 *no_space_count = count + no_similar_count;
9424 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9429 // search free slot - special bag case
9430 if( pProto->BagFamily )
9432 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9434 uint32 keyringSize = GetMaxKeyringSize();
9435 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9436 if(res!=EQUIP_ERR_OK)
9438 if(no_space_count)
9439 *no_space_count = count + no_similar_count;
9440 return res;
9443 if(count==0)
9445 if(no_similar_count==0)
9446 return EQUIP_ERR_OK;
9448 if(no_space_count)
9449 *no_space_count = count + no_similar_count;
9450 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9453 /* until proper implementation
9454 else if(false pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9456 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9457 if(res!=EQUIP_ERR_OK)
9459 if(no_space_count)
9460 *no_space_count = count + no_similar_count;
9461 return res;
9464 if(count==0)
9466 if(no_similar_count==0)
9467 return EQUIP_ERR_OK;
9469 if(no_space_count)
9470 *no_space_count = count + no_similar_count;
9471 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9475 /* until proper implementation
9476 else if(false pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9478 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9479 if(res!=EQUIP_ERR_OK)
9481 if(no_space_count)
9482 *no_space_count = count + no_similar_count;
9483 return res;
9486 if(count==0)
9488 if(no_similar_count==0)
9489 return EQUIP_ERR_OK;
9491 if(no_space_count)
9492 *no_space_count = count + no_similar_count;
9493 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9497 /* until proper implementation
9498 else if(false pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9500 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9501 if(res!=EQUIP_ERR_OK)
9503 if(no_space_count)
9504 *no_space_count = count + no_similar_count;
9505 return res;
9508 if(count==0)
9510 if(no_similar_count==0)
9511 return EQUIP_ERR_OK;
9513 if(no_space_count)
9514 *no_space_count = count + no_similar_count;
9515 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9520 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9522 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9523 if(res!=EQUIP_ERR_OK)
9524 continue;
9526 if(count==0)
9528 if(no_similar_count==0)
9529 return EQUIP_ERR_OK;
9531 if(no_space_count)
9532 *no_space_count = count + no_similar_count;
9533 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9538 // search free slot
9539 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9540 if(res!=EQUIP_ERR_OK)
9542 if(no_space_count)
9543 *no_space_count = count + no_similar_count;
9544 return res;
9547 if(count==0)
9549 if(no_similar_count==0)
9550 return EQUIP_ERR_OK;
9552 if(no_space_count)
9553 *no_space_count = count + no_similar_count;
9554 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9557 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9559 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9560 if(res!=EQUIP_ERR_OK)
9561 continue;
9563 if(count==0)
9565 if(no_similar_count==0)
9566 return EQUIP_ERR_OK;
9568 if(no_space_count)
9569 *no_space_count = count + no_similar_count;
9570 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9574 if(no_space_count)
9575 *no_space_count = count + no_similar_count;
9577 return EQUIP_ERR_INVENTORY_FULL;
9580 //////////////////////////////////////////////////////////////////////////
9581 uint8 Player::CanStoreItems( Item **pItems,int count) const
9583 Item *pItem2;
9585 // fill space table
9586 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9587 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9588 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9589 int inv_pets[VANITYPET_SLOT_END-VANITYPET_SLOT_START];
9590 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9591 int inv_quests[QUESTBAG_SLOT_END-QUESTBAG_SLOT_START];
9593 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9594 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9595 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9596 memset(inv_pets,0,sizeof(int)*(VANITYPET_SLOT_END-VANITYPET_SLOT_START));
9597 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9598 memset(inv_quests,0,sizeof(int)*(QUESTBAG_SLOT_END-QUESTBAG_SLOT_START));
9600 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9602 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9604 if (pItem2 && !pItem2->IsInTrade())
9606 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9610 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9612 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9614 if (pItem2 && !pItem2->IsInTrade())
9616 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9620 for(int i = VANITYPET_SLOT_START; i < VANITYPET_SLOT_END; i++)
9622 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9624 if (pItem2 && !pItem2->IsInTrade())
9626 inv_pets[i-VANITYPET_SLOT_START] = pItem2->GetCount();
9630 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
9632 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9634 if (pItem2 && !pItem2->IsInTrade())
9636 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9640 for(int i = QUESTBAG_SLOT_START; i < QUESTBAG_SLOT_END; i++)
9642 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9644 if (pItem2 && !pItem2->IsInTrade())
9646 inv_quests[i-QUESTBAG_SLOT_START] = pItem2->GetCount();
9650 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9652 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9654 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9656 pItem2 = GetItemByPos( i, j );
9657 if (pItem2 && !pItem2->IsInTrade())
9659 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9665 // check free space for all items
9666 for (int k=0;k<count;k++)
9668 Item *pItem = pItems[k];
9670 // no item
9671 if (!pItem) continue;
9673 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9674 ItemPrototype const *pProto = pItem->GetProto();
9676 // strange item
9677 if( !pProto )
9678 return EQUIP_ERR_ITEM_NOT_FOUND;
9680 // item it 'bind'
9681 if(pItem->IsBindedNotWith(GetGUID()))
9682 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9684 Bag *pBag;
9685 ItemPrototype const *pBagProto;
9687 // item is 'one item only'
9688 uint8 res = CanTakeMoreSimilarItems(pItem);
9689 if(res != EQUIP_ERR_OK)
9690 return res;
9692 // search stack for merge to
9693 if( pProto->Stackable != 1 )
9695 bool b_found = false;
9697 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9699 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9700 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9702 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9703 b_found = true;
9704 break;
9707 if (b_found) continue;
9709 for(int t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; t++)
9711 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9712 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_pets[t-VANITYPET_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9714 inv_pets[t-VANITYPET_SLOT_START] += pItem->GetCount();
9715 b_found = true;
9716 break;
9719 if (b_found) continue;
9721 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9723 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9724 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9726 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9727 b_found = true;
9728 break;
9731 if (b_found) continue;
9733 for(int t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; t++)
9735 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9736 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_quests[t-QUESTBAG_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9738 inv_quests[t-QUESTBAG_SLOT_START] += pItem->GetCount();
9739 b_found = true;
9740 break;
9743 if (b_found) continue;
9745 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9747 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9748 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9750 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9751 b_found = true;
9752 break;
9755 if (b_found) continue;
9757 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9759 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9760 if( pBag )
9762 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9764 pItem2 = GetItemByPos( t, j );
9765 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9767 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9768 b_found = true;
9769 break;
9774 if (b_found) continue;
9777 // special bag case
9778 if( pProto->BagFamily )
9780 bool b_found = false;
9781 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9783 uint32 keyringSize = GetMaxKeyringSize();
9784 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9786 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9788 inv_keys[t-KEYRING_SLOT_START] = 1;
9789 b_found = true;
9790 break;
9795 if (b_found) continue;
9797 /* until proper implementation
9798 if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9800 for(uint32 t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; ++t)
9802 if( inv_pets[t-VANITYPET_SLOT_START] == 0 )
9804 inv_pets[t-VANITYPET_SLOT_START] = 1;
9805 b_found = true;
9806 break;
9811 if (b_found) continue;
9813 /* until proper implementation
9814 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9816 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9818 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9820 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9821 b_found = true;
9822 break;
9827 if (b_found) continue;
9829 /* until proper implementation
9830 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9832 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9834 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9836 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9837 b_found = true;
9838 break;
9843 if (b_found) continue;
9846 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9848 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9849 if( pBag )
9851 pBagProto = pBag->GetProto();
9853 // not plain container check
9854 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9855 ItemCanGoIntoBag(pProto,pBagProto) )
9857 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9859 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9861 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9862 b_found = true;
9863 break;
9869 if (b_found) continue;
9872 // search free slot
9873 bool b_found = false;
9874 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9876 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9878 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9879 b_found = true;
9880 break;
9883 if (b_found) continue;
9885 // search free slot in bags
9886 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9888 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9889 if( pBag )
9891 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9893 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9895 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9896 b_found = true;
9897 break;
9903 // no free slot found?
9904 if (!b_found)
9905 return EQUIP_ERR_INVENTORY_FULL;
9908 return EQUIP_ERR_OK;
9911 //////////////////////////////////////////////////////////////////////////
9912 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9914 dest = 0;
9915 Item *pItem = Item::CreateItem( item, 1, this );
9916 if( pItem )
9918 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9919 delete pItem;
9920 return result;
9923 return EQUIP_ERR_ITEM_NOT_FOUND;
9926 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9928 dest = 0;
9929 if( pItem )
9931 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9932 ItemPrototype const *pProto = pItem->GetProto();
9933 if( pProto )
9935 // May be here should be more stronger checks; STUNNED checked
9936 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9937 if (not_loading && hasUnitState(UNIT_STAT_STUNNED))
9938 return EQUIP_ERR_YOU_ARE_STUNNED;
9940 if(pItem->IsBindedNotWith(GetGUID()))
9941 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9943 // check count of items (skip for auto move for same player from bank)
9944 uint8 res = CanTakeMoreSimilarItems(pItem);
9945 if(res != EQUIP_ERR_OK)
9946 return res;
9948 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9949 // - combat
9950 // - in-progress arenas
9951 if( !pProto->CanChangeEquipStateInCombat() )
9953 if( isInCombat() )
9954 return EQUIP_ERR_NOT_IN_COMBAT;
9956 if(BattleGround* bg = GetBattleGround())
9957 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9958 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9961 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9962 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9964 if(IsNonMeleeSpellCasted(false))
9965 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9967 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9968 if( eslot == NULL_SLOT )
9969 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9971 uint8 msg = CanUseItem( pItem , not_loading );
9972 if( msg != EQUIP_ERR_OK )
9973 return msg;
9974 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9975 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9977 // check unique-equipped on item
9978 if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
9980 // there is an equip limit on this item
9981 Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
9982 if (tItem && (!swap || tItem->GetSlot() != eslot ) )
9983 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9986 // check unique-equipped on gems
9987 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
9989 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
9990 if(!enchant_id)
9991 continue;
9992 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
9993 if(!enchantEntry)
9994 continue;
9996 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
9997 if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
9999 Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
10000 if(tItem && (!swap || tItem->GetSlot() != eslot ))
10001 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
10005 // check unique-equipped special item classes
10006 if (pProto->Class == ITEM_CLASS_QUIVER)
10008 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10010 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
10012 if( ItemPrototype const* pBagProto = pBag->GetProto() )
10014 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
10015 (!swap || pBag->GetSlot() != eslot ) )
10017 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
10018 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
10019 else
10020 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
10027 uint32 type = pProto->InventoryType;
10029 if(eslot == EQUIPMENT_SLOT_OFFHAND)
10031 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
10033 if(!CanDualWield())
10034 return EQUIP_ERR_CANT_DUAL_WIELD;
10036 else if (type == INVTYPE_2HWEAPON)
10038 if(!CanDualWield() || !CanTitanGrip())
10039 return EQUIP_ERR_CANT_DUAL_WIELD;
10042 if(IsTwoHandUsed())
10043 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
10046 // equip two-hand weapon case (with possible unequip 2 items)
10047 if( type == INVTYPE_2HWEAPON )
10049 if (eslot == EQUIPMENT_SLOT_OFFHAND)
10051 if (!CanTitanGrip())
10052 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10054 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
10055 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10057 if (!CanTitanGrip())
10059 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
10060 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
10061 ItemPosCountVec off_dest;
10062 if( offItem && (!not_loading ||
10063 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
10064 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
10065 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
10068 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
10069 return EQUIP_ERR_OK;
10072 if( !swap )
10073 return EQUIP_ERR_ITEM_NOT_FOUND;
10074 else
10075 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
10078 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
10080 // Applied only to equipped items and bank bags
10081 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
10082 return EQUIP_ERR_OK;
10084 Item* pItem = GetItemByPos(pos);
10086 // Applied only to existed equipped item
10087 if( !pItem )
10088 return EQUIP_ERR_OK;
10090 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
10092 ItemPrototype const *pProto = pItem->GetProto();
10093 if( !pProto )
10094 return EQUIP_ERR_ITEM_NOT_FOUND;
10096 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10097 // - combat
10098 // - in-progress arenas
10099 if( !pProto->CanChangeEquipStateInCombat() )
10101 if( isInCombat() )
10102 return EQUIP_ERR_NOT_IN_COMBAT;
10104 if(BattleGround* bg = GetBattleGround())
10105 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
10106 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
10109 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
10110 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
10112 return EQUIP_ERR_OK;
10115 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
10117 if( !pItem )
10118 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10120 uint32 count = pItem->GetCount();
10122 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
10123 ItemPrototype const *pProto = pItem->GetProto();
10124 if( !pProto )
10125 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10127 if( pItem->IsBindedNotWith(GetGUID()) )
10128 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10130 // check count of items (skip for auto move for same player from bank)
10131 uint8 res = CanTakeMoreSimilarItems(pItem);
10132 if(res != EQUIP_ERR_OK)
10133 return res;
10135 // in specific slot
10136 if( bag != NULL_BAG && slot != NULL_SLOT )
10138 if( pProto->InventoryType == INVTYPE_BAG )
10140 Bag *pBag = (Bag*)pItem;
10141 if( pBag )
10143 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
10145 if( !HasBankBagSlot( slot ) )
10146 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
10147 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
10148 return cantuse;
10150 else
10152 if( !pBag->IsEmpty() )
10153 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
10157 else
10159 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
10160 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
10163 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
10164 if(res!=EQUIP_ERR_OK)
10165 return res;
10167 if(count==0)
10168 return EQUIP_ERR_OK;
10171 // not specific slot or have space for partly store only in specific slot
10173 // in specific bag
10174 if( bag != NULL_BAG )
10176 if( pProto->InventoryType == INVTYPE_BAG )
10178 Bag *pBag = (Bag*)pItem;
10179 if( pBag && !pBag->IsEmpty() )
10180 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
10183 // search stack in bag for merge to
10184 if( pProto->Stackable != 1 )
10186 if( bag == INVENTORY_SLOT_BAG_0 )
10188 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10189 if(res!=EQUIP_ERR_OK)
10190 return res;
10192 if(count==0)
10193 return EQUIP_ERR_OK;
10195 else
10197 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
10198 if(res!=EQUIP_ERR_OK)
10199 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
10201 if(res!=EQUIP_ERR_OK)
10202 return res;
10204 if(count==0)
10205 return EQUIP_ERR_OK;
10209 // search free slot in bag
10210 if( bag == INVENTORY_SLOT_BAG_0 )
10212 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10213 if(res!=EQUIP_ERR_OK)
10214 return res;
10216 if(count==0)
10217 return EQUIP_ERR_OK;
10219 else
10221 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
10222 if(res!=EQUIP_ERR_OK)
10223 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
10225 if(res!=EQUIP_ERR_OK)
10226 return res;
10228 if(count==0)
10229 return EQUIP_ERR_OK;
10233 // not specific bag or have space for partly store only in specific bag
10235 // search stack for merge to
10236 if( pProto->Stackable != 1 )
10238 // in slots
10239 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10240 if(res!=EQUIP_ERR_OK)
10241 return res;
10243 if(count==0)
10244 return EQUIP_ERR_OK;
10246 // in special bags
10247 if( pProto->BagFamily )
10249 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10251 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10252 if(res!=EQUIP_ERR_OK)
10253 continue;
10255 if(count==0)
10256 return EQUIP_ERR_OK;
10260 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10262 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10263 if(res!=EQUIP_ERR_OK)
10264 continue;
10266 if(count==0)
10267 return EQUIP_ERR_OK;
10271 // search free place in special bag
10272 if( pProto->BagFamily )
10274 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10276 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10277 if(res!=EQUIP_ERR_OK)
10278 continue;
10280 if(count==0)
10281 return EQUIP_ERR_OK;
10285 // search free space
10286 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10287 if(res!=EQUIP_ERR_OK)
10288 return res;
10290 if(count==0)
10291 return EQUIP_ERR_OK;
10293 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10295 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10296 if(res!=EQUIP_ERR_OK)
10297 continue;
10299 if(count==0)
10300 return EQUIP_ERR_OK;
10302 return EQUIP_ERR_BANK_FULL;
10305 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10307 if( pItem )
10309 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10310 if( !isAlive() && not_loading )
10311 return EQUIP_ERR_YOU_ARE_DEAD;
10312 //if( isStunned() )
10313 // return EQUIP_ERR_YOU_ARE_STUNNED;
10314 ItemPrototype const *pProto = pItem->GetProto();
10315 if( pProto )
10317 if( pItem->IsBindedNotWith(GetGUID()) )
10318 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10319 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10320 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10321 if( pItem->GetSkill() != 0 )
10323 if( GetSkillValue( pItem->GetSkill() ) == 0 )
10324 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10326 if( pProto->RequiredSkill != 0 )
10328 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10329 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10330 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10331 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10333 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10334 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10335 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
10336 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10337 if( getLevel() < pProto->RequiredLevel )
10338 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10339 return EQUIP_ERR_OK;
10342 return EQUIP_ERR_ITEM_NOT_FOUND;
10345 bool Player::CanUseItem( ItemPrototype const *pProto )
10347 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10349 if( pProto )
10351 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10352 return false;
10353 if( pProto->RequiredSkill != 0 )
10355 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10356 return false;
10357 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10358 return false;
10360 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10361 return false;
10362 if( getLevel() < pProto->RequiredLevel )
10363 return false;
10364 return true;
10366 return false;
10369 uint8 Player::CanUseAmmo( uint32 item ) const
10371 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10372 if( !isAlive() )
10373 return EQUIP_ERR_YOU_ARE_DEAD;
10374 //if( isStunned() )
10375 // return EQUIP_ERR_YOU_ARE_STUNNED;
10376 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10377 if( pProto )
10379 if( pProto->InventoryType!= INVTYPE_AMMO )
10380 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10381 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10382 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10383 if( pProto->RequiredSkill != 0 )
10385 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10386 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10387 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10388 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10390 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10391 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10392 /*if( GetReputation() < pProto->RequiredReputation )
10393 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10395 if( getLevel() < pProto->RequiredLevel )
10396 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10398 // Requires No Ammo
10399 if(GetDummyAura(46699))
10400 return EQUIP_ERR_BAG_FULL6;
10402 return EQUIP_ERR_OK;
10404 return EQUIP_ERR_ITEM_NOT_FOUND;
10407 void Player::SetAmmo( uint32 item )
10409 if(!item)
10410 return;
10412 // already set
10413 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10414 return;
10416 // check ammo
10417 if(item)
10419 uint8 msg = CanUseAmmo( item );
10420 if( msg != EQUIP_ERR_OK )
10422 SendEquipError( msg, NULL, NULL );
10423 return;
10427 SetUInt32Value(PLAYER_AMMO_ID, item);
10429 _ApplyAmmoBonuses();
10432 void Player::RemoveAmmo()
10434 SetUInt32Value(PLAYER_AMMO_ID, 0);
10436 m_ammoDPS = 0.0f;
10438 if(CanModifyStats())
10439 UpdateDamagePhysical(RANGED_ATTACK);
10442 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10443 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10445 uint32 count = 0;
10446 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10447 count += itr->count;
10449 Item *pItem = Item::CreateItem( item, count, this );
10450 if( pItem )
10452 ItemAddedQuestCheck( item, count );
10453 if(randomPropertyId)
10454 pItem->SetItemRandomProperties(randomPropertyId);
10455 pItem = StoreItem( dest, pItem, update );
10457 return pItem;
10460 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10462 if( !pItem )
10463 return NULL;
10465 Item* lastItem = pItem;
10467 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10469 uint16 pos = itr->pos;
10470 uint32 count = itr->count;
10472 ++itr;
10474 if(itr == dest.end())
10476 lastItem = _StoreItem(pos,pItem,count,false,update);
10477 break;
10480 lastItem = _StoreItem(pos,pItem,count,true,update);
10483 return lastItem;
10486 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10487 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10489 if( !pItem )
10490 return NULL;
10492 uint8 bag = pos >> 8;
10493 uint8 slot = pos & 255;
10495 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10497 Item *pItem2 = GetItemByPos( bag, slot );
10499 if( !pItem2 )
10501 if(clone)
10502 pItem = pItem->CloneItem(count,this);
10503 else
10504 pItem->SetCount(count);
10506 if(!pItem)
10507 return NULL;
10509 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10510 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10511 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10512 pItem->SetBinding( true );
10514 if( bag == INVENTORY_SLOT_BAG_0 )
10516 m_items[slot] = pItem;
10517 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10518 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10519 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10521 pItem->SetSlot( slot );
10522 pItem->SetContainer( NULL );
10524 if( IsInWorld() && update )
10526 pItem->AddToWorld();
10527 pItem->SendUpdateToPlayer( this );
10530 pItem->SetState(ITEM_CHANGED, this);
10532 else
10534 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10535 if( pBag )
10537 pBag->StoreItem( slot, pItem, update );
10538 if( IsInWorld() && update )
10540 pItem->AddToWorld();
10541 pItem->SendUpdateToPlayer( this );
10543 pItem->SetState(ITEM_CHANGED, this);
10544 pBag->SetState(ITEM_CHANGED, this);
10548 AddEnchantmentDurations(pItem);
10549 AddItemDurations(pItem);
10551 return pItem;
10553 else
10555 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10556 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10557 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10558 pItem2->SetBinding( true );
10560 pItem2->SetCount( pItem2->GetCount() + count );
10561 if( IsInWorld() && update )
10562 pItem2->SendUpdateToPlayer( this );
10564 if(!clone)
10566 // delete item (it not in any slot currently)
10567 if( IsInWorld() && update )
10569 pItem->RemoveFromWorld();
10570 pItem->DestroyForPlayer( this );
10573 RemoveEnchantmentDurations(pItem);
10574 RemoveItemDurations(pItem);
10576 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10577 pItem->SetState(ITEM_REMOVED, this);
10579 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10580 AddEnchantmentDurations(pItem2);
10582 pItem2->SetState(ITEM_CHANGED, this);
10584 return pItem2;
10588 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10590 Item *pItem = Item::CreateItem( item, 1, this );
10591 if( pItem )
10593 ItemAddedQuestCheck( item, 1 );
10594 Item * retItem = EquipItem( pos, pItem, update );
10596 return retItem;
10598 return NULL;
10601 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10603 if( pItem )
10605 AddEnchantmentDurations(pItem);
10606 AddItemDurations(pItem);
10608 uint8 bag = pos >> 8;
10609 uint8 slot = pos & 255;
10611 Item *pItem2 = GetItemByPos( bag, slot );
10613 if( !pItem2 )
10615 VisualizeItem( slot, pItem);
10617 if(isAlive())
10619 ItemPrototype const *pProto = pItem->GetProto();
10621 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10622 if(pProto && pProto->ItemSet)
10623 AddItemsSetItem(this,pItem);
10625 _ApplyItemMods(pItem, slot, true);
10627 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10629 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10631 if (getClass() == CLASS_ROGUE)
10632 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10634 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10636 if (!spellProto)
10637 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10638 else
10640 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10642 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10643 data << uint64(GetGUID());
10644 data << uint8(1);
10645 data << uint32(cooldownSpell);
10646 data << uint32(0);
10647 GetSession()->SendPacket(&data);
10652 if( IsInWorld() && update )
10654 pItem->AddToWorld();
10655 pItem->SendUpdateToPlayer( this );
10658 ApplyEquipCooldown(pItem);
10660 if( slot == EQUIPMENT_SLOT_MAINHAND )
10661 UpdateExpertise(BASE_ATTACK);
10662 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10663 UpdateExpertise(OFF_ATTACK);
10665 else
10667 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10668 if( IsInWorld() && update )
10669 pItem2->SendUpdateToPlayer( this );
10671 // delete item (it not in any slot currently)
10672 //pItem->DeleteFromDB();
10673 if( IsInWorld() && update )
10675 pItem->RemoveFromWorld();
10676 pItem->DestroyForPlayer( this );
10679 RemoveEnchantmentDurations(pItem);
10680 RemoveItemDurations(pItem);
10682 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10683 pItem->SetState(ITEM_REMOVED, this);
10684 pItem2->SetState(ITEM_CHANGED, this);
10686 ApplyEquipCooldown(pItem2);
10688 return pItem2;
10692 return pItem;
10695 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10697 if( pItem )
10699 AddEnchantmentDurations(pItem);
10700 AddItemDurations(pItem);
10702 uint8 slot = pos & 255;
10703 VisualizeItem( slot, pItem);
10705 if( IsInWorld() )
10707 pItem->AddToWorld();
10708 pItem->SendUpdateToPlayer( this );
10713 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10715 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10716 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10717 // entry // Size: 1
10718 // inspected enchantments // Size: 6
10719 // ? // Size: 5
10720 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10721 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10722 // // = 16
10724 if(pItem)
10726 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10728 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10729 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10731 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10732 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10734 // Use SetInt16Value to prevent set high part to FFFF for negative value
10735 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10736 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10738 else
10740 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10742 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10743 SetUInt32Value(VisibleBase + 0, 0);
10745 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10746 SetUInt32Value(VisibleBase + 1 + i, 0);
10748 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10749 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10753 void Player::VisualizeItem( uint8 slot, Item *pItem)
10755 if(!pItem)
10756 return;
10758 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10759 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10760 pItem->SetBinding( true );
10762 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10764 m_items[slot] = pItem;
10765 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10766 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10767 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10768 pItem->SetSlot( slot );
10769 pItem->SetContainer( NULL );
10771 if( slot < EQUIPMENT_SLOT_END )
10772 SetVisibleItemSlot(slot,pItem);
10774 pItem->SetState(ITEM_CHANGED, this);
10777 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10779 // note: removeitem does not actually change the item
10780 // it only takes the item out of storage temporarily
10781 // note2: if removeitem is to be used for delinking
10782 // the item must be removed from the player's updatequeue
10784 Item *pItem = GetItemByPos( bag, slot );
10785 if( pItem )
10787 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10789 RemoveEnchantmentDurations(pItem);
10790 RemoveItemDurations(pItem);
10792 if( bag == INVENTORY_SLOT_BAG_0 )
10794 if ( slot < INVENTORY_SLOT_BAG_END )
10796 ItemPrototype const *pProto = pItem->GetProto();
10797 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10799 if(pProto && pProto->ItemSet)
10800 RemoveItemsSetItem(this,pProto);
10802 _ApplyItemMods(pItem, slot, false);
10804 // remove item dependent auras and casts (only weapon and armor slots)
10805 if(slot < EQUIPMENT_SLOT_END)
10806 RemoveItemDependentAurasAndCasts(pItem);
10808 // remove held enchantments
10809 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10811 if (pItem->GetItemSuffixFactor())
10813 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10814 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10816 else
10818 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10819 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10824 m_items[slot] = NULL;
10825 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10827 if ( slot < EQUIPMENT_SLOT_END )
10828 SetVisibleItemSlot(slot,NULL);
10830 else
10832 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10833 if( pBag )
10834 pBag->RemoveItem(slot, update);
10836 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10837 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10838 pItem->SetSlot( NULL_SLOT );
10839 if( IsInWorld() && update )
10840 pItem->SendUpdateToPlayer( this );
10842 if( slot == EQUIPMENT_SLOT_MAINHAND )
10843 UpdateExpertise(BASE_ATTACK);
10844 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10845 UpdateExpertise(OFF_ATTACK);
10849 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10850 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10852 if(Item* it = GetItemByPos(bag,slot))
10854 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10855 RemoveItem( bag,slot,update);
10856 it->RemoveFromUpdateQueueOf(this);
10857 if(it->IsInWorld())
10859 it->RemoveFromWorld();
10860 it->DestroyForPlayer( this );
10865 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10866 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10868 // update quest counters
10869 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10871 // store item
10872 Item* pLastItem = StoreItem( dest, pItem, update);
10874 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10875 if(pLastItem==pItem)
10877 // update owner for last item (this can be original item with wrong owner
10878 if(pLastItem->GetOwnerGUID() != GetGUID())
10879 pLastItem->SetOwnerGUID(GetGUID());
10881 // if this original item then it need create record in inventory
10882 // in case trade we already have item in other player inventory
10883 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10887 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10889 Item *pItem = GetItemByPos( bag, slot );
10890 if( pItem )
10892 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10894 // start from destroy contained items (only equipped bag can have its)
10895 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10897 for (int i = 0; i < MAX_BAG_SIZE; i++)
10898 DestroyItem(slot,i,update);
10901 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10902 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10904 RemoveEnchantmentDurations(pItem);
10905 RemoveItemDurations(pItem);
10907 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10909 if( bag == INVENTORY_SLOT_BAG_0 )
10911 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10913 // equipment and equipped bags can have applied bonuses
10914 if ( slot < INVENTORY_SLOT_BAG_END )
10916 ItemPrototype const *pProto = pItem->GetProto();
10918 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10919 if(pProto && pProto->ItemSet)
10920 RemoveItemsSetItem(this,pProto);
10922 _ApplyItemMods(pItem, slot, false);
10925 if ( slot < EQUIPMENT_SLOT_END )
10927 // remove item dependent auras and casts (only weapon and armor slots)
10928 RemoveItemDependentAurasAndCasts(pItem);
10930 // equipment visual show
10931 SetVisibleItemSlot(slot,NULL);
10934 m_items[slot] = NULL;
10936 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10937 pBag->RemoveItem(slot, update);
10939 if( IsInWorld() && update )
10941 pItem->RemoveFromWorld();
10942 pItem->DestroyForPlayer(this);
10945 //pItem->SetOwnerGUID(0);
10946 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10947 pItem->SetSlot( NULL_SLOT );
10948 pItem->SetState(ITEM_REMOVED, this);
10952 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10954 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10955 Item *pItem;
10956 ItemPrototype const *pProto;
10957 uint32 remcount = 0;
10959 // in inventory
10960 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10962 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10963 if( pItem && pItem->GetEntry() == item )
10965 if( pItem->GetCount() + remcount <= count )
10967 // all items in inventory can unequipped
10968 remcount += pItem->GetCount();
10969 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10971 if(remcount >=count)
10972 return;
10974 else
10976 pProto = pItem->GetProto();
10977 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10978 pItem->SetCount( pItem->GetCount() - count + remcount );
10979 if( IsInWorld() & update )
10980 pItem->SendUpdateToPlayer( this );
10981 pItem->SetState(ITEM_CHANGED, this);
10982 return;
10986 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10988 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10989 if( pItem && pItem->GetEntry() == item )
10991 if( pItem->GetCount() + remcount <= count )
10993 // all keys can be unequipped
10994 remcount += pItem->GetCount();
10995 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10997 if(remcount >=count)
10998 return;
11000 else
11002 pProto = pItem->GetProto();
11003 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11004 pItem->SetCount( pItem->GetCount() - count + remcount );
11005 if( IsInWorld() & update )
11006 pItem->SendUpdateToPlayer( this );
11007 pItem->SetState(ITEM_CHANGED, this);
11008 return;
11013 // in inventory bags
11014 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11016 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11018 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11020 pItem = pBag->GetItemByPos(j);
11021 if( pItem && pItem->GetEntry() == item )
11023 // all items in bags can be unequipped
11024 if( pItem->GetCount() + remcount <= count )
11026 remcount += pItem->GetCount();
11027 DestroyItem( i, j, update );
11029 if(remcount >=count)
11030 return;
11032 else
11034 pProto = pItem->GetProto();
11035 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11036 pItem->SetCount( pItem->GetCount() - count + remcount );
11037 if( IsInWorld() && update )
11038 pItem->SendUpdateToPlayer( this );
11039 pItem->SetState(ITEM_CHANGED, this);
11040 return;
11047 // in equipment and bag list
11048 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
11050 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11051 if( pItem && pItem->GetEntry() == item )
11053 if( pItem->GetCount() + remcount <= count )
11055 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
11057 remcount += pItem->GetCount();
11058 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11060 if(remcount >=count)
11061 return;
11064 else
11066 pProto = pItem->GetProto();
11067 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11068 pItem->SetCount( pItem->GetCount() - count + remcount );
11069 if( IsInWorld() & update )
11070 pItem->SendUpdateToPlayer( this );
11071 pItem->SetState(ITEM_CHANGED, this);
11072 return;
11078 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
11080 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
11082 // in inventory
11083 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11085 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11086 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11087 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11089 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
11091 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11092 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11093 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11096 // in inventory bags
11097 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11099 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11100 if( pBag )
11102 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11104 Item* pItem = pBag->GetItemByPos(j);
11105 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11106 DestroyItem( i, j, update);
11111 // in equipment and bag list
11112 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
11114 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11115 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11116 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11120 void Player::DestroyConjuredItems( bool update )
11122 // used when entering arena
11123 // destroys all conjured items
11124 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
11126 // in inventory
11127 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11129 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11130 if( pItem && pItem->GetProto() &&
11131 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11132 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11133 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11136 // in inventory bags
11137 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11139 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11140 if( pBag )
11142 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11144 Item* pItem = pBag->GetItemByPos(j);
11145 if( pItem && pItem->GetProto() &&
11146 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11147 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11148 DestroyItem( i, j, update);
11153 // in equipment and bag list
11154 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
11156 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11157 if( pItem && pItem->GetProto() &&
11158 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11159 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11160 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11164 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
11166 if(!pItem)
11167 return;
11169 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
11171 if( pItem->GetCount() <= count )
11173 count-= pItem->GetCount();
11175 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
11177 else
11179 ItemRemovedQuestCheck( pItem->GetEntry(), count);
11180 pItem->SetCount( pItem->GetCount() - count );
11181 count = 0;
11182 if( IsInWorld() & update )
11183 pItem->SendUpdateToPlayer( this );
11184 pItem->SetState(ITEM_CHANGED, this);
11188 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
11190 uint8 srcbag = src >> 8;
11191 uint8 srcslot = src & 255;
11193 uint8 dstbag = dst >> 8;
11194 uint8 dstslot = dst & 255;
11196 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11197 if( !pSrcItem )
11199 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11200 return;
11203 // not let split all items (can be only at cheating)
11204 if(pSrcItem->GetCount() == count)
11206 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11207 return;
11210 // not let split more existed items (can be only at cheating)
11211 if(pSrcItem->GetCount() < count)
11213 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
11214 return;
11217 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11219 //best error message found for attempting to split while looting
11220 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11221 return;
11224 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11225 Item *pNewItem = pSrcItem->CloneItem( count, this );
11226 if( !pNewItem )
11228 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11229 return;
11232 if( IsInventoryPos( dst ) )
11234 // change item amount before check (for unique max count check)
11235 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11237 ItemPosCountVec dest;
11238 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11239 if( msg != EQUIP_ERR_OK )
11241 delete pNewItem;
11242 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11243 SendEquipError( msg, pSrcItem, NULL );
11244 return;
11247 if( IsInWorld() )
11248 pSrcItem->SendUpdateToPlayer( this );
11249 pSrcItem->SetState(ITEM_CHANGED, this);
11250 StoreItem( dest, pNewItem, true);
11252 else if( IsBankPos ( dst ) )
11254 // change item amount before check (for unique max count check)
11255 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11257 ItemPosCountVec dest;
11258 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11259 if( msg != EQUIP_ERR_OK )
11261 delete pNewItem;
11262 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11263 SendEquipError( msg, pSrcItem, NULL );
11264 return;
11267 if( IsInWorld() )
11268 pSrcItem->SendUpdateToPlayer( this );
11269 pSrcItem->SetState(ITEM_CHANGED, this);
11270 BankItem( dest, pNewItem, true);
11272 else if( IsEquipmentPos ( dst ) )
11274 // change item amount before check (for unique max count check), provide space for splitted items
11275 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11277 uint16 dest;
11278 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11279 if( msg != EQUIP_ERR_OK )
11281 delete pNewItem;
11282 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11283 SendEquipError( msg, pSrcItem, NULL );
11284 return;
11287 if( IsInWorld() )
11288 pSrcItem->SendUpdateToPlayer( this );
11289 pSrcItem->SetState(ITEM_CHANGED, this);
11290 EquipItem( dest, pNewItem, true);
11291 AutoUnequipOffhandIfNeed();
11295 void Player::SwapItem( uint16 src, uint16 dst )
11297 uint8 srcbag = src >> 8;
11298 uint8 srcslot = src & 255;
11300 uint8 dstbag = dst >> 8;
11301 uint8 dstslot = dst & 255;
11303 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11304 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11306 if( !pSrcItem )
11307 return;
11309 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11311 if(!isAlive() )
11313 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11314 return;
11317 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11319 //best error message found for attempting to swap while looting
11320 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11321 return;
11324 // check unequip potability for equipped items and bank bags
11325 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11327 // bags can be swapped with empty bag slots
11328 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ));
11329 if(msg != EQUIP_ERR_OK)
11331 SendEquipError( msg, pSrcItem, pDstItem );
11332 return;
11336 // prevent put equipped/bank bag in self
11337 if( IsBagPos ( src ) && srcslot == dstbag)
11339 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11340 return;
11343 if( !pDstItem )
11345 if( IsInventoryPos( dst ) )
11347 ItemPosCountVec dest;
11348 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11349 if( msg != EQUIP_ERR_OK )
11351 SendEquipError( msg, pSrcItem, NULL );
11352 return;
11355 RemoveItem(srcbag, srcslot, true);
11356 StoreItem( dest, pSrcItem, true);
11358 else if( IsBankPos ( dst ) )
11360 ItemPosCountVec dest;
11361 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11362 if( msg != EQUIP_ERR_OK )
11364 SendEquipError( msg, pSrcItem, NULL );
11365 return;
11368 RemoveItem(srcbag, srcslot, true);
11369 BankItem( dest, pSrcItem, true);
11371 else if( IsEquipmentPos ( dst ) )
11373 uint16 dest;
11374 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11375 if( msg != EQUIP_ERR_OK )
11377 SendEquipError( msg, pSrcItem, NULL );
11378 return;
11381 RemoveItem(srcbag, srcslot, true);
11382 EquipItem( dest, pSrcItem, true);
11383 AutoUnequipOffhandIfNeed();
11386 else // if (!pDstItem)
11388 if(pDstItem->m_lootGenerated) // prevent swap looting item
11390 //best error message found for attempting to swap while looting
11391 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11392 return;
11395 // check unequip potability for equipped items and bank bags
11396 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11398 // bags can be swapped with empty bag slots
11399 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) );
11400 if(msg != EQUIP_ERR_OK)
11402 SendEquipError( msg, pSrcItem, pDstItem );
11403 return;
11407 // attempt merge to / fill target item
11409 uint8 msg;
11410 ItemPosCountVec sDest;
11411 uint16 eDest;
11412 if( IsInventoryPos( dst ) )
11413 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11414 else if( IsBankPos ( dst ) )
11415 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11416 else if( IsEquipmentPos ( dst ) )
11417 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11418 else
11419 return;
11421 // can be merge/fill
11422 if(msg == EQUIP_ERR_OK)
11424 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11426 RemoveItem(srcbag, srcslot, true);
11428 if( IsInventoryPos( dst ) )
11429 StoreItem( sDest, pSrcItem, true);
11430 else if( IsBankPos ( dst ) )
11431 BankItem( sDest, pSrcItem, true);
11432 else if( IsEquipmentPos ( dst ) )
11434 EquipItem( eDest, pSrcItem, true);
11435 AutoUnequipOffhandIfNeed();
11438 else
11440 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11441 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11442 pSrcItem->SetState(ITEM_CHANGED, this);
11443 pDstItem->SetState(ITEM_CHANGED, this);
11444 if( IsInWorld() )
11446 pSrcItem->SendUpdateToPlayer( this );
11447 pDstItem->SendUpdateToPlayer( this );
11450 return;
11454 // impossible merge/fill, do real swap
11455 uint8 msg;
11457 // check src->dest move possibility
11458 ItemPosCountVec sDest;
11459 uint16 eDest;
11460 if( IsInventoryPos( dst ) )
11461 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11462 else if( IsBankPos( dst ) )
11463 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11464 else if( IsEquipmentPos( dst ) )
11466 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11467 if( msg == EQUIP_ERR_OK )
11468 msg = CanUnequipItem( eDest, true );
11471 if( msg != EQUIP_ERR_OK )
11473 SendEquipError( msg, pSrcItem, pDstItem );
11474 return;
11477 // check dest->src move possibility
11478 ItemPosCountVec sDest2;
11479 uint16 eDest2;
11480 if( IsInventoryPos( src ) )
11481 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11482 else if( IsBankPos( src ) )
11483 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11484 else if( IsEquipmentPos( src ) )
11486 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11487 if( msg == EQUIP_ERR_OK )
11488 msg = CanUnequipItem( eDest2, true);
11491 if( msg != EQUIP_ERR_OK )
11493 SendEquipError( msg, pDstItem, pSrcItem );
11494 return;
11497 // now do moves, remove...
11498 RemoveItem(dstbag, dstslot, false);
11499 RemoveItem(srcbag, srcslot, false);
11501 // add to dest
11502 if( IsInventoryPos( dst ) )
11503 StoreItem(sDest, pSrcItem, true);
11504 else if( IsBankPos( dst ) )
11505 BankItem(sDest, pSrcItem, true);
11506 else if( IsEquipmentPos( dst ) )
11507 EquipItem(eDest, pSrcItem, true);
11509 // add to src
11510 if( IsInventoryPos( src ) )
11511 StoreItem(sDest2, pDstItem, true);
11512 else if( IsBankPos( src ) )
11513 BankItem(sDest2, pDstItem, true);
11514 else if( IsEquipmentPos( src ) )
11515 EquipItem(eDest2, pDstItem, true);
11517 AutoUnequipOffhandIfNeed();
11521 void Player::AddItemToBuyBackSlot( Item *pItem )
11523 if( pItem )
11525 uint32 slot = m_currentBuybackSlot;
11526 // if current back slot non-empty search oldest or free
11527 if(m_items[slot])
11529 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11530 uint32 oldest_slot = BUYBACK_SLOT_START;
11532 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11534 // found empty
11535 if(!m_items[i])
11537 slot = i;
11538 break;
11541 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11543 if(oldest_time > i_time)
11545 oldest_time = i_time;
11546 oldest_slot = i;
11550 // find oldest
11551 slot = oldest_slot;
11554 RemoveItemFromBuyBackSlot( slot, true );
11555 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11557 m_items[slot] = pItem;
11558 time_t base = time(NULL);
11559 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11560 uint32 eslot = slot - BUYBACK_SLOT_START;
11562 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11563 ItemPrototype const *pProto = pItem->GetProto();
11564 if( pProto )
11565 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11566 else
11567 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11568 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11570 // move to next (for non filled list is move most optimized choice)
11571 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11572 ++m_currentBuybackSlot;
11576 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11578 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11579 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11580 return m_items[slot];
11581 return NULL;
11584 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11586 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11587 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11589 Item *pItem = m_items[slot];
11590 if( pItem )
11592 pItem->RemoveFromWorld();
11593 if(del) pItem->SetState(ITEM_REMOVED, this);
11596 m_items[slot] = NULL;
11598 uint32 eslot = slot - BUYBACK_SLOT_START;
11599 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11600 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11601 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11603 // if current backslot is filled set to now free slot
11604 if(m_items[m_currentBuybackSlot])
11605 m_currentBuybackSlot = slot;
11609 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11611 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11612 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11613 data << uint8(msg);
11615 if(msg)
11617 data << uint64(pItem ? pItem->GetGUID() : 0);
11618 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11619 data << uint8(0); // not 0 there...
11621 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11623 uint32 level = 0;
11625 if(pItem)
11626 if(ItemPrototype const* proto = pItem->GetProto())
11627 level = proto->RequiredLevel;
11629 data << uint32(level); // new 2.4.0
11632 GetSession()->SendPacket(&data);
11635 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11637 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11638 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11639 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11640 data << uint32(item);
11641 if( param > 0 )
11642 data << uint32(param);
11643 data << uint8(msg);
11644 GetSession()->SendPacket(&data);
11647 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11649 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11650 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11651 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11652 data << uint64(guid);
11653 if( param > 0 )
11654 data << uint32(param);
11655 data << uint8(msg);
11656 GetSession()->SendPacket(&data);
11659 void Player::ClearTrade()
11661 tradeGold = 0;
11662 acceptTrade = false;
11663 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11664 tradeItems[i] = NULL_SLOT;
11667 void Player::TradeCancel(bool sendback)
11669 if(pTrader)
11671 // send yellow "Trade canceled" message to both traders
11672 WorldSession* ws;
11673 ws = GetSession();
11674 if(sendback)
11675 ws->SendCancelTrade();
11676 ws = pTrader->GetSession();
11677 if(!ws->PlayerLogout())
11678 ws->SendCancelTrade();
11680 // cleanup
11681 ClearTrade();
11682 pTrader->ClearTrade();
11683 // prevent loss of reference
11684 pTrader->pTrader = NULL;
11685 pTrader = NULL;
11689 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11691 if(m_itemDuration.empty())
11692 return;
11694 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11696 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11698 Item* item = *itr;
11699 ++itr; // current element can be erased in UpdateDuration
11701 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11702 item->UpdateDuration(this,time);
11706 void Player::UpdateEnchantTime(uint32 time)
11708 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11710 assert(itr->item);
11711 next=itr;
11712 if(!itr->item->GetEnchantmentId(itr->slot))
11714 next = m_enchantDuration.erase(itr);
11716 else if(itr->leftduration <= time)
11718 ApplyEnchantment(itr->item,itr->slot,false,false);
11719 itr->item->ClearEnchantment(itr->slot);
11720 next = m_enchantDuration.erase(itr);
11722 else if(itr->leftduration > time)
11724 itr->leftduration -= time;
11725 ++next;
11730 void Player::AddEnchantmentDurations(Item *item)
11732 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11734 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11735 continue;
11737 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11738 if( duration > 0 )
11739 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11743 void Player::RemoveEnchantmentDurations(Item *item)
11745 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11747 if(itr->item == item)
11749 // save duration in item
11750 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11751 itr = m_enchantDuration.erase(itr);
11753 else
11754 ++itr;
11758 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11760 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11761 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11763 next = itr;
11764 if(itr->slot==slot)
11766 if(itr->item && itr->item->GetEnchantmentId(slot))
11768 // remove from stats
11769 ApplyEnchantment(itr->item,slot,false,false);
11770 // remove visual
11771 itr->item->ClearEnchantment(slot);
11773 // remove from update list
11774 next = m_enchantDuration.erase(itr);
11776 else
11777 ++next;
11780 // remove enchants from inventory items
11781 // NOTE: no need to remove these from stats, since these aren't equipped
11782 // in inventory
11783 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11785 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11786 if( pItem && pItem->GetEnchantmentId(slot) )
11787 pItem->ClearEnchantment(slot);
11790 // in inventory bags
11791 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11793 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11794 if( pBag )
11796 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11798 Item* pItem = pBag->GetItemByPos(j);
11799 if( pItem && pItem->GetEnchantmentId(slot) )
11800 pItem->ClearEnchantment(slot);
11806 // duration == 0 will remove item enchant
11807 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11809 if(!item)
11810 return;
11812 if(slot >= MAX_ENCHANTMENT_SLOT)
11813 return;
11815 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11817 if(itr->item == item && itr->slot == slot)
11819 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11820 m_enchantDuration.erase(itr);
11821 break;
11824 if(item && duration > 0 )
11826 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11827 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11831 void Player::ApplyEnchantment(Item *item,bool apply)
11833 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11834 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11837 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11839 if(!item)
11840 return;
11842 if(!item->IsEquipped())
11843 return;
11845 if(slot >= MAX_ENCHANTMENT_SLOT)
11846 return;
11848 uint32 enchant_id = item->GetEnchantmentId(slot);
11849 if(!enchant_id)
11850 return;
11852 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11853 if(!pEnchant)
11854 return;
11856 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11857 return;
11859 for (int s=0; s<3; s++)
11861 uint32 enchant_display_type = pEnchant->type[s];
11862 uint32 enchant_amount = pEnchant->amount[s];
11863 uint32 enchant_spell_id = pEnchant->spellid[s];
11865 switch(enchant_display_type)
11867 case ITEM_ENCHANTMENT_TYPE_NONE:
11868 break;
11869 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11870 // processed in Player::CastItemCombatSpell
11871 break;
11872 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11873 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11874 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11875 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11876 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11877 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11878 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11879 break;
11880 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11881 if(enchant_spell_id)
11883 if(apply)
11885 int32 basepoints = 0;
11886 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11887 if (item->GetItemRandomPropertyId())
11889 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11890 if (item_rand)
11892 // Search enchant_amount
11893 for (int k=0; k<3; k++)
11895 if(item_rand->enchant_id[k] == enchant_id)
11897 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11898 break;
11903 // Cast custom spell vs all equal basepoints getted from enchant_amount
11904 if (basepoints)
11905 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11906 else
11907 CastSpell(this,enchant_spell_id,true,item);
11909 else
11910 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11912 break;
11913 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11914 if (!enchant_amount)
11916 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11917 if(item_rand)
11919 for (int k=0; k<3; k++)
11921 if(item_rand->enchant_id[k] == enchant_id)
11923 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11924 break;
11930 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11931 break;
11932 case ITEM_ENCHANTMENT_TYPE_STAT:
11934 if (!enchant_amount)
11936 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11937 if(item_rand_suffix)
11939 for (int k=0; k<3; k++)
11941 if(item_rand_suffix->enchant_id[k] == enchant_id)
11943 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11944 break;
11950 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11951 switch (enchant_spell_id)
11953 case ITEM_MOD_AGILITY:
11954 sLog.outDebug("+ %u AGILITY",enchant_amount);
11955 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11956 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11957 break;
11958 case ITEM_MOD_STRENGTH:
11959 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11960 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11961 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11962 break;
11963 case ITEM_MOD_INTELLECT:
11964 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11965 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11966 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11967 break;
11968 case ITEM_MOD_SPIRIT:
11969 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11970 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11971 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11972 break;
11973 case ITEM_MOD_STAMINA:
11974 sLog.outDebug("+ %u STAMINA",enchant_amount);
11975 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11976 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11977 break;
11978 case ITEM_MOD_DEFENSE_SKILL_RATING:
11979 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11980 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11981 break;
11982 case ITEM_MOD_DODGE_RATING:
11983 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11984 sLog.outDebug("+ %u DODGE", enchant_amount);
11985 break;
11986 case ITEM_MOD_PARRY_RATING:
11987 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11988 sLog.outDebug("+ %u PARRY", enchant_amount);
11989 break;
11990 case ITEM_MOD_BLOCK_RATING:
11991 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11992 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11993 break;
11994 case ITEM_MOD_HIT_MELEE_RATING:
11995 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11996 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11997 break;
11998 case ITEM_MOD_HIT_RANGED_RATING:
11999 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12000 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
12001 break;
12002 case ITEM_MOD_HIT_SPELL_RATING:
12003 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12004 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
12005 break;
12006 case ITEM_MOD_CRIT_MELEE_RATING:
12007 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12008 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
12009 break;
12010 case ITEM_MOD_CRIT_RANGED_RATING:
12011 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12012 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
12013 break;
12014 case ITEM_MOD_CRIT_SPELL_RATING:
12015 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12016 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
12017 break;
12018 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12019 // in Enchantments
12020 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12021 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12022 // break;
12023 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12024 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12025 // break;
12026 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12027 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12028 // break;
12029 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12030 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12031 // break;
12032 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12033 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12034 // break;
12035 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12036 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12037 // break;
12038 // case ITEM_MOD_HASTE_MELEE_RATING:
12039 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12040 // break;
12041 // case ITEM_MOD_HASTE_RANGED_RATING:
12042 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12043 // break;
12044 case ITEM_MOD_HASTE_SPELL_RATING:
12045 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12046 break;
12047 case ITEM_MOD_HIT_RATING:
12048 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12049 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12050 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12051 sLog.outDebug("+ %u HIT", enchant_amount);
12052 break;
12053 case ITEM_MOD_CRIT_RATING:
12054 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12055 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12056 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12057 sLog.outDebug("+ %u CRITICAL", enchant_amount);
12058 break;
12059 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12060 // case ITEM_MOD_HIT_TAKEN_RATING:
12061 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12062 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12063 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12064 // break;
12065 // case ITEM_MOD_CRIT_TAKEN_RATING:
12066 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12067 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12068 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12069 // break;
12070 case ITEM_MOD_RESILIENCE_RATING:
12071 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12072 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12073 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12074 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
12075 break;
12076 case ITEM_MOD_HASTE_RATING:
12077 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12078 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12079 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12080 sLog.outDebug("+ %u HASTE", enchant_amount);
12081 break;
12082 case ITEM_MOD_EXPERTISE_RATING:
12083 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
12084 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
12085 break;
12086 case ITEM_MOD_ATTACK_POWER:
12087 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
12088 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
12089 break;
12090 case ITEM_MOD_RANGED_ATTACK_POWER:
12091 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12092 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
12093 break;
12094 case ITEM_MOD_FERAL_ATTACK_POWER:
12095 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
12096 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
12097 break;
12098 case ITEM_MOD_SPELL_HEALING_DONE:
12099 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
12100 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
12101 break;
12102 case ITEM_MOD_SPELL_DAMAGE_DONE:
12103 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
12104 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
12105 break;
12106 case ITEM_MOD_MANA_REGENERATION:
12107 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
12108 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
12109 break;
12110 case ITEM_MOD_ARMOR_PENETRATION_RATING:
12111 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
12112 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
12113 break;
12114 case ITEM_MOD_SPELL_POWER:
12115 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
12116 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
12117 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
12118 break;
12119 default:
12120 break;
12122 break;
12124 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
12126 if(getClass() == CLASS_SHAMAN)
12128 float addValue = 0.0f;
12129 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12131 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
12132 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
12134 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
12136 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
12137 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
12140 break;
12142 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
12143 // processed in Player::CastItemUseSpell
12144 break;
12145 default:
12146 sLog.outError("Unknown item enchantment display type: %d",enchant_display_type);
12147 break;
12148 } /*switch(enchant_display_type)*/
12149 } /*for*/
12151 // visualize enchantment at player and equipped items
12152 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
12154 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
12155 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
12158 if(apply_dur)
12160 if(apply)
12162 // set duration
12163 uint32 duration = item->GetEnchantmentDuration(slot);
12164 if(duration > 0)
12165 AddEnchantmentDuration(item,slot,duration);
12167 else
12169 // duration == 0 will remove EnchantDuration
12170 AddEnchantmentDuration(item,slot,0);
12175 void Player::SendEnchantmentDurations()
12177 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
12179 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
12183 void Player::SendItemDurations()
12185 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
12187 (*itr)->SendTimeUpdate(this);
12191 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12193 if(!item) // prevent crash
12194 return;
12196 // last check 2.0.10
12197 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12198 data << GetGUID(); // player GUID
12199 data << uint32(received); // 0=looted, 1=from npc
12200 data << uint32(created); // 0=received, 1=created
12201 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12202 data << (uint8)item->GetBagSlot(); // bagslot
12203 // item slot, but when added to stack: 0xFFFFFFFF
12204 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
12205 data << uint32(item->GetEntry()); // item id
12206 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12207 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12208 data << uint32(count); // count of items
12209 data << GetItemCount(item->GetEntry()); // count of items in inventory
12211 if (broadcast && GetGroup())
12212 GetGroup()->BroadcastPacket(&data);
12213 else
12214 GetSession()->SendPacket(&data);
12217 /*********************************************************/
12218 /*** QUEST SYSTEM ***/
12219 /*********************************************************/
12221 void Player::PrepareQuestMenu( uint64 guid )
12223 Object *pObject;
12224 QuestRelations* pObjectQR;
12225 QuestRelations* pObjectQIR;
12226 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12227 if( pCreature )
12229 pObject = (Object*)pCreature;
12230 pObjectQR = &objmgr.mCreatureQuestRelations;
12231 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12233 else
12235 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12236 if( pGameObject )
12238 pObject = (Object*)pGameObject;
12239 pObjectQR = &objmgr.mGOQuestRelations;
12240 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12242 else
12243 return;
12246 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12247 qm.ClearMenu();
12249 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12251 uint32 quest_id = i->second;
12252 QuestStatus status = GetQuestStatus( quest_id );
12253 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12254 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
12255 else if ( status == QUEST_STATUS_INCOMPLETE )
12256 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
12257 else if (status == QUEST_STATUS_AVAILABLE )
12258 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12261 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12263 uint32 quest_id = i->second;
12264 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12265 if(!pQuest) continue;
12267 QuestStatus status = GetQuestStatus( quest_id );
12269 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12270 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
12271 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12272 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
12276 void Player::SendPreparedQuest( uint64 guid )
12278 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12279 if( questMenu.Empty() )
12280 return;
12282 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
12284 uint32 status = qmi0.m_qIcon;
12286 // single element case
12287 if ( questMenu.MenuItemCount() == 1 )
12289 // Auto open -- maybe also should verify there is no greeting
12290 uint32 quest_id = qmi0.m_qId;
12291 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12292 if ( pQuest )
12294 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
12295 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
12296 else if( status == DIALOG_STATUS_INCOMPLETE )
12297 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
12298 // Send completable on repeatable quest if player don't have quest
12299 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
12300 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
12301 else
12302 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
12305 // multiply entries
12306 else
12308 QEmote qe;
12309 qe._Delay = 0;
12310 qe._Emote = 0;
12311 std::string title = "";
12312 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12313 if( pCreature )
12315 uint32 textid = pCreature->GetNpcTextId();
12316 GossipText * gossiptext = objmgr.GetGossipText(textid);
12317 if( !gossiptext )
12319 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12320 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12321 title = "";
12323 else
12325 qe = gossiptext->Options[0].Emotes[0];
12327 if(!gossiptext->Options[0].Text_0.empty())
12329 title = gossiptext->Options[0].Text_0;
12331 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12332 if (loc_idx >= 0)
12334 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12335 if (nl)
12337 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12338 title = nl->Text_0[0][loc_idx];
12342 else
12344 title = gossiptext->Options[0].Text_1;
12346 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12347 if (loc_idx >= 0)
12349 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12350 if (nl)
12352 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12353 title = nl->Text_1[0][loc_idx];
12359 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12363 bool Player::IsActiveQuest( uint32 quest_id ) const
12365 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12367 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12370 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12372 Object *pObject;
12373 QuestRelations* pObjectQR;
12374 QuestRelations* pObjectQIR;
12376 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12377 if( pCreature )
12379 pObject = (Object*)pCreature;
12380 pObjectQR = &objmgr.mCreatureQuestRelations;
12381 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12383 else
12385 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12386 if( pGameObject )
12388 pObject = (Object*)pGameObject;
12389 pObjectQR = &objmgr.mGOQuestRelations;
12390 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12392 else
12393 return NULL;
12396 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12397 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12399 if (itr->second == nextQuestID)
12400 return objmgr.GetQuestTemplate(nextQuestID);
12403 return NULL;
12406 bool Player::CanSeeStartQuest( Quest const *pQuest )
12408 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12409 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12410 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12411 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12413 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12416 return false;
12419 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12421 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12422 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12423 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12424 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12425 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12426 && SatisfyQuestDay( pQuest, msg );
12429 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12431 if( !SatisfyQuestLog( msg ) )
12432 return false;
12434 uint32 srcitem = pQuest->GetSrcItemId();
12435 if( srcitem > 0 )
12437 uint32 count = pQuest->GetSrcItemCount();
12438 ItemPosCountVec dest;
12439 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12441 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12442 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12443 return true;
12444 else if( msg != EQUIP_ERR_OK )
12446 SendEquipError( msg, NULL, NULL );
12447 return false;
12450 return true;
12453 bool Player::CanCompleteQuest( uint32 quest_id )
12455 if( quest_id )
12457 QuestStatusData& q_status = mQuestStatus[quest_id];
12458 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12459 return false; // not allow re-complete quest
12461 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12463 if(!qInfo)
12464 return false;
12466 // auto complete quest
12467 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12468 return true;
12470 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12473 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12475 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12477 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12478 return false;
12482 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12484 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12486 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12487 continue;
12489 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12490 return false;
12494 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12495 return false;
12497 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12498 return false;
12500 if ( qInfo->GetRewOrReqMoney() < 0 )
12502 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12503 return false;
12506 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12507 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12508 return false;
12510 return true;
12513 return false;
12516 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12518 // Solve problem that player don't have the quest and try complete it.
12519 // if repeatable she must be able to complete event if player don't have it.
12520 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12521 if( !CanTakeQuest(pQuest, false) )
12522 return false;
12524 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12525 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12526 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12527 return false;
12529 if( !CanRewardQuest(pQuest, false) )
12530 return false;
12532 return true;
12535 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12537 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12538 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12539 return false;
12541 // daily quest can't be rewarded (25 daily quest already completed)
12542 if(!SatisfyQuestDay(pQuest,true))
12543 return false;
12545 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12546 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12547 return false;
12549 // prevent receive reward with quest items in bank
12550 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12552 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12554 if( pQuest->ReqItemCount[i]!= 0 &&
12555 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12557 if(msg)
12558 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12559 return false;
12564 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12565 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12566 return false;
12568 return true;
12571 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12573 // prevent receive reward with quest items in bank or for not completed quest
12574 if(!CanRewardQuest(pQuest,msg))
12575 return false;
12577 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12579 if( pQuest->RewChoiceItemId[reward] )
12581 ItemPosCountVec dest;
12582 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12583 if( res != EQUIP_ERR_OK )
12585 SendEquipError( res, NULL, NULL );
12586 return false;
12591 if ( pQuest->GetRewItemsCount() > 0 )
12593 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12595 if( pQuest->RewItemId[i] )
12597 ItemPosCountVec dest;
12598 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12599 if( res != EQUIP_ERR_OK )
12601 SendEquipError( res, NULL, NULL );
12602 return false;
12608 return true;
12611 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12613 uint16 log_slot = FindQuestSlot( 0 );
12614 assert(log_slot < MAX_QUEST_LOG_SIZE);
12616 uint32 quest_id = pQuest->GetQuestId();
12618 // if not exist then created with set uState==NEW and rewarded=false
12619 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12620 if (questStatusData.uState != QUEST_NEW)
12621 questStatusData.uState = QUEST_CHANGED;
12623 // check for repeatable quests status reset
12624 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12625 questStatusData.m_explored = false;
12627 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12629 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12630 questStatusData.m_itemcount[i] = 0;
12633 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12635 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12636 questStatusData.m_creatureOrGOcount[i] = 0;
12639 GiveQuestSourceItem( pQuest );
12640 AdjustQuestReqItemCount( pQuest );
12642 if( pQuest->GetRepObjectiveFaction() )
12643 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
12645 uint32 qtime = 0;
12646 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12648 uint32 limittime = pQuest->GetLimitTime();
12650 // shared timed quest
12651 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12652 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
12654 AddTimedQuest( quest_id );
12655 questStatusData.m_timer = limittime * 1000;
12656 qtime = static_cast<uint32>(time(NULL)) + limittime;
12658 else
12659 questStatusData.m_timer = 0;
12661 SetQuestSlot(log_slot, quest_id, qtime);
12663 //starting initial quest script
12664 if(questGiver && pQuest->GetQuestStartScript()!=0)
12665 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12667 UpdateForQuestsGO();
12670 void Player::CompleteQuest( uint32 quest_id )
12672 if( quest_id )
12674 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12676 uint16 log_slot = FindQuestSlot( quest_id );
12677 if( log_slot < MAX_QUEST_LOG_SIZE)
12678 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12680 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12682 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12683 RewardQuest(qInfo,0,this,false);
12684 else
12685 SendQuestComplete( quest_id );
12690 void Player::IncompleteQuest( uint32 quest_id )
12692 if( quest_id )
12694 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12696 uint16 log_slot = FindQuestSlot( quest_id );
12697 if( log_slot < MAX_QUEST_LOG_SIZE)
12698 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12702 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12704 uint32 quest_id = pQuest->GetQuestId();
12706 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12708 if ( pQuest->ReqItemId[i] )
12709 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12712 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12713 // SetTimedQuest( 0 );
12714 m_timedquests.erase(pQuest->GetQuestId());
12716 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12718 if( pQuest->RewChoiceItemId[reward] )
12720 ItemPosCountVec dest;
12721 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12723 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12724 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12729 if ( pQuest->GetRewItemsCount() > 0 )
12731 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12733 if( pQuest->RewItemId[i] )
12735 ItemPosCountVec dest;
12736 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12738 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12739 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12745 RewardReputation( pQuest );
12747 if( pQuest->GetRewSpellCast() > 0 )
12748 CastSpell( this, pQuest->GetRewSpellCast(), true);
12749 else if( pQuest->GetRewSpell() > 0)
12750 CastSpell( this, pQuest->GetRewSpell(), true);
12752 uint16 log_slot = FindQuestSlot( quest_id );
12753 if( log_slot < MAX_QUEST_LOG_SIZE)
12754 SetQuestSlot(log_slot,0);
12756 QuestStatusData& q_status = mQuestStatus[quest_id];
12758 // Not give XP in case already completed once repeatable quest
12759 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12761 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12762 GiveXP( XP , NULL );
12763 else
12764 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12766 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12767 ModifyMoney( pQuest->GetRewOrReqMoney() );
12769 // honor reward
12770 if(pQuest->GetRewHonorableKills())
12771 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12773 // title reward
12774 if(pQuest->GetCharTitleId())
12776 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12777 SetTitle(titleEntry);
12780 if(pQuest->GetBonusTalents())
12782 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12783 InitTalentForLevel();
12786 // Send reward mail
12787 if(pQuest->GetRewMailTemplateId())
12789 MailMessageType mailType;
12790 uint32 senderGuidOrEntry;
12791 switch(questGiver->GetTypeId())
12793 case TYPEID_UNIT:
12794 mailType = MAIL_CREATURE;
12795 senderGuidOrEntry = questGiver->GetEntry();
12796 break;
12797 case TYPEID_GAMEOBJECT:
12798 mailType = MAIL_GAMEOBJECT;
12799 senderGuidOrEntry = questGiver->GetEntry();
12800 break;
12801 case TYPEID_ITEM:
12802 mailType = MAIL_ITEM;
12803 senderGuidOrEntry = questGiver->GetEntry();
12804 break;
12805 case TYPEID_PLAYER:
12806 mailType = MAIL_NORMAL;
12807 senderGuidOrEntry = questGiver->GetGUIDLow();
12808 break;
12809 default:
12810 mailType = MAIL_NORMAL;
12811 senderGuidOrEntry = GetGUIDLow();
12812 break;
12815 Loot questMailLoot;
12817 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this);
12819 // fill mail
12820 MailItemsInfo mi; // item list preparing
12822 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.items.size(); ++i)
12824 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12826 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12828 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12829 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12834 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.quest_items.size(); ++i)
12836 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i+questMailLoot.items.size(),this))
12838 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12840 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12841 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12846 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12849 if(pQuest->IsDaily())
12851 SetDailyQuestStatus(quest_id);
12852 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12855 if ( !pQuest->IsRepeatable() )
12856 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12857 else
12858 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12860 q_status.m_rewarded = true;
12862 if(announce)
12863 SendQuestReward( pQuest, XP, questGiver );
12865 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12866 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12867 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST);
12870 void Player::FailQuest( uint32 quest_id )
12872 if( quest_id )
12874 IncompleteQuest( quest_id );
12876 uint16 log_slot = FindQuestSlot( quest_id );
12877 if( log_slot < MAX_QUEST_LOG_SIZE)
12879 SetQuestSlotTimer(log_slot, 1 );
12880 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12882 SendQuestFailed( quest_id );
12886 void Player::FailTimedQuest( uint32 quest_id )
12888 if( quest_id )
12890 QuestStatusData& q_status = mQuestStatus[quest_id];
12892 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12893 q_status.m_timer = 0;
12895 IncompleteQuest( quest_id );
12897 uint16 log_slot = FindQuestSlot( quest_id );
12898 if( log_slot < MAX_QUEST_LOG_SIZE)
12900 SetQuestSlotTimer(log_slot, 1 );
12901 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12903 SendQuestTimerFailed( quest_id );
12907 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12909 int32 zoneOrSort = qInfo->GetZoneOrSort();
12910 int32 skillOrClass = qInfo->GetSkillOrClass();
12912 // skip zone zoneOrSort and 0 case skillOrClass
12913 if( zoneOrSort >= 0 && skillOrClass == 0 )
12914 return true;
12916 int32 questSort = -zoneOrSort;
12917 uint8 reqSortClass = ClassByQuestSort(questSort);
12919 // check class sort cases in zoneOrSort
12920 if( reqSortClass != 0 && getClass() != reqSortClass)
12922 if( msg )
12923 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12924 return false;
12927 // check class
12928 if( skillOrClass < 0 )
12930 uint8 reqClass = -int32(skillOrClass);
12931 if(getClass() != reqClass)
12933 if( msg )
12934 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12935 return false;
12938 // check skill
12939 else if( skillOrClass > 0 )
12941 uint32 reqSkill = skillOrClass;
12942 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12944 if( msg )
12945 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12946 return false;
12950 return true;
12953 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12955 if( getLevel() < qInfo->GetMinLevel() )
12957 if( msg )
12958 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12959 return false;
12961 return true;
12964 bool Player::SatisfyQuestLog( bool msg )
12966 // exist free slot
12967 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12968 return true;
12970 if( msg )
12972 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12973 GetSession()->SendPacket( &data );
12974 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12976 return false;
12979 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12981 // No previous quest (might be first quest in a series)
12982 if( qInfo->prevQuests.empty())
12983 return true;
12985 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12987 uint32 prevId = abs(*iter);
12989 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12990 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12992 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12994 // If any of the positive previous quests completed, return true
12995 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12997 // skip one-from-all exclusive group
12998 if(qPrevInfo->GetExclusiveGroup() >= 0)
12999 return true;
13001 // each-from-all exclusive group ( < 0)
13002 // can be start if only all quests in prev quest exclusive group completed and rewarded
13003 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13004 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13006 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13008 for(; iter != end; ++iter)
13010 uint32 exclude_Id = iter->second;
13012 // skip checked quest id, only state of other quests in group is interesting
13013 if(exclude_Id == prevId)
13014 continue;
13016 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13018 // alternative quest from group also must be completed and rewarded(reported)
13019 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
13021 if( msg )
13022 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13023 return false;
13026 return true;
13028 // If any of the negative previous quests active, return true
13029 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13030 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
13032 // skip one-from-all exclusive group
13033 if(qPrevInfo->GetExclusiveGroup() >= 0)
13034 return true;
13036 // each-from-all exclusive group ( < 0)
13037 // can be start if only all quests in prev quest exclusive group active
13038 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13039 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13041 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13043 for(; iter != end; ++iter)
13045 uint32 exclude_Id = iter->second;
13047 // skip checked quest id, only state of other quests in group is interesting
13048 if(exclude_Id == prevId)
13049 continue;
13051 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13053 // alternative quest from group also must be active
13054 if( i_exstatus == mQuestStatus.end() ||
13055 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
13056 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
13058 if( msg )
13059 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13060 return false;
13063 return true;
13068 // Has only positive prev. quests in non-rewarded state
13069 // and negative prev. quests in non-active state
13070 if( msg )
13071 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13073 return false;
13076 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
13078 uint32 reqraces = qInfo->GetRequiredRaces();
13079 if ( reqraces == 0 )
13080 return true;
13081 if( (reqraces & getRaceMask()) == 0 )
13083 if( msg )
13084 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13085 return false;
13087 return true;
13090 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13092 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13093 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13095 if( msg )
13096 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13097 return false;
13100 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13101 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13103 if( msg )
13104 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13105 return false;
13108 return true;
13111 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13113 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13114 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13116 if( msg )
13117 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13118 return false;
13120 return true;
13123 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
13125 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
13127 if( msg )
13128 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
13129 return false;
13131 return true;
13134 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13136 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13137 if(qInfo->GetExclusiveGroup() <= 0)
13138 return true;
13140 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13141 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13143 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13145 for(; iter != end; ++iter)
13147 uint32 exclude_Id = iter->second;
13149 // skip checked quest id, only state of other quests in group is interesting
13150 if(exclude_Id == qInfo->GetQuestId())
13151 continue;
13153 // not allow have daily quest if daily quest from exclusive group already recently completed
13154 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
13155 if( !SatisfyQuestDay(Nquest, false) )
13157 if( msg )
13158 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13159 return false;
13162 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13164 // alternative quest already started or completed
13165 if( i_exstatus != mQuestStatus.end()
13166 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13168 if( msg )
13169 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13170 return false;
13173 return true;
13176 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13178 if(!qInfo->GetNextQuestInChain())
13179 return true;
13181 // next quest in chain already started or completed
13182 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13183 if( itr != mQuestStatus.end()
13184 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13186 if( msg )
13187 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13188 return false;
13191 // check for all quests further up the chain
13192 // only necessary if there are quest chains with more than one quest that can be skipped
13193 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13194 return true;
13197 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13199 // No previous quest in chain
13200 if( qInfo->prevChainQuests.empty())
13201 return true;
13203 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13205 uint32 prevId = *iter;
13207 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
13209 if( i_prevstatus != mQuestStatus.end() )
13211 // If any of the previous quests in chain active, return false
13212 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13213 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13215 if( msg )
13216 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13217 return false;
13221 // check for all quests further down the chain
13222 // only necessary if there are quest chains with more than one quest that can be skipped
13223 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13224 // return false;
13227 // No previous quest in chain active
13228 return true;
13231 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13233 if(!qInfo->IsDaily())
13234 return true;
13236 bool have_slot = false;
13237 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13239 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13240 if(qInfo->GetQuestId()==id)
13241 return false;
13243 if(!id)
13244 have_slot = true;
13247 if(!have_slot)
13249 if( msg )
13250 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13251 return false;
13254 return true;
13257 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13259 uint32 srcitem = pQuest->GetSrcItemId();
13260 if( srcitem > 0 )
13262 uint32 count = pQuest->GetSrcItemCount();
13263 if( count <= 0 )
13264 count = 1;
13266 ItemPosCountVec dest;
13267 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13268 if( msg == EQUIP_ERR_OK )
13270 Item * item = StoreNewItem(dest, srcitem, true);
13271 SendNewItem(item, count, true, false);
13272 return true;
13274 // player already have max amount required item, just report success
13275 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13276 return true;
13277 else
13278 SendEquipError( msg, NULL, NULL );
13279 return false;
13282 return true;
13285 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13287 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13288 if( qInfo )
13290 uint32 srcitem = qInfo->GetSrcItemId();
13291 if( srcitem > 0 )
13293 uint32 count = qInfo->GetSrcItemCount();
13294 if( count <= 0 )
13295 count = 1;
13297 // exist one case when destroy source quest item not possible:
13298 // non un-equippable item (equipped non-empty bag, for example)
13299 uint8 res = CanUnequipItems(srcitem,count);
13300 if(res != EQUIP_ERR_OK)
13302 if(msg)
13303 SendEquipError( res, NULL, NULL );
13304 return false;
13307 DestroyItemCount(srcitem, count, true, true);
13310 return true;
13313 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13315 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13316 if( qInfo )
13318 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13319 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13320 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13321 && !qInfo->IsRepeatable() )
13322 return itr->second.m_rewarded;
13324 return false;
13326 return false;
13329 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13331 if( quest_id )
13333 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13334 if( itr != mQuestStatus.end() )
13335 return itr->second.m_status;
13337 return QUEST_STATUS_NONE;
13340 bool Player::CanShareQuest(uint32 quest_id) const
13342 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13343 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13345 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13346 if( itr != mQuestStatus.end() )
13347 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13349 return false;
13352 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13354 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13355 if( qInfo )
13357 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13359 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13360 m_timedquests.erase(qInfo->GetQuestId());
13363 QuestStatusData& q_status = mQuestStatus[quest_id];
13365 q_status.m_status = status;
13366 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13369 UpdateForQuestsGO();
13372 // not used in MaNGOS, but used in scripting code
13373 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13375 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13376 if( !qInfo )
13377 return 0;
13379 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13380 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13381 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13383 return 0;
13386 void Player::AdjustQuestReqItemCount( Quest const* pQuest )
13388 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13390 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
13392 uint32 reqitemcount = pQuest->ReqItemCount[i];
13393 if( reqitemcount != 0 )
13395 uint32 quest_id = pQuest->GetQuestId();
13396 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13398 QuestStatusData& q_status = mQuestStatus[quest_id];
13399 q_status.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13400 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13406 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13408 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13409 if ( GetQuestSlotQuestId(i) == quest_id )
13410 return i;
13412 return MAX_QUEST_LOG_SIZE;
13415 void Player::AreaExploredOrEventHappens( uint32 questId )
13417 if( questId )
13419 uint16 log_slot = FindQuestSlot( questId );
13420 if( log_slot < MAX_QUEST_LOG_SIZE)
13422 QuestStatusData& q_status = mQuestStatus[questId];
13424 if(!q_status.m_explored)
13426 q_status.m_explored = true;
13427 if (q_status.uState != QUEST_NEW)
13428 q_status.uState = QUEST_CHANGED;
13431 if( CanCompleteQuest( questId ) )
13432 CompleteQuest( questId );
13436 //not used in mangosd, function for external script library
13437 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13439 if( Group *pGroup = GetGroup() )
13441 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13443 Player *pGroupGuy = itr->getSource();
13445 // for any leave or dead (with not released body) group member at appropriate distance
13446 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13447 pGroupGuy->AreaExploredOrEventHappens(questId);
13450 else
13451 AreaExploredOrEventHappens(questId);
13454 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13456 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13458 uint32 questid = GetQuestSlotQuestId(i);
13459 if ( questid == 0 )
13460 continue;
13462 QuestStatusData& q_status = mQuestStatus[questid];
13464 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13465 continue;
13467 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13468 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13469 continue;
13471 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13473 uint32 reqitem = qInfo->ReqItemId[j];
13474 if ( reqitem == entry )
13476 uint32 reqitemcount = qInfo->ReqItemCount[j];
13477 uint32 curitemcount = q_status.m_itemcount[j];
13478 if ( curitemcount < reqitemcount )
13480 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13481 q_status.m_itemcount[j] += additemcount;
13482 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13484 SendQuestUpdateAddItem( qInfo, j, additemcount );
13486 if ( CanCompleteQuest( questid ) )
13487 CompleteQuest( questid );
13488 return;
13492 UpdateForQuestsGO();
13493 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
13496 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13498 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13500 uint32 questid = GetQuestSlotQuestId(i);
13501 if(!questid)
13502 continue;
13503 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13504 if ( !qInfo )
13505 continue;
13506 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13507 continue;
13509 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13511 uint32 reqitem = qInfo->ReqItemId[j];
13512 if ( reqitem == entry )
13514 QuestStatusData& q_status = mQuestStatus[questid];
13516 uint32 reqitemcount = qInfo->ReqItemCount[j];
13517 uint32 curitemcount;
13518 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13519 curitemcount = q_status.m_itemcount[j];
13520 else
13521 curitemcount = GetItemCount(entry,true);
13522 if ( curitemcount < reqitemcount + count )
13524 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13525 q_status.m_itemcount[j] = curitemcount - remitemcount;
13526 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13528 IncompleteQuest( questid );
13530 return;
13534 UpdateForQuestsGO();
13537 void Player::KilledMonster( uint32 entry, uint64 guid )
13539 uint32 addkillcount = 1;
13540 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13541 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13543 uint32 questid = GetQuestSlotQuestId(i);
13544 if(!questid)
13545 continue;
13547 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13548 if( !qInfo )
13549 continue;
13550 // just if !ingroup || !noraidgroup || raidgroup
13551 QuestStatusData& q_status = mQuestStatus[questid];
13552 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13554 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13556 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13558 // skip GO activate objective or none
13559 if(qInfo->ReqCreatureOrGOId[j] <=0)
13560 continue;
13562 // skip Cast at creature objective
13563 if(qInfo->ReqSpell[j] !=0 )
13564 continue;
13566 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13568 if ( reqkill == entry )
13570 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13571 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13572 if ( curkillcount < reqkillcount )
13574 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13575 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13577 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13579 if ( CanCompleteQuest( questid ) )
13580 CompleteQuest( questid );
13582 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13583 continue;
13591 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13593 bool isCreature = IS_CREATURE_GUID(guid);
13595 uint32 addCastCount = 1;
13596 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13598 uint32 questid = GetQuestSlotQuestId(i);
13599 if(!questid)
13600 continue;
13602 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13603 if ( !qInfo )
13604 continue;
13606 QuestStatusData& q_status = mQuestStatus[questid];
13608 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13610 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13612 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13614 // skip kill creature objective (0) or wrong spell casts
13615 if(qInfo->ReqSpell[j] != spell_id )
13616 continue;
13618 uint32 reqTarget = 0;
13620 if(isCreature)
13622 // creature activate objectives
13623 if(qInfo->ReqCreatureOrGOId[j] > 0)
13624 // checked at quest_template loading
13625 reqTarget = qInfo->ReqCreatureOrGOId[j];
13627 else
13629 // GO activate objective
13630 if(qInfo->ReqCreatureOrGOId[j] < 0)
13631 // checked at quest_template loading
13632 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13635 // other not this creature/GO related objectives
13636 if( reqTarget != entry )
13637 continue;
13639 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13640 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13641 if ( curCastCount < reqCastCount )
13643 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13644 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13646 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13649 if ( CanCompleteQuest( questid ) )
13650 CompleteQuest( questid );
13652 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13653 break;
13660 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13662 uint32 addTalkCount = 1;
13663 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13665 uint32 questid = GetQuestSlotQuestId(i);
13666 if(!questid)
13667 continue;
13669 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13670 if ( !qInfo )
13671 continue;
13673 QuestStatusData& q_status = mQuestStatus[questid];
13675 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13677 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13679 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13681 // skip spell casts and Gameobject objectives
13682 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13683 continue;
13685 uint32 reqTarget = 0;
13687 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13688 // checked at quest_template loading
13689 reqTarget = qInfo->ReqCreatureOrGOId[j];
13690 else
13691 continue;
13693 if ( reqTarget == entry )
13695 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13696 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13697 if ( curTalkCount < reqTalkCount )
13699 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13700 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13702 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13704 if ( CanCompleteQuest( questid ) )
13705 CompleteQuest( questid );
13707 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13708 continue;
13716 void Player::MoneyChanged( uint32 count )
13718 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13720 uint32 questid = GetQuestSlotQuestId(i);
13721 if (!questid)
13722 continue;
13724 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13725 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13727 QuestStatusData& q_status = mQuestStatus[questid];
13729 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13731 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13733 if ( CanCompleteQuest( questid ) )
13734 CompleteQuest( questid );
13737 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13739 if(int32(count) < -qInfo->GetRewOrReqMoney())
13740 IncompleteQuest( questid );
13746 bool Player::HasQuestForItem( uint32 itemid ) const
13748 for( QuestStatusMap::const_iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
13750 QuestStatusData const& q_status = i->second;
13752 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13754 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
13755 if(!qinfo)
13756 continue;
13758 // hide quest if player is in raid-group and quest is no raid quest
13759 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13760 continue;
13762 // There should be no mixed ReqItem/ReqSource drop
13763 // This part for ReqItem drop
13764 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13766 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13767 return true;
13769 // This part - for ReqSource
13770 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13772 // examined item is a source item
13773 if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
13775 uint32 idx = qinfo->ReqSourceRef[j]-1;
13777 // total count of created ReqItems and SourceItems is less than ReqItemCount
13778 if(qinfo->ReqItemId[idx] != 0 &&
13779 q_status.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
13780 return true;
13782 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13783 if (qinfo->ReqCreatureOrGOId[idx] != 0)
13785 if(q_status.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
13786 return true;
13788 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13789 else if(qinfo->ReqSpell[idx] != 0)
13791 // not casted and need more reagents/item for use.
13792 if(!q_status.m_explored && GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13793 return true;
13799 return false;
13802 void Player::SendQuestComplete( uint32 quest_id )
13804 if( quest_id )
13806 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13807 data << uint32(quest_id);
13808 GetSession()->SendPacket( &data );
13809 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13813 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13815 uint32 questid = pQuest->GetQuestId();
13816 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13817 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13818 data << uint32(questid);
13820 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13822 data << uint32(XP);
13823 data << uint32(pQuest->GetRewOrReqMoney());
13825 else
13827 data << uint32(0);
13828 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13831 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13832 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13833 GetSession()->SendPacket( &data );
13835 if (pQuest->GetQuestCompleteScript() != 0)
13836 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13839 void Player::SendQuestFailed( uint32 quest_id )
13841 if( quest_id )
13843 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13844 data << quest_id;
13845 data << uint32(0); // failed reason (4 for inventory is full)
13846 GetSession()->SendPacket( &data );
13847 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13851 void Player::SendQuestTimerFailed( uint32 quest_id )
13853 if( quest_id )
13855 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13856 data << quest_id;
13857 GetSession()->SendPacket( &data );
13858 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13862 void Player::SendCanTakeQuestResponse( uint32 msg )
13864 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13865 data << uint32(msg);
13866 GetSession()->SendPacket( &data );
13867 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13870 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13872 if( pPlayer )
13874 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13875 data << uint64(pPlayer->GetGUID());
13876 data << uint8(msg); // valid values: 0-8
13877 GetSession()->SendPacket( &data );
13878 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13882 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13884 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13885 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13886 //data << pQuest->ReqItemId[item_idx];
13887 //data << count;
13888 GetSession()->SendPacket( &data );
13891 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13893 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13895 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13896 if (entry < 0)
13897 // client expected gameobject template id in form (id|0x80000000)
13898 entry = (-entry) | 0x80000000;
13900 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13901 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13902 data << uint32(pQuest->GetQuestId());
13903 data << uint32(entry);
13904 data << uint32(old_count + add_count);
13905 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13906 data << uint64(guid);
13907 GetSession()->SendPacket(&data);
13909 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13910 if( log_slot < MAX_QUEST_LOG_SIZE)
13911 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13914 /*********************************************************/
13915 /*** LOAD SYSTEM ***/
13916 /*********************************************************/
13918 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13920 bool delete_result = true;
13921 if(!result)
13923 // 0 1 2 3 4 5 6 7 8 9
13924 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13925 if(!result) return false;
13927 else delete_result = false;
13929 Field *fields = result->Fetch();
13931 if(!LoadValues( fields[1].GetString()))
13933 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13934 if(delete_result) delete result;
13935 return false;
13938 // overwrite possible wrong/corrupted guid
13939 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13941 m_name = fields[2].GetCppString();
13943 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13944 SetMapId(fields[6].GetUInt32());
13945 // the instance id is not needed at character enum
13947 m_Played_time[0] = fields[7].GetUInt32();
13948 m_Played_time[1] = fields[8].GetUInt32();
13950 m_atLoginFlags = fields[9].GetUInt32();
13952 // I don't see these used anywhere ..
13953 /*_LoadGroup();
13955 _LoadBoundInstances();*/
13957 if (delete_result) delete result;
13959 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13960 m_items[i] = NULL;
13962 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13963 m_deathState = DEAD;
13965 return true;
13968 void Player::_LoadDeclinedNames(QueryResult* result)
13970 if(!result)
13971 return;
13973 if(m_declinedname)
13974 delete m_declinedname;
13976 m_declinedname = new DeclinedName;
13977 Field *fields = result->Fetch();
13978 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13979 m_declinedname->name[i] = fields[i].GetCppString();
13981 delete result;
13984 void Player::_LoadArenaTeamInfo(QueryResult *result)
13986 // arenateamid, played_week, played_season, personal_rating
13987 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13988 if (!result)
13989 return;
13993 Field *fields = result->Fetch();
13995 uint32 arenateamid = fields[0].GetUInt32();
13996 uint32 played_week = fields[1].GetUInt32();
13997 uint32 played_season = fields[2].GetUInt32();
13998 uint32 personal_rating = fields[3].GetUInt32();
14000 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
14001 if(!aTeam)
14003 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
14004 continue;
14006 uint8 arenaSlot = aTeam->GetSlot();
14008 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
14009 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
14010 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
14011 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
14012 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
14013 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
14015 }while (result->NextRow());
14016 delete result;
14019 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
14021 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
14022 if(!result)
14023 return false;
14025 Field *fields = result->Fetch();
14027 x = fields[0].GetFloat();
14028 y = fields[1].GetFloat();
14029 z = fields[2].GetFloat();
14030 o = fields[3].GetFloat();
14031 mapid = fields[4].GetUInt32();
14032 in_flight = !fields[5].GetCppString().empty();
14034 delete result;
14035 return true;
14038 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
14040 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
14041 if( !result )
14042 return false;
14044 Field *fields = result->Fetch();
14046 data = StrSplit(fields[0].GetCppString(), " ");
14048 delete result;
14050 return true;
14053 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
14055 if(index >= data.size())
14056 return 0;
14058 return (uint32)atoi(data[index].c_str());
14061 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
14063 float result;
14064 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
14065 memcpy(&result, &temp, sizeof(result));
14067 return result;
14070 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14072 Tokens data;
14073 if(!LoadValuesArrayFromDB(data,guid))
14074 return 0;
14076 return GetUInt32ValueFromArray(data,index);
14079 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14081 float result;
14082 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14083 memcpy(&result, &temp, sizeof(result));
14085 return result;
14088 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14090 //// 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
14091 //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 FROM characters WHERE guid = '%u'", guid);
14092 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14094 if(!result)
14096 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14097 return false;
14100 Field *fields = result->Fetch();
14102 uint32 dbAccountId = fields[1].GetUInt32();
14104 // check if the character's account in the db and the logged in account match.
14105 // player should be able to load/delete character only with correct account!
14106 if( dbAccountId != GetSession()->GetAccountId() )
14108 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14109 delete result;
14110 return false;
14113 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14115 m_name = fields[3].GetCppString();
14117 // check name limitations
14118 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
14120 delete result;
14121 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14122 return false;
14125 if(!LoadValues( fields[2].GetString()))
14127 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
14128 delete result;
14129 return false;
14132 // overwrite possible wrong/corrupted guid
14133 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14135 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14136 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14138 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
14139 SetVisibleItemSlot(slot,NULL);
14141 if (m_items[slot])
14143 delete m_items[slot];
14144 m_items[slot] = NULL;
14148 // update money limits
14149 if(GetMoney() > MAX_MONEY_AMOUNT)
14150 SetMoney(MAX_MONEY_AMOUNT);
14152 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14153 outDebugValues();
14155 m_race = fields[4].GetUInt8();
14156 //Need to call it to initialize m_team (m_team can be calculated from m_race)
14157 //Other way is to saves m_team into characters table.
14158 setFactionForRace(m_race);
14159 SetCharm(0);
14161 m_class = fields[5].GetUInt8();
14163 PlayerInfo const *info = objmgr.GetPlayerInfo(m_race, m_class);
14164 if(!info)
14166 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
14167 delete result;
14168 return false;
14171 InitPrimaryProffesions(); // to max set before any spell loaded
14173 uint32 transGUID = fields[24].GetUInt32();
14174 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
14175 SetMapId(fields[9].GetUInt32());
14176 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
14178 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14180 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14182 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
14183 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
14184 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14186 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14188 // check arena teams integrity
14189 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14191 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14192 if(!arena_team_id)
14193 continue;
14195 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
14196 if(at->HaveMember(GetGUID()))
14197 continue;
14199 // arena team not exist or not member, cleanup fields
14200 for(int j =0; j < 6; ++j)
14201 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
14204 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14206 if(!IsPositionValid())
14208 sLog.outError("ERROR: 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());
14210 SetMapId(info->mapId);
14211 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
14213 transGUID = 0;
14215 m_movementInfo.t_x = 0.0f;
14216 m_movementInfo.t_y = 0.0f;
14217 m_movementInfo.t_z = 0.0f;
14218 m_movementInfo.t_o = 0.0f;
14221 // load the player's map here if it's not already loaded
14222 Map *map = GetMap();
14223 // since the player may not be bound to the map yet, make sure subsequent
14224 // getmap calls won't create new maps
14225 SetInstanceId(map->GetInstanceId());
14227 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14228 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14230 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14231 if(at)
14232 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14233 else
14234 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());
14237 SaveRecallPosition();
14239 if (transGUID != 0)
14241 m_movementInfo.t_x = fields[20].GetFloat();
14242 m_movementInfo.t_y = fields[21].GetFloat();
14243 m_movementInfo.t_z = fields[22].GetFloat();
14244 m_movementInfo.t_o = fields[23].GetFloat();
14246 if( !MaNGOS::IsValidMapCoord(
14247 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14248 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14249 // transport size limited
14250 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14252 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14253 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14254 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14256 SetMapId(info->mapId);
14257 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
14259 m_movementInfo.t_x = 0.0f;
14260 m_movementInfo.t_y = 0.0f;
14261 m_movementInfo.t_z = 0.0f;
14262 m_movementInfo.t_o = 0.0f;
14264 transGUID = 0;
14268 if (transGUID != 0)
14270 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14272 if( (*iter)->GetGUIDLow() == transGUID)
14274 m_transport = *iter;
14275 m_transport->AddPassenger(this);
14276 SetMapId(m_transport->GetMapId());
14277 break;
14281 if(!m_transport)
14283 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
14284 guid,transGUID);
14286 SetMapId(info->mapId);
14287 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
14289 m_movementInfo.t_x = 0.0f;
14290 m_movementInfo.t_y = 0.0f;
14291 m_movementInfo.t_z = 0.0f;
14292 m_movementInfo.t_o = 0.0f;
14294 transGUID = 0;
14298 time_t now = time(NULL);
14299 time_t logoutTime = time_t(fields[16].GetUInt64());
14301 // since last logout (in seconds)
14302 uint64 time_diff = uint64(now - logoutTime);
14304 // set value, including drunk invisibility detection
14305 // calculate sobering. after 15 minutes logged out, the player will be sober again
14306 float soberFactor;
14307 if(time_diff > 15*MINUTE)
14308 soberFactor = 0;
14309 else
14310 soberFactor = 1-time_diff/(15.0f*MINUTE);
14311 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14312 SetDrunkValue(newDrunkenValue);
14314 m_rest_bonus = fields[15].GetFloat();
14315 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14316 float bubble0 = 0.031;
14317 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14318 float bubble1 = 0.125;
14320 if((int32)fields[16].GetUInt32() > 0)
14322 float bubble = fields[17].GetUInt32() > 0
14323 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14324 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14326 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14329 m_cinematic = fields[12].GetUInt32();
14330 m_Played_time[0]= fields[13].GetUInt32();
14331 m_Played_time[1]= fields[14].GetUInt32();
14333 m_resetTalentsCost = fields[18].GetUInt32();
14334 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14336 // reserve some flags
14337 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14339 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14340 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14342 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14344 uint32 extraflags = fields[25].GetUInt32();
14346 m_stableSlots = fields[26].GetUInt32();
14347 if(m_stableSlots > 4)
14349 sLog.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots));
14350 m_stableSlots = 4;
14353 m_atLoginFlags = fields[27].GetUInt32();
14355 // Honor system
14356 // Update Honor kills data
14357 m_lastHonorUpdateTime = logoutTime;
14358 UpdateHonorFields();
14360 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14361 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14362 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14364 std::string taxi_nodes = fields[31].GetCppString();
14366 delete result;
14368 // clear channel spell data (if saved at channel spell casting)
14369 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14370 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14372 // clear charm/summon related fields
14373 SetCharm(NULL);
14374 SetPet(NULL);
14375 SetCharmerGUID(0);
14376 SetOwnerGUID(0);
14377 SetCreatorGUID(0);
14379 // reset some aura modifiers before aura apply
14380 SetFarSightGUID(0);
14381 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14382 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14384 // reset skill modifiers and set correct unlearn flags
14385 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
14387 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
14389 // set correct unlearn bit
14390 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
14391 if(!id) continue;
14393 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
14394 if(!pSkill) continue;
14396 // enable unlearn button for primary professions only
14397 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
14398 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
14399 else
14400 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
14403 // make sure the unit is considered out of combat for proper loading
14404 ClearInCombat();
14406 // make sure the unit is considered not in duel for proper loading
14407 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14408 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14410 // remember loaded power/health values to restore after stats initialization and modifier applying
14411 uint32 savedHealth = GetHealth();
14412 uint32 savedPower[MAX_POWERS];
14413 for(uint32 i = 0; i < MAX_POWERS; ++i)
14414 savedPower[i] = GetPower(Powers(i));
14416 // reset stats before loading any modifiers
14417 InitStatsForLevel();
14418 InitTaxiNodesForLevel();
14419 InitGlyphsForLevel();
14420 InitRunes();
14422 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14424 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14425 //_LoadMail();
14427 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14428 _LoadGlyphAuras();
14430 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14431 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14432 m_deathState = DEAD;
14434 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14436 // after spell load, learn rewarded spell if need also
14437 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14438 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14440 // after spell and quest load
14441 InitTalentForLevel();
14442 learnSkillRewardedSpells();
14443 learnDefaultSpells();
14445 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14447 // must be before inventory (some items required reputation check)
14448 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14450 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14452 // update items with duration and realtime
14453 UpdateItemDuration(time_diff, true);
14455 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14457 // unread mails and next delivery time, actual mails not loaded
14458 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14460 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14462 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14463 return false;
14465 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14466 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14467 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14469 if(!HasTitle(curTitle))
14470 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14473 // Not finish taxi flight path
14474 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14476 // problems with taxi path loading
14477 TaxiNodesEntry const* nodeEntry = NULL;
14478 if(uint32 node_id = m_taxi.GetTaxiSource())
14479 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14481 if(!nodeEntry) // don't know taxi start node, to homebind
14483 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14484 SetMapId(m_homebindMapId);
14485 Relocate( m_homebindX, m_homebindY, m_homebindZ,0.0f);
14486 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14488 else // have start node, to it
14490 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14491 SetMapId(nodeEntry->map_id);
14492 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14493 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14495 m_taxi.ClearTaxiDestinations();
14497 else if(uint32 node_id = m_taxi.GetTaxiSource())
14499 // save source node as recall coord to prevent recall and fall from sky
14500 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14501 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14502 m_recallMap = nodeEntry->map_id;
14503 m_recallX = nodeEntry->x;
14504 m_recallY = nodeEntry->y;
14505 m_recallZ = nodeEntry->z;
14507 // flight will started later
14510 // has to be called after last Relocate() in Player::LoadFromDB
14511 SetFallInformation(0, GetPositionZ());
14513 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14515 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14516 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14517 if(!isAlive())
14518 RemoveAllAurasOnDeath();
14520 //apply all stat bonuses from items and auras
14521 SetCanModifyStats(true);
14522 UpdateAllStats();
14524 // restore remembered power/health values (but not more max values)
14525 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14526 for(uint32 i = 0; i < MAX_POWERS; ++i)
14527 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14529 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14530 outDebugValues();
14532 // GM state
14533 if(GetSession()->GetSecurity() > SEC_PLAYER)
14535 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14537 default:
14538 case 0: break; // disable
14539 case 1: SetGameMaster(true); break; // enable
14540 case 2: // save state
14541 if(extraflags & PLAYER_EXTRA_GM_ON)
14542 SetGameMaster(true);
14543 break;
14546 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14548 default:
14549 case 0: break; // disable
14550 case 1: SetAcceptTicket(true); break; // enable
14551 case 2: // save state
14552 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14553 SetAcceptTicket(true);
14554 break;
14557 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14559 default:
14560 case 0: break; // disable
14561 case 1: SetGMChat(true); break; // enable
14562 case 2: // save state
14563 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14564 SetGMChat(true);
14565 break;
14568 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14570 default:
14571 case 0: break; // disable
14572 case 1: SetAcceptWhispers(true); break; // enable
14573 case 2: // save state
14574 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14575 SetAcceptWhispers(true);
14576 break;
14580 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14582 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14583 m_achievementMgr.CheckAllAchievementCriteria();
14584 return true;
14587 bool Player::isAllowedToLoot(Creature* creature)
14589 if(Player* recipient = creature->GetLootRecipient())
14591 if (recipient == this)
14592 return true;
14593 if( Group* otherGroup = recipient->GetGroup())
14595 Group* thisGroup = GetGroup();
14596 if(!thisGroup)
14597 return false;
14598 return thisGroup == otherGroup;
14600 return false;
14602 else
14603 // prevent other players from looting if the recipient got disconnected
14604 return !creature->hasLootRecipient();
14607 void Player::_LoadActions(QueryResult *result)
14609 m_actionButtons.clear();
14611 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14613 if(result)
14617 Field *fields = result->Fetch();
14619 uint8 button = fields[0].GetUInt8();
14621 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
14623 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14625 while( result->NextRow() );
14627 delete result;
14631 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14633 m_Auras.clear();
14634 for (int i = 0; i < TOTAL_AURAS; i++)
14635 m_modAuras[i].clear();
14637 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14639 if(result)
14643 Field *fields = result->Fetch();
14644 uint64 caster_guid = fields[0].GetUInt64();
14645 uint32 spellid = fields[1].GetUInt32();
14646 uint32 effindex = fields[2].GetUInt32();
14647 uint32 stackcount = fields[3].GetUInt32();
14648 int32 damage = (int32)fields[4].GetUInt32();
14649 int32 maxduration = (int32)fields[5].GetUInt32();
14650 int32 remaintime = (int32)fields[6].GetUInt32();
14651 int32 remaincharges = (int32)fields[7].GetUInt32();
14653 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14654 if(!spellproto)
14656 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14657 continue;
14660 if(effindex >= 3)
14662 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14663 continue;
14666 // negative effects should continue counting down after logout
14667 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14669 if(remaintime <= int32(timediff))
14670 continue;
14672 remaintime -= timediff;
14675 // prevent wrong values of remaincharges
14676 if(spellproto->procCharges)
14678 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14679 remaincharges = spellproto->procCharges;
14681 else
14682 remaincharges = 0;
14684 //do not load single target auras (unless they were cast by the player)
14685 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
14686 continue;
14688 for(uint32 i=0; i<stackcount; i++)
14690 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14691 if(!damage)
14692 damage = aura->GetModifier()->m_amount;
14693 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14694 AddAura(aura);
14695 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14698 while( result->NextRow() );
14700 delete result;
14703 if(m_class == CLASS_WARRIOR)
14704 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14707 void Player::_LoadGlyphAuras()
14709 for (uint8 i = 0; i <= MAX_GLYPH_SLOT_INDEX; ++i)
14711 if (uint32 glyph = GetGlyph(i))
14713 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14715 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14717 if(gp->TypeFlags == gs->TypeFlags)
14719 CastSpell(this, gp->SpellId, true);
14720 continue;
14722 else
14723 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14725 else
14726 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14728 else
14729 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14731 // On any error remove glyph
14732 SetGlyph(i, 0);
14737 void Player::LoadCorpse()
14739 if( isAlive() )
14741 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14743 else
14745 if(Corpse *corpse = GetCorpse())
14747 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14749 else
14751 //Prevent Dead Player login without corpse
14752 ResurrectPlayer(0.5f);
14757 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14759 //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());
14760 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14761 //NOTE: the "order by `bag`" is important because it makes sure
14762 //the bagMap is filled before items in the bags are loaded
14763 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14764 //expected to be equipped before offhand items (TODO: fixme)
14766 uint32 zone = GetZoneId();
14768 if (result)
14770 std::list<Item*> problematicItems;
14772 // prevent items from being added to the queue when stored
14773 m_itemUpdateQueueBlocked = true;
14776 Field *fields = result->Fetch();
14777 uint32 bag_guid = fields[1].GetUInt32();
14778 uint8 slot = fields[2].GetUInt8();
14779 uint32 item_guid = fields[3].GetUInt32();
14780 uint32 item_id = fields[4].GetUInt32();
14782 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14784 if(!proto)
14786 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14787 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14788 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14789 continue;
14792 Item *item = NewItemOrBag(proto);
14794 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14796 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14797 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14798 item->FSetState(ITEM_REMOVED);
14799 item->SaveToDB(); // it also deletes item object !
14800 continue;
14803 // not allow have in alive state item limited to another map/zone
14804 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14806 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14807 item->FSetState(ITEM_REMOVED);
14808 item->SaveToDB(); // it also deletes item object !
14809 continue;
14812 // "Conjured items disappear if you are logged out for more than 15 minutes"
14813 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14815 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14816 item->FSetState(ITEM_REMOVED);
14817 item->SaveToDB(); // it also deletes item object !
14818 continue;
14821 bool success = true;
14823 if (!bag_guid)
14825 // the item is not in a bag
14826 item->SetContainer( NULL );
14827 item->SetSlot(slot);
14829 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14831 ItemPosCountVec dest;
14832 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14833 item = StoreItem(dest, item, true);
14834 else
14835 success = false;
14837 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14839 uint16 dest;
14840 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14841 QuickEquipItem(dest, item);
14842 else
14843 success = false;
14845 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14847 ItemPosCountVec dest;
14848 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14849 item = BankItem(dest, item, true);
14850 else
14851 success = false;
14854 if(success)
14856 // store bags that may contain items in them
14857 if(item->IsBag() && IsBagPos(item->GetPos()))
14858 bagMap[item_guid] = (Bag*)item;
14861 else
14863 item->SetSlot(NULL_SLOT);
14864 // the item is in a bag, find the bag
14865 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14866 if(itr != bagMap.end())
14867 itr->second->StoreItem(slot, item, true );
14868 else
14869 success = false;
14872 // item's state may have changed after stored
14873 if (success)
14874 item->SetState(ITEM_UNCHANGED, this);
14875 else
14877 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);
14878 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14879 problematicItems.push_back(item);
14881 } while (result->NextRow());
14883 delete result;
14884 m_itemUpdateQueueBlocked = false;
14886 // send by mail problematic items
14887 while(!problematicItems.empty())
14889 // fill mail
14890 MailItemsInfo mi; // item list preparing
14892 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14894 Item* item = problematicItems.front();
14895 problematicItems.pop_front();
14897 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14900 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14902 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14905 //if(isAlive())
14906 _ApplyAllItemMods();
14909 // load mailed item which should receive current player
14910 void Player::_LoadMailedItems(Mail *mail)
14912 // data needs to be at first place for Item::LoadFromDB
14913 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);
14914 if(!result)
14915 return;
14919 Field *fields = result->Fetch();
14920 uint32 item_guid_low = fields[1].GetUInt32();
14921 uint32 item_template = fields[2].GetUInt32();
14923 mail->AddItem(item_guid_low, item_template);
14925 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14927 if(!proto)
14929 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);
14930 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14931 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14932 continue;
14935 Item *item = NewItemOrBag(proto);
14937 if(!item->LoadFromDB(item_guid_low, 0, result))
14939 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14940 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14941 item->FSetState(ITEM_REMOVED);
14942 item->SaveToDB(); // it also deletes item object !
14943 continue;
14946 AddMItem(item);
14947 } while (result->NextRow());
14949 delete result;
14952 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14954 //set a count of unread mails
14955 //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);
14956 if (resultUnread)
14958 Field *fieldMail = resultUnread->Fetch();
14959 unReadMails = fieldMail[0].GetUInt8();
14960 delete resultUnread;
14963 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14964 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14965 if (resultDelivery)
14967 Field *fieldMail = resultDelivery->Fetch();
14968 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14969 delete resultDelivery;
14973 void Player::_LoadMail()
14975 m_mail.clear();
14976 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14977 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());
14978 if(result)
14982 Field *fields = result->Fetch();
14983 Mail *m = new Mail;
14984 m->messageID = fields[0].GetUInt32();
14985 m->messageType = fields[1].GetUInt8();
14986 m->sender = fields[2].GetUInt32();
14987 m->receiver = fields[3].GetUInt32();
14988 m->subject = fields[4].GetCppString();
14989 m->itemTextId = fields[5].GetUInt32();
14990 bool has_items = fields[6].GetBool();
14991 m->expire_time = (time_t)fields[7].GetUInt64();
14992 m->deliver_time = (time_t)fields[8].GetUInt64();
14993 m->money = fields[9].GetUInt32();
14994 m->COD = fields[10].GetUInt32();
14995 m->checked = fields[11].GetUInt32();
14996 m->stationery = fields[12].GetUInt8();
14997 m->mailTemplateId = fields[13].GetInt16();
14999 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15001 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15002 m->mailTemplateId = 0;
15005 m->state = MAIL_STATE_UNCHANGED;
15007 if (has_items)
15008 _LoadMailedItems(m);
15010 m_mail.push_back(m);
15011 } while( result->NextRow() );
15012 delete result;
15014 m_mailsLoaded = true;
15017 void Player::LoadPet()
15019 //fixme: the pet should still be loaded if the player is not in world
15020 // just not added to the map
15021 if(IsInWorld())
15023 Pet *pet = new Pet;
15024 if(!pet->LoadPetFromDB(this,0,0,true))
15025 delete pet;
15029 void Player::_LoadQuestStatus(QueryResult *result)
15031 mQuestStatus.clear();
15033 uint32 slot = 0;
15035 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15036 //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());
15038 if(result)
15042 Field *fields = result->Fetch();
15044 uint32 quest_id = fields[0].GetUInt32();
15045 // used to be new, no delete?
15046 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15047 if( pQuest )
15049 // find or create
15050 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15052 uint32 qstatus = fields[1].GetUInt32();
15053 if(qstatus < MAX_QUEST_STATUS)
15054 questStatusData.m_status = QuestStatus(qstatus);
15055 else
15057 questStatusData.m_status = QUEST_STATUS_NONE;
15058 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15061 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15062 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15064 time_t quest_time = time_t(fields[4].GetUInt64());
15066 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15068 AddTimedQuest( quest_id );
15070 if (quest_time <= sWorld.GetGameTime())
15071 questStatusData.m_timer = 1;
15072 else
15073 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
15075 else
15076 quest_time = 0;
15078 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15079 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15080 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15081 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15082 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15083 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15084 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15085 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15087 questStatusData.uState = QUEST_UNCHANGED;
15089 // add to quest log
15090 if( slot < MAX_QUEST_LOG_SIZE &&
15091 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
15092 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
15093 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
15095 SetQuestSlot(slot,quest_id,quest_time);
15097 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
15098 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
15100 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15101 if(questStatusData.m_creatureOrGOcount[idx])
15102 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
15104 ++slot;
15107 if(questStatusData.m_rewarded)
15109 // learn rewarded spell if unknown
15110 learnQuestRewardedSpells(pQuest);
15112 // set rewarded title if any
15113 if(pQuest->GetCharTitleId())
15115 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15116 SetTitle(titleEntry);
15119 if(pQuest->GetBonusTalents())
15120 m_questRewardTalentCount+=pQuest->GetBonusTalents();
15123 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15126 while( result->NextRow() );
15128 delete result;
15131 // clear quest log tail
15132 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15133 SetQuestSlot(i,0);
15136 void Player::_LoadDailyQuestStatus(QueryResult *result)
15138 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15139 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15141 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15143 if(result)
15145 uint32 quest_daily_idx = 0;
15149 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15151 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15152 break;
15155 Field *fields = result->Fetch();
15157 uint32 quest_id = fields[0].GetUInt32();
15159 // save _any_ from daily quest times (it must be after last reset anyway)
15160 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15162 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15163 if( !pQuest )
15164 continue;
15166 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15167 ++quest_daily_idx;
15169 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15171 while( result->NextRow() );
15173 delete result;
15176 m_DailyQuestChanged = false;
15179 void Player::_LoadReputation(QueryResult *result)
15181 m_factions.clear();
15183 // Set initial reputations (so everything is nifty before DB data load)
15184 SetInitialFactions();
15186 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
15188 if(result)
15192 Field *fields = result->Fetch();
15194 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
15195 if( factionEntry && (factionEntry->reputationListID >= 0))
15197 FactionState* faction = &m_factions[factionEntry->reputationListID];
15199 // update standing to current
15200 faction->Standing = int32(fields[1].GetUInt32());
15202 uint32 dbFactionFlags = fields[2].GetUInt32();
15204 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
15205 SetFactionVisible(faction); // have internal checks for forced invisibility
15207 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
15208 SetFactionInactive(faction,true); // have internal checks for visibility requirement
15210 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
15211 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
15212 else // DB not at war
15214 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
15215 if( faction->Flags & FACTION_FLAG_VISIBLE )
15216 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
15219 // set atWar for hostile
15220 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
15221 SetFactionAtWar(faction,true);
15223 // reset changed flag if values similar to saved in DB
15224 if(faction->Flags==dbFactionFlags)
15225 faction->Changed = false;
15228 while( result->NextRow() );
15230 delete result;
15234 void Player::_LoadSpells(QueryResult *result)
15236 for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
15237 delete itr->second;
15238 m_spells.clear();
15240 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15242 if(result)
15246 Field *fields = result->Fetch();
15248 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
15250 while( result->NextRow() );
15252 delete result;
15256 void Player::_LoadTutorials(QueryResult *result)
15258 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
15260 if(result)
15264 Field *fields = result->Fetch();
15266 for (int iI=0; iI<8; iI++)
15267 m_Tutorials[iI] = fields[iI].GetUInt32();
15269 while( result->NextRow() );
15271 delete result;
15274 m_TutorialsChanged = false;
15277 void Player::_LoadGroup(QueryResult *result)
15279 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15280 if(result)
15282 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15283 delete result;
15284 Group* group = objmgr.GetGroupByLeader(leaderGuid);
15285 if(group)
15287 uint8 subgroup = group->GetMemberGroup(GetGUID());
15288 SetGroup(group, subgroup);
15289 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
15291 // the group leader may change the instance difficulty while the player is offline
15292 SetDifficulty(group->GetDifficulty());
15298 void Player::_LoadBoundInstances(QueryResult *result)
15300 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15301 m_boundInstances[i].clear();
15303 Group *group = GetGroup();
15305 //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));
15306 if(result)
15310 Field *fields = result->Fetch();
15311 bool perm = fields[1].GetBool();
15312 uint32 mapId = fields[2].GetUInt32();
15313 uint32 instanceId = fields[0].GetUInt32();
15314 uint8 difficulty = fields[3].GetUInt8();
15315 time_t resetTime = (time_t)fields[4].GetUInt64();
15316 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15317 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15318 // and in that case it is not used
15320 if(!perm && group)
15322 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);
15323 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15324 continue;
15327 // since non permanent binds are always solo bind, they can always be reset
15328 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15329 if(save) BindToInstance(save, perm, true);
15330 } while(result->NextRow());
15331 delete result;
15335 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15337 // some instances only have one difficulty
15338 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15339 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15341 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15342 if(itr != m_boundInstances[difficulty].end())
15343 return &itr->second;
15344 else
15345 return NULL;
15348 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15350 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15351 UnbindInstance(itr, difficulty, unload);
15354 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15356 if(itr != m_boundInstances[difficulty].end())
15358 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15359 itr->second.save->RemovePlayer(this); // save can become invalid
15360 m_boundInstances[difficulty].erase(itr++);
15364 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15366 if(save)
15368 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15369 if(bind.save)
15371 // update the save when the group kills a boss
15372 if(permanent != bind.perm || save != bind.save)
15373 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());
15375 else
15376 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15378 if(bind.save != save)
15380 if(bind.save) bind.save->RemovePlayer(this);
15381 save->AddPlayer(this);
15384 if(permanent) save->SetCanReset(false);
15386 bind.save = save;
15387 bind.perm = permanent;
15388 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());
15389 return &bind;
15391 else
15392 return NULL;
15395 void Player::SendRaidInfo()
15397 uint32 counter = 0;
15399 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15401 size_t p_counter = data.wpos();
15402 data << uint32(counter); // placeholder
15404 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15406 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15408 if(itr->second.perm)
15410 InstanceSave *save = itr->second.save;
15411 data << uint32(save->GetMapId());
15412 data << uint32(save->GetResetTime() - time(NULL));
15413 data << uint32(save->GetInstanceId());
15414 data << uint32(save->GetDifficulty());
15415 ++counter;
15419 data.put<uint32>(p_counter,counter);
15420 GetSession()->SendPacket(&data);
15424 - called on every successful teleportation to a map
15426 void Player::SendSavedInstances()
15428 bool hasBeenSaved = false;
15429 WorldPacket data;
15431 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15433 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15435 if(itr->second.perm) // only permanent binds are sent
15437 hasBeenSaved = true;
15438 break;
15443 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15444 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15445 data << uint32(hasBeenSaved);
15446 GetSession()->SendPacket(&data);
15448 if(!hasBeenSaved)
15449 return;
15451 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15453 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15455 if(itr->second.perm)
15457 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15458 data << uint32(itr->second.save->GetMapId());
15459 GetSession()->SendPacket(&data);
15465 /// convert the player's binds to the group
15466 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15468 bool has_binds = false;
15469 bool has_solo = false;
15471 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15472 assert(player_guid);
15474 // copy all binds to the group, when changing leader it's assumed the character
15475 // will not have any solo binds
15477 if(player)
15479 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15481 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15483 has_binds = true;
15484 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15485 // permanent binds are not removed
15486 if(!itr->second.perm)
15488 player->UnbindInstance(itr, i, true); // increments itr
15489 has_solo = true;
15491 else
15492 ++itr;
15497 // if the player's not online we don't know what binds it has
15498 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));
15499 // the following should not get executed when changing leaders
15500 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15503 bool Player::_LoadHomeBind(QueryResult *result)
15505 bool ok = false;
15506 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15507 if (result)
15509 Field *fields = result->Fetch();
15510 m_homebindMapId = fields[0].GetUInt32();
15511 m_homebindZoneId = fields[1].GetUInt16();
15512 m_homebindX = fields[2].GetFloat();
15513 m_homebindY = fields[3].GetFloat();
15514 m_homebindZ = fields[4].GetFloat();
15515 delete result;
15517 // accept saved data only for valid position (and non instanceable)
15518 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15519 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
15521 ok = true;
15523 else
15524 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15527 if(!ok)
15529 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15530 if(!info) return false;
15532 m_homebindMapId = info->mapId;
15533 m_homebindZoneId = info->zoneId;
15534 m_homebindX = info->positionX;
15535 m_homebindY = info->positionY;
15536 m_homebindZ = info->positionZ;
15538 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);
15541 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15542 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15544 return true;
15547 /*********************************************************/
15548 /*** SAVE SYSTEM ***/
15549 /*********************************************************/
15551 void Player::SaveToDB()
15553 // delay auto save at any saves (manual, in code, or autosave)
15554 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15556 // first save/honor gain after midnight will also update the player's honor fields
15557 UpdateHonorFields();
15559 // players aren't saved on battleground maps
15560 uint32 mapid = IsBeingTeleported() ? GetTeleportDest().mapid : GetMapId();
15561 const MapEntry * me = sMapStore.LookupEntry(mapid);
15562 if(!me || me->IsBattleGroundOrArena())
15563 return;
15565 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15566 //save, far from tavern/city
15567 //save, but in tavern/city
15568 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15569 outDebugValues();
15571 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15572 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15573 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15574 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15575 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15576 uint32 tmp_displayid = GetDisplayId();
15578 // Set player sit state to standing on save, also stealth and shifted form
15579 SetByteValue(UNIT_FIELD_BYTES_1, 0, 0); // stand state
15580 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15581 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0); // stand flags?
15582 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15583 SetDisplayId(GetNativeDisplayId());
15585 bool inworld = IsInWorld();
15587 CharacterDatabase.BeginTransaction();
15589 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15591 std::string sql_name = m_name;
15592 CharacterDatabase.escape_string(sql_name);
15594 std::ostringstream ss;
15595 ss << "INSERT INTO characters (guid,account,name,race,class,"
15596 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15597 "taximask, online, cinematic, "
15598 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15599 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15600 "death_expire_time, taxi_path, arena_pending_points) VALUES ("
15601 << GetGUIDLow() << ", "
15602 << GetSession()->GetAccountId() << ", '"
15603 << sql_name << "', "
15604 << m_race << ", "
15605 << m_class << ", ";
15607 bool save_to_dest = false;
15608 if(IsBeingTeleported())
15610 // don't save to battlegrounds or arenas
15611 const MapEntry *entry = sMapStore.LookupEntry(GetTeleportDest().mapid);
15612 if(entry && entry->map_type != MAP_BATTLEGROUND && entry->map_type != MAP_ARENA)
15613 save_to_dest = true;
15616 if(!save_to_dest)
15618 ss << GetMapId() << ", "
15619 << (uint32)GetDifficulty() << ", "
15620 << finiteAlways(GetPositionX()) << ", "
15621 << finiteAlways(GetPositionY()) << ", "
15622 << finiteAlways(GetPositionZ()) << ", "
15623 << finiteAlways(GetOrientation()) << ", '";
15625 else
15627 ss << GetTeleportDest().mapid << ", "
15628 << (uint32)GetDifficulty() << ", "
15629 << finiteAlways(GetTeleportDest().x) << ", "
15630 << finiteAlways(GetTeleportDest().y) << ", "
15631 << finiteAlways(GetTeleportDest().z) << ", "
15632 << finiteAlways(GetTeleportDest().o) << ", '";
15635 uint16 i;
15636 for( i = 0; i < m_valuesCount; i++ )
15638 ss << GetUInt32Value(i) << " ";
15641 ss << "', ";
15643 ss << m_taxi; // string with TaxiMaskSize numbers
15645 ss << ", ";
15646 ss << (inworld ? 1 : 0);
15648 ss << ", ";
15649 ss << m_cinematic;
15651 ss << ", ";
15652 ss << m_Played_time[0];
15653 ss << ", ";
15654 ss << m_Played_time[1];
15656 ss << ", ";
15657 ss << finiteAlways(m_rest_bonus);
15658 ss << ", ";
15659 ss << (uint64)time(NULL);
15660 ss << ", ";
15661 ss << is_save_resting;
15662 ss << ", ";
15663 ss << m_resetTalentsCost;
15664 ss << ", ";
15665 ss << (uint64)m_resetTalentsTime;
15667 ss << ", ";
15668 ss << finiteAlways(m_movementInfo.t_x);
15669 ss << ", ";
15670 ss << finiteAlways(m_movementInfo.t_y);
15671 ss << ", ";
15672 ss << finiteAlways(m_movementInfo.t_z);
15673 ss << ", ";
15674 ss << finiteAlways(m_movementInfo.t_o);
15675 ss << ", ";
15676 if (m_transport)
15677 ss << m_transport->GetGUIDLow();
15678 else
15679 ss << "0";
15681 ss << ", ";
15682 ss << m_ExtraFlags;
15684 ss << ", ";
15685 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15687 ss << ", ";
15688 ss << uint32(m_atLoginFlags);
15690 ss << ", ";
15691 ss << GetZoneId();
15693 ss << ", ";
15694 ss << (uint64)m_deathExpireTime;
15696 ss << ", '";
15697 ss << m_taxi.SaveTaxiDestinationsToString();
15698 ss << "', '0' )";
15700 CharacterDatabase.Execute( ss.str().c_str() );
15702 if(m_mailsUpdated) //save mails only when needed
15703 _SaveMail();
15705 _SaveInventory();
15706 _SaveQuestStatus();
15707 _SaveDailyQuestStatus();
15708 _SaveTutorials();
15709 _SaveSpells();
15710 _SaveSpellCooldowns();
15711 _SaveActions();
15712 _SaveAuras();
15713 _SaveReputation();
15715 CharacterDatabase.CommitTransaction();
15717 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15718 SetDisplayId(tmp_displayid);
15719 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15720 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15721 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15722 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15724 // save pet (hunter pet level and experience and all type pets health/mana).
15725 if(Pet* pet = GetPet())
15726 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15727 m_achievementMgr.SaveToDB();
15730 // fast save function for item/money cheating preventing - save only inventory and money state
15731 void Player::SaveInventoryAndGoldToDB()
15733 _SaveInventory();
15734 //money is in data field
15735 SaveDataFieldToDB();
15738 void Player::_SaveActions()
15740 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15742 switch (itr->second.uState)
15744 case ACTIONBUTTON_NEW:
15745 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15746 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15747 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15748 ++itr;
15749 break;
15750 case ACTIONBUTTON_CHANGED:
15751 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15752 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15753 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15754 ++itr;
15755 break;
15756 case ACTIONBUTTON_DELETED:
15757 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15758 m_actionButtons.erase(itr++);
15759 break;
15760 default:
15761 ++itr;
15762 break;
15767 void Player::_SaveAuras()
15769 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15771 AuraMap const& auras = GetAuras();
15773 if (auras.empty())
15774 return;
15776 spellEffectPair lastEffectPair = auras.begin()->first;
15777 uint32 stackCounter = 1;
15779 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15781 if(itr == auras.end() || lastEffectPair != itr->first)
15783 AuraMap::const_iterator itr2 = itr;
15784 // save previous spellEffectPair to db
15785 itr2--;
15786 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15788 //skip all auras from spells that are passive or need a shapeshift
15789 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15791 //do not save single target auras (unless they were cast by the player)
15792 if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
15794 uint8 i;
15795 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15796 for (i = 0; i < 3; i++)
15797 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15798 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15799 break;
15801 if (i == 3)
15803 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15804 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15805 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()));
15810 if(itr == auras.end())
15811 break;
15814 if (lastEffectPair == itr->first)
15815 stackCounter++;
15816 else
15818 lastEffectPair = itr->first;
15819 stackCounter = 1;
15824 void Player::_SaveInventory()
15826 // force items in buyback slots to new state
15827 // and remove those that aren't already
15828 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
15830 Item *item = m_items[i];
15831 if (!item || item->GetState() == ITEM_NEW) continue;
15832 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15833 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15834 m_items[i]->FSetState(ITEM_NEW);
15837 // update enchantment durations
15838 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15840 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15843 // if no changes
15844 if (m_itemUpdateQueue.empty()) return;
15846 // do not save if the update queue is corrupt
15847 bool error = false;
15848 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15850 Item *item = m_itemUpdateQueue[i];
15851 if(!item || item->GetState() == ITEM_REMOVED) continue;
15852 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15854 if (test == NULL)
15856 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());
15857 error = true;
15859 else if (test != item)
15861 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());
15862 error = true;
15866 if (error)
15868 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15869 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15870 return;
15873 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15875 Item *item = m_itemUpdateQueue[i];
15876 if(!item) continue;
15878 Bag *container = item->GetContainer();
15879 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15881 switch(item->GetState())
15883 case ITEM_NEW:
15884 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());
15885 break;
15886 case ITEM_CHANGED:
15887 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());
15888 break;
15889 case ITEM_REMOVED:
15890 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15891 break;
15892 case ITEM_UNCHANGED:
15893 break;
15896 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15898 m_itemUpdateQueue.clear();
15901 void Player::_SaveMail()
15903 if (!m_mailsLoaded)
15904 return;
15906 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15908 Mail *m = (*itr);
15909 if (m->state == MAIL_STATE_CHANGED)
15911 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'",
15912 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15913 if(m->removedItems.size())
15915 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15916 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15917 m->removedItems.clear();
15919 m->state = MAIL_STATE_UNCHANGED;
15921 else if (m->state == MAIL_STATE_DELETED)
15923 if (m->HasItems())
15924 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15925 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15926 if (m->itemTextId)
15927 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15928 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15929 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15933 //deallocate deleted mails...
15934 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15936 if ((*itr)->state == MAIL_STATE_DELETED)
15938 Mail* m = *itr;
15939 m_mail.erase(itr);
15940 delete m;
15941 itr = m_mail.begin();
15943 else
15944 ++itr;
15947 m_mailsUpdated = false;
15950 void Player::_SaveQuestStatus()
15952 // we don't need transactions here.
15953 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15955 switch (i->second.uState)
15957 case QUEST_NEW :
15958 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15959 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15960 GetGUIDLow(), i->first, i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / 1000 + 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]);
15961 break;
15962 case QUEST_CHANGED :
15963 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' ",
15964 i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / 1000 + 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 );
15965 break;
15966 case QUEST_UNCHANGED:
15967 break;
15969 i->second.uState = QUEST_UNCHANGED;
15973 void Player::_SaveDailyQuestStatus()
15975 if(!m_DailyQuestChanged)
15976 return;
15978 m_DailyQuestChanged = false;
15980 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15982 // we don't need transactions here.
15983 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15984 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15985 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15986 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15987 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15990 void Player::_SaveReputation()
15992 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
15994 if (itr->second.Changed)
15996 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
15997 CharacterDatabase.PExecute("INSERT INTO character_reputation (guid,faction,standing,flags) VALUES ('%u', '%u', '%i', '%u')", GetGUIDLow(), itr->second.ID, itr->second.Standing, itr->second.Flags);
15998 itr->second.Changed = false;
16003 void Player::_SaveSpells()
16005 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
16007 ++next;
16008 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
16009 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
16011 // add only changed/new not dependent spells
16012 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
16013 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);
16015 if (itr->second->state == PLAYERSPELL_REMOVED)
16016 _removeSpell(itr->first);
16017 else
16018 itr->second->state = PLAYERSPELL_UNCHANGED;
16022 void Player::_SaveTutorials()
16024 if(!m_TutorialsChanged)
16025 return;
16027 uint32 Rows=0;
16028 // it's better than rebuilding indexes multiple times
16029 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
16030 if(result)
16032 Rows = result->Fetch()[0].GetUInt32();
16033 delete result;
16036 if (Rows)
16038 CharacterDatabase.PExecute("UPDATE character_tutorial SET tut0='%u', tut1='%u', tut2='%u', tut3='%u', tut4='%u', tut5='%u', tut6='%u', tut7='%u' WHERE account = '%u' AND realmid = '%u'",
16039 m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7], GetSession()->GetAccountId(), realmID );
16041 else
16043 CharacterDatabase.PExecute("INSERT INTO character_tutorial (account,realmid,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES ('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')", GetSession()->GetAccountId(), realmID, m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7]);
16046 m_TutorialsChanged = false;
16049 void Player::outDebugValues() const
16051 if(!sLog.IsOutDebug()) // optimize disabled debug output
16052 return;
16054 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
16055 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
16056 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
16057 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
16058 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
16059 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
16060 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
16061 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
16062 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
16063 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
16064 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
16065 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
16068 /*********************************************************/
16069 /*** FLOOD FILTER SYSTEM ***/
16070 /*********************************************************/
16072 void Player::UpdateSpeakTime()
16074 // ignore chat spam protection for GMs in any mode
16075 if(GetSession()->GetSecurity() > SEC_PLAYER)
16076 return;
16078 time_t current = time (NULL);
16079 if(m_speakTime > current)
16081 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
16082 if(!max_count)
16083 return;
16085 ++m_speakCount;
16086 if(m_speakCount >= max_count)
16088 // prevent overwrite mute time, if message send just before mutes set, for example.
16089 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
16090 if(GetSession()->m_muteTime < new_mute)
16091 GetSession()->m_muteTime = new_mute;
16093 m_speakCount = 0;
16096 else
16097 m_speakCount = 0;
16099 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
16102 bool Player::CanSpeak() const
16104 return GetSession()->m_muteTime <= time (NULL);
16107 /*********************************************************/
16108 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16109 /*********************************************************/
16111 void Player::SendAttackSwingNotInRange()
16113 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16114 GetSession()->SendPacket( &data );
16117 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16119 std::ostringstream ss;
16120 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16121 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16122 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16123 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16124 sLog.outDebug(ss.str().c_str());
16125 CharacterDatabase.Execute(ss.str().c_str());
16128 void Player::SaveDataFieldToDB()
16130 std::ostringstream ss;
16131 ss<<"UPDATE characters SET data='";
16133 for(uint16 i = 0; i < m_valuesCount; i++ )
16135 ss << GetUInt32Value(i) << " ";
16137 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16139 CharacterDatabase.Execute(ss.str().c_str());
16142 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16144 std::ostringstream ss2;
16145 ss2<<"UPDATE characters SET data='";
16146 int i=0;
16147 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16149 ss2<<tokens[i]<<" ";
16151 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16153 return CharacterDatabase.Execute(ss2.str().c_str());
16156 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16158 char buf[11];
16159 snprintf(buf,11,"%u",value);
16161 if(index >= tokens.size())
16162 return;
16164 tokens[index] = buf;
16167 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16169 Tokens tokens;
16170 if(!LoadValuesArrayFromDB(tokens,guid))
16171 return;
16173 if(index >= tokens.size())
16174 return;
16176 char buf[11];
16177 snprintf(buf,11,"%u",value);
16178 tokens[index] = buf;
16180 SaveValuesArrayInDB(tokens,guid);
16183 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16185 uint32 temp;
16186 memcpy(&temp, &value, sizeof(value));
16187 Player::SetUInt32ValueInDB(index, temp, guid);
16190 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16192 Tokens tokens;
16193 if(!LoadValuesArrayFromDB(tokens, guid))
16194 return;
16196 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
16197 uint8 race = unit_bytes0 & 0xFF;
16198 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
16200 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
16201 if(!info)
16202 return;
16204 unit_bytes0 &= ~(0xFF << 16);
16205 unit_bytes0 |= (gender << 16);
16206 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
16208 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
16209 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
16211 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
16213 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
16214 player_bytes2 &= ~0xFF;
16215 player_bytes2 |= facialHair;
16216 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
16218 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
16219 player_bytes3 &= ~0xFF;
16220 player_bytes3 |= gender;
16221 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
16223 SaveValuesArrayInDB(tokens, guid);
16226 void Player::SendAttackSwingNotStanding()
16228 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
16229 GetSession()->SendPacket( &data );
16232 void Player::SendAttackSwingDeadTarget()
16234 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16235 GetSession()->SendPacket( &data );
16238 void Player::SendAttackSwingCantAttack()
16240 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16241 GetSession()->SendPacket( &data );
16244 void Player::SendAttackSwingCancelAttack()
16246 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16247 GetSession()->SendPacket( &data );
16250 void Player::SendAttackSwingBadFacingAttack()
16252 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16253 GetSession()->SendPacket( &data );
16256 void Player::SendAutoRepeatCancel()
16258 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
16259 data.append(GetPackGUID()); // may be it's target guid
16260 GetSession()->SendPacket( &data );
16263 void Player::PlaySound(uint32 Sound, bool OnlySelf)
16265 WorldPacket data(SMSG_PLAY_SOUND, 4);
16266 data << Sound;
16267 if (OnlySelf)
16268 GetSession()->SendPacket( &data );
16269 else
16270 SendMessageToSet( &data, true );
16273 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16275 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16276 data << Area;
16277 data << Experience;
16278 GetSession()->SendPacket(&data);
16281 void Player::SendDungeonDifficulty(bool IsInGroup)
16283 uint8 val = 0x00000001;
16284 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16285 data << (uint32)GetDifficulty();
16286 data << uint32(val);
16287 data << uint32(IsInGroup);
16288 GetSession()->SendPacket(&data);
16291 void Player::SendResetFailedNotify(uint32 mapid)
16293 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16294 data << uint32(mapid);
16295 GetSession()->SendPacket(&data);
16298 /// Reset all solo instances and optionally send a message on success for each
16299 void Player::ResetInstances(uint8 method)
16301 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16303 // we assume that when the difficulty changes, all instances that can be reset will be
16304 uint8 dif = GetDifficulty();
16306 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16308 InstanceSave *p = itr->second.save;
16309 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16310 if(!entry || !p->CanReset())
16312 ++itr;
16313 continue;
16316 if(method == INSTANCE_RESET_ALL)
16318 // the "reset all instances" method can only reset normal maps
16319 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16321 ++itr;
16322 continue;
16326 // if the map is loaded, reset it
16327 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16328 if(map && map->IsDungeon())
16329 ((InstanceMap*)map)->Reset(method);
16331 // since this is a solo instance there should not be any players inside
16332 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16333 SendResetInstanceSuccess(p->GetMapId());
16335 p->DeleteFromDB();
16336 m_boundInstances[dif].erase(itr++);
16338 // the following should remove the instance save from the manager and delete it as well
16339 p->RemovePlayer(this);
16343 void Player::SendResetInstanceSuccess(uint32 MapId)
16345 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16346 data << MapId;
16347 GetSession()->SendPacket(&data);
16350 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16352 // TODO: find what other fail reasons there are besides players in the instance
16353 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16354 data << reason;
16355 data << MapId;
16356 GetSession()->SendPacket(&data);
16359 /*********************************************************/
16360 /*** Update timers ***/
16361 /*********************************************************/
16363 ///checks the 15 afk reports per 5 minutes limit
16364 void Player::UpdateAfkReport(time_t currTime)
16366 if(m_bgAfkReportedTimer <= currTime)
16368 m_bgAfkReportedCount = 0;
16369 m_bgAfkReportedTimer = currTime+5*MINUTE;
16373 void Player::UpdateContestedPvP(uint32 diff)
16375 if(!m_contestedPvPTimer||isInCombat())
16376 return;
16377 if(m_contestedPvPTimer <= diff)
16379 ResetContestedPvP();
16381 else
16382 m_contestedPvPTimer -= diff;
16385 void Player::UpdatePvPFlag(time_t currTime)
16387 if(!IsPvP())
16388 return;
16389 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16390 return;
16392 UpdatePvP(false);
16395 void Player::UpdateDuelFlag(time_t currTime)
16397 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16398 return;
16400 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16401 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16403 duel->startTimer = 0;
16404 duel->startTime = currTime;
16405 duel->opponent->duel->startTimer = 0;
16406 duel->opponent->duel->startTime = currTime;
16409 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16411 if(!pet)
16412 pet = GetPet();
16414 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16416 //returning of reagents only for players, so best done here
16417 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16418 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16420 if(spellInfo)
16422 for(uint32 i = 0; i < 7; ++i)
16424 if(spellInfo->Reagent[i] > 0)
16426 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16427 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16428 if( msg == EQUIP_ERR_OK )
16430 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16431 if(IsInWorld())
16432 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16437 m_temporaryUnsummonedPetNumber = 0;
16440 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16441 return;
16443 // only if current pet in slot
16444 switch(pet->getPetType())
16446 case MINI_PET:
16447 m_miniPet = 0;
16448 break;
16449 case GUARDIAN_PET:
16450 m_guardianPets.erase(pet->GetGUID());
16451 break;
16452 default:
16453 if(GetPetGUID() == pet->GetGUID())
16454 SetPet(NULL);
16455 break;
16458 pet->CombatStop();
16460 if(returnreagent)
16462 switch(pet->GetEntry())
16464 //warlock pets except imp are removed(?) when logging out
16465 case 1860:
16466 case 1863:
16467 case 417:
16468 case 17252:
16469 mode = PET_SAVE_NOT_IN_SLOT;
16470 break;
16474 pet->SavePetToDB(mode);
16476 pet->CleanupsBeforeDelete();
16477 pet->AddObjectToRemoveList();
16478 pet->m_removed = true;
16480 if(pet->isControlled())
16482 WorldPacket data(SMSG_PET_SPELLS, 8);
16483 data << uint64(0);
16484 data << uint32(0);
16485 GetSession()->SendPacket(&data);
16487 if(GetGroup())
16488 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16492 void Player::RemoveMiniPet()
16494 if(Pet* pet = GetMiniPet())
16496 pet->Remove(PET_SAVE_AS_DELETED);
16497 m_miniPet = 0;
16501 Pet* Player::GetMiniPet()
16503 if(!m_miniPet)
16504 return NULL;
16505 return ObjectAccessor::GetPet(m_miniPet);
16508 void Player::RemoveGuardians()
16510 while(!m_guardianPets.empty())
16512 uint64 guid = *m_guardianPets.begin();
16513 if(Pet* pet = ObjectAccessor::GetPet(guid))
16514 pet->Remove(PET_SAVE_AS_DELETED);
16516 m_guardianPets.erase(guid);
16520 bool Player::HasGuardianWithEntry(uint32 entry)
16522 // pet guid middle part is entry (and creature also)
16523 // and in guardian list must be guardians with same entry _always_
16524 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16525 if(GUID_ENPART(*itr)==entry)
16526 return true;
16528 return false;
16531 void Player::Uncharm()
16533 Unit* charm = GetCharm();
16534 if(!charm)
16535 return;
16537 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16538 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16541 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16543 *data << (uint8)msgtype;
16544 *data << (uint32)language;
16545 *data << (uint64)GetGUID();
16546 *data << (uint32)language; //language 2.1.0 ?
16547 *data << (uint64)GetGUID();
16548 *data << (uint32)(text.length()+1);
16549 *data << text;
16550 *data << (uint8)chatTag();
16553 void Player::Say(const std::string& text, const uint32 language)
16555 WorldPacket data(SMSG_MESSAGECHAT, 200);
16556 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16557 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16560 void Player::Yell(const std::string& text, const uint32 language)
16562 WorldPacket data(SMSG_MESSAGECHAT, 200);
16563 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16564 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16567 void Player::TextEmote(const std::string& text)
16569 WorldPacket data(SMSG_MESSAGECHAT, 200);
16570 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16571 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16574 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16576 if (language != LANG_ADDON) // if not addon data
16577 language = LANG_UNIVERSAL; // whispers should always be readable
16579 Player *rPlayer = objmgr.GetPlayer(receiver);
16581 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16582 if(!rPlayer->isDND() || isGameMaster())
16584 WorldPacket data(SMSG_MESSAGECHAT, 200);
16585 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16586 rPlayer->GetSession()->SendPacket(&data);
16588 data.Initialize(SMSG_MESSAGECHAT, 200);
16589 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16590 GetSession()->SendPacket(&data);
16592 else
16594 // announce to player that player he is whispering to is dnd and cannot receive his message
16595 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16598 if(!isAcceptWhispers())
16600 SetAcceptWhispers(true);
16601 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16604 // announce to player that player he is whispering to is afk
16605 if(rPlayer->isAFK())
16606 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16608 // if player whisper someone, auto turn of dnd to be able to receive an answer
16609 if(isDND() && !rPlayer->isGameMaster())
16610 ToggleDND();
16613 void Player::PetSpellInitialize()
16615 Pet* pet = GetPet();
16617 if(!pet)
16618 return;
16620 sLog.outDebug("Pet Spells Groups");
16622 CharmInfo *charmInfo = pet->GetCharmInfo();
16624 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16625 data << uint64(pet->GetGUID());
16626 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16627 data << uint32(0);
16628 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16630 // action bar loop
16631 for(uint32 i = 0; i < 10; i++)
16633 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16636 size_t spellsCountPos = data.wpos();
16638 // spells count
16639 uint8 addlist = 0;
16640 data << uint8(addlist); // placeholder
16642 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16644 // spells loop
16645 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16647 if(itr->second->state == PETSPELL_REMOVED)
16648 continue;
16650 data << uint16(itr->first);
16651 data << uint16(itr->second->active); // pet spell active state isn't boolean
16652 ++addlist;
16656 data.put<uint8>(spellsCountPos, addlist);
16658 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16659 data << uint8(cooldownsCount);
16661 time_t curTime = time(NULL);
16663 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16665 time_t cooldown = 0;
16667 if(itr->second > curTime)
16668 cooldown = (itr->second - curTime) * 1000;
16670 data << uint16(itr->first); // spellid
16671 data << uint16(0); // spell category?
16672 data << uint32(itr->second); // cooldown
16673 data << uint32(0); // category cooldown
16676 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16678 time_t cooldown = 0;
16680 if(itr->second > curTime)
16681 cooldown = (itr->second - curTime) * 1000;
16683 data << uint16(itr->first); // spellid
16684 data << uint16(0); // spell category?
16685 data << uint32(0); // cooldown
16686 data << uint32(itr->second); // category cooldown
16689 GetSession()->SendPacket(&data);
16692 void Player::PossessSpellInitialize()
16694 Unit* charm = GetCharm();
16696 if(!charm)
16697 return;
16699 CharmInfo *charmInfo = charm->GetCharmInfo();
16701 if(!charmInfo)
16703 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16704 return;
16707 uint8 addlist = 0;
16708 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16710 //16
16711 data << uint64(charm->GetGUID());
16712 data << uint32(0x00000000);
16713 data << uint32(0);
16714 data << uint8(0) << uint8(0) << uint16(0);
16716 for(uint32 i = 0; i < 10; i++) //40
16718 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16721 data << uint8(addlist); //1
16723 uint8 count = 0;
16724 data << uint8(count); // cooldowns count
16726 GetSession()->SendPacket(&data);
16729 void Player::CharmSpellInitialize()
16731 Unit* charm = GetCharm();
16733 if(!charm)
16734 return;
16736 CharmInfo *charmInfo = charm->GetCharmInfo();
16737 if(!charmInfo)
16739 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16740 return;
16743 uint8 addlist = 0;
16745 if(charm->GetTypeId() != TYPEID_PLAYER)
16747 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16749 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16751 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16753 if(charmInfo->GetCharmSpell(i)->spellId)
16754 ++addlist;
16759 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16761 data << uint64(charm->GetGUID());
16762 data << uint32(0x00000000);
16763 data << uint32(0);
16764 if(charm->GetTypeId() != TYPEID_PLAYER)
16765 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16766 else
16767 data << uint8(0) << uint8(0);
16768 data << uint16(0);
16770 for(uint32 i = 0; i < 10; i++) //40
16772 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16775 data << uint8(addlist); //1
16777 if(addlist)
16779 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16781 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16782 if(cspell->spellId)
16784 data << uint16(cspell->spellId);
16785 data << uint16(cspell->active);
16790 uint8 count = 0;
16791 data << uint8(count); // cooldowns count
16793 GetSession()->SendPacket(&data);
16796 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16798 if (!mod || !spellInfo)
16799 return false;
16801 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16803 // prevent apply to any spell except spell that trigger expire
16804 if(spell)
16806 if(mod->lastAffected != spell)
16807 return false;
16809 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16810 return false;
16813 return spellmgr.IsAffectedByMod(spellInfo, mod);
16816 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16818 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16820 for(int eff=0;eff<96;++eff)
16822 uint64 _mask = 0;
16823 uint64 _mask2= 0;
16824 if (eff<64) _mask = uint64(1) << (eff- 0);
16825 else _mask2= uint64(1) << (eff-64);
16826 if ( mod->mask & _mask || mod->mask2 & _mask2)
16828 int32 val = 0;
16829 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16831 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16832 val += (*itr)->value;
16834 val += apply ? mod->value : -(mod->value);
16835 WorldPacket data(Opcode, (1+1+4));
16836 data << uint8(eff);
16837 data << uint8(mod->op);
16838 data << int32(val);
16839 SendDirectMessage(&data);
16843 if (apply)
16844 m_spellMods[mod->op].push_back(mod);
16845 else
16847 if (mod->charges == -1)
16848 --m_SpellModRemoveCount;
16849 m_spellMods[mod->op].remove(mod);
16850 delete mod;
16854 void Player::RemoveSpellMods(Spell const* spell)
16856 if(!spell || (m_SpellModRemoveCount == 0))
16857 return;
16859 for(int i=0;i<MAX_SPELLMOD;++i)
16861 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16863 SpellModifier *mod = *itr;
16864 ++itr;
16866 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16868 RemoveAurasDueToSpell(mod->spellId);
16869 if (m_spellMods[i].empty())
16870 break;
16871 else
16872 itr = m_spellMods[i].begin();
16878 // send Proficiency
16879 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16881 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16882 data << pr1 << pr2;
16883 GetSession()->SendPacket (&data);
16886 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16888 QueryResult *result = NULL;
16889 if(type==10)
16890 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16891 else
16892 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16893 if(result)
16895 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.
16896 { // and SendPetitionQueryOpcode reads data from the DB
16897 Field *fields = result->Fetch();
16898 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16899 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16901 // send update if charter owner in game
16902 Player* owner = objmgr.GetPlayer(ownerguid);
16903 if(owner)
16904 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16906 } while ( result->NextRow() );
16908 delete result;
16910 if(type==10)
16911 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16912 else
16913 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16916 CharacterDatabase.BeginTransaction();
16917 if(type == 10)
16919 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16920 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16922 else
16924 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16925 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16927 CharacterDatabase.CommitTransaction();
16930 void Player::LeaveAllArenaTeams(uint64 guid)
16932 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));
16933 if(!result)
16934 return;
16938 Field *fields = result->Fetch();
16939 uint32 at_id = fields[0].GetUInt32();
16940 if(at_id != 0)
16942 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16943 if(at)
16944 at->DelMember(guid);
16946 } while (result->NextRow());
16948 delete result;
16951 void Player::SetRestBonus (float rest_bonus_new)
16953 // Prevent resting on max level
16954 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16955 rest_bonus_new = 0;
16957 if(rest_bonus_new < 0)
16958 rest_bonus_new = 0;
16960 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16962 if(rest_bonus_new > rest_bonus_max)
16963 m_rest_bonus = rest_bonus_max;
16964 else
16965 m_rest_bonus = rest_bonus_new;
16967 // update data for client
16968 if(m_rest_bonus>10)
16969 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16970 else if(m_rest_bonus<=1)
16971 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16973 //RestTickUpdate
16974 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16977 void Player::HandleStealthedUnitsDetection()
16979 std::list<Unit*> stealthedUnits;
16981 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16982 Cell cell(p);
16983 cell.data.Part.reserved = ALL_DISTRICT;
16984 cell.SetNoCreate();
16986 MaNGOS::AnyStealthedCheck u_check;
16987 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
16989 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16990 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16992 CellLock<GridReadGuard> cell_lock(cell, p);
16993 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16994 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16996 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16998 if((*i)==this)
17000 i = stealthedUnits.erase(i);
17001 continue;
17004 if ((*i)->isVisibleForOrDetect(this,true))
17007 (*i)->SendUpdateToPlayer(this);
17008 m_clientGUIDs.insert((*i)->GetGUID());
17010 #ifdef MANGOS_DEBUG
17011 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17012 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
17013 #endif
17015 // target aura duration for caster show only if target exist at caster client
17016 // send data at target visibility change (adding to client)
17017 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
17018 SendAurasForTarget(*i);
17020 i = stealthedUnits.erase(i);
17021 continue;
17024 ++i;
17028 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
17030 if(nodes.size() < 2)
17031 return false;
17033 // not let cheating with start flight mounted
17034 if(IsMounted())
17036 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17037 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
17038 GetSession()->SendPacket(&data);
17039 return false;
17042 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17044 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17045 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
17046 GetSession()->SendPacket(&data);
17047 return false;
17050 // 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
17051 if(GetSession()->isLogingOut() ||
17052 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
17053 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
17054 IsNonMeleeSpellCasted(false) ||
17055 isInCombat())
17057 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17058 data << uint32(ERR_TAXIPLAYERBUSY);
17059 GetSession()->SendPacket(&data);
17060 return false;
17063 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
17064 return false;
17066 uint32 sourcenode = nodes[0];
17068 // starting node too far away (cheat?)
17069 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
17070 if( !node || node->map_id != GetMapId() ||
17071 (node->x - GetPositionX())*(node->x - GetPositionX())+
17072 (node->y - GetPositionY())*(node->y - GetPositionY())+
17073 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
17074 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
17076 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17077 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17078 GetSession()->SendPacket(&data);
17079 return false;
17082 // Prepare to flight start now
17084 // stop combat at start taxi flight if any
17085 CombatStop();
17087 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17088 TradeCancel(true);
17090 // clean not finished taxi path if any
17091 m_taxi.ClearTaxiDestinations();
17093 // 0 element current node
17094 m_taxi.AddTaxiDestination(sourcenode);
17096 // fill destinations path tail
17097 uint32 sourcepath = 0;
17098 uint32 totalcost = 0;
17100 uint32 prevnode = sourcenode;
17101 uint32 lastnode = 0;
17103 for(uint32 i = 1; i < nodes.size(); ++i)
17105 uint32 path, cost;
17107 lastnode = nodes[i];
17108 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
17110 if(!path)
17112 m_taxi.ClearTaxiDestinations();
17113 return false;
17116 totalcost += cost;
17118 if(prevnode == sourcenode)
17119 sourcepath = path;
17121 m_taxi.AddTaxiDestination(lastnode);
17123 prevnode = lastnode;
17126 if(!mount_id) // if not provide then attempt use default.
17127 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
17129 if (mount_id == 0 || sourcepath == 0)
17131 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17132 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17133 GetSession()->SendPacket(&data);
17134 m_taxi.ClearTaxiDestinations();
17135 return false;
17138 uint32 money = GetMoney();
17140 if(npc)
17142 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17145 if(money < totalcost)
17147 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17148 data << uint32(ERR_TAXINOTENOUGHMONEY);
17149 GetSession()->SendPacket(&data);
17150 m_taxi.ClearTaxiDestinations();
17151 return false;
17154 //Checks and preparations done, DO FLIGHT
17155 ModifyMoney(-(int32)totalcost);
17157 // prevent stealth flight
17158 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17160 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17161 data << uint32(ERR_TAXIOK);
17162 GetSession()->SendPacket(&data);
17164 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17166 GetSession()->SendDoFlight(mount_id, sourcepath);
17168 return true;
17171 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17173 // last check 2.0.10
17174 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17175 data << GetGUID();
17176 data << uint8(0x0); // flags (0x1, 0x2)
17177 time_t curTime = time(NULL);
17178 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17180 if (itr->second->state == PLAYERSPELL_REMOVED)
17181 continue;
17182 uint32 unSpellId = itr->first;
17183 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17184 if (!spellInfo)
17186 ASSERT(spellInfo);
17187 continue;
17190 // Not send cooldown for this spells
17191 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17192 continue;
17194 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17196 data << unSpellId;
17197 data << unTimeMs; // in m.secs
17198 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
17201 GetSession()->SendPacket(&data);
17204 void Player::InitDataForForm(bool reapplyMods)
17206 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17207 if(ssEntry && ssEntry->attackSpeed)
17209 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17210 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17211 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17213 else
17214 SetRegularAttackTime();
17216 switch(m_form)
17218 case FORM_CAT:
17220 if(getPowerType()!=POWER_ENERGY)
17221 setPowerType(POWER_ENERGY);
17222 break;
17224 case FORM_BEAR:
17225 case FORM_DIREBEAR:
17227 if(getPowerType()!=POWER_RAGE)
17228 setPowerType(POWER_RAGE);
17229 break;
17231 default: // 0, for example
17233 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17234 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17235 setPowerType(Powers(cEntry->powerType));
17236 break;
17240 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17241 if (!reapplyMods)
17242 UpdateEquipSpellsAtFormChange();
17244 UpdateAttackPowerAndDamage();
17245 UpdateAttackPowerAndDamage(true);
17248 // Return true is the bought item has a max count to force refresh of window by caller
17249 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
17251 // cheating attempt
17252 if(count < 1) count = 1;
17254 if(!isAlive())
17255 return false;
17257 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
17258 if( !pProto )
17260 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17261 return false;
17264 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
17265 if (!pCreature)
17267 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17268 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17269 return false;
17272 VendorItemData const* vItems = pCreature->GetVendorItems();
17273 if(!vItems || vItems->Empty())
17275 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17276 return false;
17279 size_t vendor_slot = vItems->FindItemSlot(item);
17280 if(vendor_slot >= vItems->GetItemCount())
17282 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17283 return false;
17286 VendorItem const* crItem = vItems->m_items[vendor_slot];
17288 // check current item amount if it limited
17289 if( crItem->maxcount != 0 )
17291 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17293 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17294 return false;
17298 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17300 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17301 return false;
17304 if(crItem->ExtendedCost)
17306 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17307 if(!iece)
17309 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17310 return false;
17313 // honor points price
17314 if(GetHonorPoints() < (iece->reqhonorpoints * count))
17316 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17317 return false;
17320 // arena points price
17321 if(GetArenaPoints() < (iece->reqarenapoints * count))
17323 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17324 return false;
17327 // item base price
17328 for (uint8 i = 0; i < 5; ++i)
17330 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17332 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17333 return false;
17337 // check for personal arena rating requirement
17338 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17340 // probably not the proper equip err
17341 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17342 return false;
17346 uint32 price = pProto->BuyPrice * count;
17348 // reputation discount
17349 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17351 if( GetMoney() < price )
17353 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17354 return false;
17357 uint8 bag = 0; // init for case invalid bagGUID
17359 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17361 Bag *pBag;
17362 if( bagguid == GetGUID() )
17364 bag = INVENTORY_SLOT_BAG_0;
17366 else
17368 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
17370 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17371 if( pBag )
17373 if( bagguid == pBag->GetGUID() )
17375 bag = i;
17376 break;
17383 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17385 ItemPosCountVec dest;
17386 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17387 if( msg != EQUIP_ERR_OK )
17389 SendEquipError( msg, NULL, NULL );
17390 return false;
17393 ModifyMoney( -(int32)price );
17394 if(crItem->ExtendedCost) // case for new honor system
17396 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17397 if(iece->reqhonorpoints)
17398 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17399 if(iece->reqarenapoints)
17400 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17401 for (uint8 i = 0; i < 5; ++i)
17403 if(iece->reqitem[i])
17404 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17408 if(Item *it = StoreNewItem( dest, item, true ))
17410 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17412 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17413 data << pCreature->GetGUID();
17414 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17415 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17416 data << (uint32)count;
17417 GetSession()->SendPacket(&data);
17419 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17422 else if( IsEquipmentPos( bag, slot ) )
17424 if(pProto->BuyCount * count != 1)
17426 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17427 return false;
17430 uint16 dest;
17431 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17432 if( msg != EQUIP_ERR_OK )
17434 SendEquipError( msg, NULL, NULL );
17435 return false;
17438 ModifyMoney( -(int32)price );
17439 if(crItem->ExtendedCost) // case for new honor system
17441 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17442 if(iece->reqhonorpoints)
17443 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17444 if(iece->reqarenapoints)
17445 ModifyArenaPoints( - int32(iece->reqarenapoints));
17446 for (uint8 i = 0; i < 5; ++i)
17448 if(iece->reqitem[i])
17449 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17453 if(Item *it = EquipNewItem( dest, item, true ))
17455 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17457 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17458 data << pCreature->GetGUID();
17459 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17460 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17461 data << (uint32)count;
17462 GetSession()->SendPacket(&data);
17464 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17466 AutoUnequipOffhandIfNeed();
17469 else
17471 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17472 return false;
17475 return crItem->maxcount!=0;
17478 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17480 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17481 // the personal rating of the arena team must match the required limit as well
17482 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17483 uint32 max_personal_rating = 0;
17484 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17486 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17488 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17489 uint32 t_rating = at->GetRating();
17490 p_rating = p_rating<t_rating? p_rating : t_rating;
17491 if(max_personal_rating < p_rating)
17492 max_personal_rating = p_rating;
17495 return max_personal_rating;
17498 void Player::UpdateHomebindTime(uint32 time)
17500 // GMs never get homebind timer online
17501 if (m_InstanceValid || isGameMaster())
17503 if(m_HomebindTimer) // instance valid, but timer not reset
17505 // hide reminder
17506 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17507 data << uint32(0);
17508 data << uint32(0);
17509 GetSession()->SendPacket(&data);
17511 // instance is valid, reset homebind timer
17512 m_HomebindTimer = 0;
17514 else if (m_HomebindTimer > 0)
17516 if (time >= m_HomebindTimer)
17518 // teleport to homebind location
17519 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17521 else
17522 m_HomebindTimer -= time;
17524 else
17526 // instance is invalid, start homebind timer
17527 m_HomebindTimer = 60000;
17528 // send message to player
17529 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17530 data << m_HomebindTimer;
17531 data << uint32(1);
17532 GetSession()->SendPacket(&data);
17533 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17537 void Player::UpdatePvP(bool state, bool ovrride)
17539 if(!state || ovrride)
17541 SetPvP(state);
17542 if(Pet* pet = GetPet())
17543 pet->SetPvP(state);
17544 if(Unit* charmed = GetCharm())
17545 charmed->SetPvP(state);
17547 pvpInfo.endTimer = 0;
17549 else
17551 if(pvpInfo.endTimer != 0)
17552 pvpInfo.endTimer = time(NULL);
17553 else
17555 SetPvP(state);
17557 if(Pet* pet = GetPet())
17558 pet->SetPvP(state);
17559 if(Unit* charmed = GetCharm())
17560 charmed->SetPvP(state);
17565 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17567 SpellCooldown sc;
17568 sc.end = end_time;
17569 sc.itemid = itemid;
17570 m_spellCooldowns[spellid] = sc;
17573 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
17575 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
17576 return;
17578 // Get spell cooldown
17579 int32 cooldown = GetSpellRecoveryTime(spellInfo);
17580 // Apply spellmods
17581 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
17582 if (cooldown < 0)
17583 cooldown = 0;
17584 // Add cooldown
17585 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
17586 // Send activate
17587 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17588 data << spellInfo->Id;
17589 data << GetGUID();
17590 SendDirectMessage(&data);
17592 //slot to be excluded while counting
17593 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17595 if(!enchantmentcondition)
17596 return true;
17598 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17600 if(!Condition)
17601 return true;
17603 uint8 curcount[4] = {0, 0, 0, 0};
17605 //counting current equipped gem colors
17606 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17608 if(i == slot)
17609 continue;
17610 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17611 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17613 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17615 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17616 if(!enchant_id)
17617 continue;
17619 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17620 if(!enchantEntry)
17621 continue;
17623 uint32 gemid = enchantEntry->GemID;
17624 if(!gemid)
17625 continue;
17627 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17628 if(!gemProto)
17629 continue;
17631 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17632 if(!gemProperty)
17633 continue;
17635 uint8 GemColor = gemProperty->color;
17637 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17639 if(tmpcolormask & GemColor)
17640 ++curcount[b];
17646 bool activate = true;
17648 for(int i = 0; i < 5; i++)
17650 if(!Condition->Color[i])
17651 continue;
17653 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17655 // if have <CompareColor> use them as count, else use <value> from Condition
17656 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17658 switch(Condition->Comparator[i])
17660 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17661 activate &= (_cur_gem < _cmp_gem) ? true : false;
17662 break;
17663 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17664 activate &= (_cur_gem > _cmp_gem) ? true : false;
17665 break;
17666 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17667 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17668 break;
17672 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");
17674 return activate;
17677 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17679 //cycle all equipped items
17680 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17682 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17683 if(slot == exceptslot)
17684 continue;
17686 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17688 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17689 continue;
17691 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17693 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17694 if(!enchant_id)
17695 continue;
17697 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17698 if(!enchantEntry)
17699 continue;
17701 uint32 condition = enchantEntry->EnchantmentCondition;
17702 if(condition)
17704 //was enchant active with/without item?
17705 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17706 //should it now be?
17707 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17709 // ignore item gem conditions
17710 //if state changed, (dis)apply enchant
17711 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17718 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17719 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17721 //cycle all equipped items
17722 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17724 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17725 if(slot == exceptslot)
17726 continue;
17728 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17730 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17731 continue;
17733 //cycle all (gem)enchants
17734 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17736 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17737 if(!enchant_id) //if no enchant go to next enchant(slot)
17738 continue;
17740 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17741 if(!enchantEntry)
17742 continue;
17744 //only metagems to be (de)activated, so only enchants with condition
17745 uint32 condition = enchantEntry->EnchantmentCondition;
17746 if(condition)
17747 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17752 void Player::LeaveBattleground(bool teleportToEntryPoint)
17754 if(BattleGround *bg = GetBattleGround())
17756 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
17758 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17760 // call after remove to be sure that player resurrected for correct cast
17761 if(need_debuf)
17762 CastSpell(this, 26013, true); // Deserter
17766 bool Player::CanJoinToBattleground() const
17768 // check Deserter debuff
17769 if(GetDummyAura(26013))
17770 return false;
17772 return true;
17775 bool Player::CanReportAfkDueToLimit()
17777 // a player can complain about 15 people per 5 minutes
17778 if(m_bgAfkReportedCount >= 15)
17779 return false;
17780 ++m_bgAfkReportedCount;
17781 return true;
17784 ///This player has been blamed to be inactive in a battleground
17785 void Player::ReportedAfkBy(Player* reporter)
17787 BattleGround *bg = GetBattleGround();
17788 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17789 return;
17791 // check if player has 'Idle' or 'Inactive' debuff
17792 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17794 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17795 // 3 players have to complain to apply debuff
17796 if(m_bgAfkReporter.size() >= 3)
17798 // cast 'Idle' spell
17799 CastSpell(this, 43680, true);
17800 m_bgAfkReporter.clear();
17805 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17807 // gamemaster in GM mode see all, including ghosts
17808 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17809 return true;
17811 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17812 if (InBattleGround())
17814 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17815 return false;
17816 return true;
17819 // Live player see live player or dead player with not realized corpse
17820 if(pl->isAlive() || pl->m_deathTimer > 0)
17822 return isAlive() || m_deathTimer > 0;
17825 // Ghost see other friendly ghosts, that's for sure
17826 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17827 return true;
17829 // Dead player see live players near own corpse
17830 if(isAlive())
17832 Corpse *corpse = pl->GetCorpse();
17833 if(corpse)
17835 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17836 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17837 return true;
17841 // and not see any other
17842 return false;
17845 bool Player::IsVisibleGloballyFor( Player* u ) const
17847 if(!u)
17848 return false;
17850 // Always can see self
17851 if (u==this)
17852 return true;
17854 // Visible units, always are visible for all players
17855 if (GetVisibility() == VISIBILITY_ON)
17856 return true;
17858 // GMs are visible for higher gms (or players are visible for gms)
17859 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17860 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17862 // non faction visibility non-breakable for non-GMs
17863 if (GetVisibility() == VISIBILITY_OFF)
17864 return false;
17866 // non-gm stealth/invisibility not hide from global player lists
17867 return true;
17870 void Player::UpdateVisibilityOf(WorldObject* target)
17872 if(HaveAtClient(target))
17874 if(!target->isVisibleForInState(this,true))
17876 target->DestroyForPlayer(this);
17877 m_clientGUIDs.erase(target->GetGUID());
17879 #ifdef MANGOS_DEBUG
17880 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17881 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17882 #endif
17885 else
17887 if(target->isVisibleForInState(this,false))
17889 target->SendUpdateToPlayer(this);
17890 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17891 m_clientGUIDs.insert(target->GetGUID());
17893 #ifdef MANGOS_DEBUG
17894 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17895 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17896 #endif
17898 // target aura duration for caster show only if target exist at caster client
17899 // send data at target visibility change (adding to client)
17900 if(target!=this && target->isType(TYPEMASK_UNIT))
17901 SendAurasForTarget((Unit*)target);
17903 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17904 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17909 template<class T>
17910 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17912 s64.insert(target->GetGUID());
17915 template<>
17916 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17918 if(!target->IsTransport())
17919 s64.insert(target->GetGUID());
17922 template<class T>
17923 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17925 if(HaveAtClient(target))
17927 if(!target->isVisibleForInState(this,true))
17929 target->BuildOutOfRangeUpdateBlock(&data);
17930 m_clientGUIDs.erase(target->GetGUID());
17932 #ifdef MANGOS_DEBUG
17933 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17934 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));
17935 #endif
17938 else
17940 if(target->isVisibleForInState(this,false))
17942 visibleNow.insert(target);
17943 target->BuildUpdate(data_updates);
17944 target->BuildCreateUpdateBlockForPlayer(&data, this);
17945 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17947 #ifdef MANGOS_DEBUG
17948 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17949 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));
17950 #endif
17955 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17956 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17957 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17958 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17959 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17961 void Player::InitPrimaryProffesions()
17963 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17966 void Player::SendComboPoints()
17968 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17969 if (combotarget)
17971 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17972 data.append(combotarget->GetPackGUID());
17973 data << uint8(m_comboPoints);
17974 GetSession()->SendPacket(&data);
17978 void Player::AddComboPoints(Unit* target, int8 count)
17980 if(!count)
17981 return;
17983 // without combo points lost (duration checked in aura)
17984 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17986 if(target->GetGUID() == m_comboTarget)
17988 m_comboPoints += count;
17990 else
17992 if(m_comboTarget)
17993 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17994 target->RemoveComboPointHolder(GetGUIDLow());
17996 m_comboTarget = target->GetGUID();
17997 m_comboPoints = count;
17999 target->AddComboPointHolder(GetGUIDLow());
18002 if (m_comboPoints > 5) m_comboPoints = 5;
18003 if (m_comboPoints < 0) m_comboPoints = 0;
18005 SendComboPoints();
18008 void Player::ClearComboPoints()
18010 if(!m_comboTarget)
18011 return;
18013 // without combopoints lost (duration checked in aura)
18014 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18016 m_comboPoints = 0;
18018 SendComboPoints();
18020 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18021 target->RemoveComboPointHolder(GetGUIDLow());
18023 m_comboTarget = 0;
18026 void Player::SetGroup(Group *group, int8 subgroup)
18028 if(group == NULL) m_group.unlink();
18029 else
18031 // never use SetGroup without a subgroup unless you specify NULL for group
18032 assert(subgroup >= 0);
18033 m_group.link(group, this);
18034 m_group.setSubGroup((uint8)subgroup);
18038 void Player::SendInitialPacketsBeforeAddToMap()
18040 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
18041 data << uint32(0); // unknown, may be rest state time or experience
18042 GetSession()->SendPacket(&data);
18044 // Homebind
18045 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
18046 data << m_homebindX << m_homebindY << m_homebindZ;
18047 data << (uint32) m_homebindMapId;
18048 data << (uint32) m_homebindZoneId;
18049 GetSession()->SendPacket(&data);
18051 // SMSG_SET_PROFICIENCY
18052 // SMSG_UPDATE_AURA_DURATION
18054 // tutorial stuff
18055 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
18056 for (int i = 0; i < 8; ++i)
18057 data << uint32( GetTutorialInt(i) );
18058 GetSession()->SendPacket(&data);
18060 SendInitialSpells();
18062 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
18063 data << uint32(0); // count, for(count) uint32;
18064 GetSession()->SendPacket(&data);
18066 SendInitialActionButtons();
18067 SendInitialReputations();
18068 m_achievementMgr.SendAllAchievementData();
18069 UpdateZone(GetZoneId());
18070 SendInitWorldStates();
18072 // SMSG_SET_AURA_SINGLE
18074 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
18075 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18076 data << (float)0.01666667f; // game speed
18077 GetSession()->SendPacket( &data );
18079 data.Initialize(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18080 data << uint32(0x00000000); // on blizz it increments periodically
18081 GetSession()->SendPacket(&data);
18083 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18084 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
18085 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
18087 m_mover = this;
18090 void Player::SendInitialPacketsAfterAddToMap()
18092 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18093 data << uint32(0x00000000); // on blizz it increments periodically
18094 GetSession()->SendPacket(&data);
18096 CastSpell(this, 836, true); // LOGINEFFECT
18098 // set some aura effects that send packet to player client after add player to map
18099 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18100 // same auras state lost at far teleport, send it one more time in this case also
18101 static const AuraType auratypes[] =
18103 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18104 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18105 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18107 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18109 Unit::AuraList const& auraList = GetAurasByType(*itr);
18110 if(!auraList.empty())
18111 auraList.front()->ApplyModifier(true,true);
18114 if(HasAuraType(SPELL_AURA_MOD_STUN))
18115 SetMovement(MOVE_ROOT);
18117 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18118 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18120 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
18121 data.append(GetPackGUID());
18122 data << (uint32)2;
18123 SendMessageToSet(&data,true);
18126 SendAurasForTarget(this);
18127 SendEnchantmentDurations(); // must be after add to map
18128 SendItemDurations(); // must be after add to map
18131 void Player::SendUpdateToOutOfRangeGroupMembers()
18133 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18134 return;
18135 if(Group* group = GetGroup())
18136 group->UpdatePlayerOutOfRange(this);
18138 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18139 m_auraUpdateMask = 0;
18140 if(Pet *pet = GetPet())
18141 pet->ResetAuraUpdateMask();
18144 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18146 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18147 data << uint32(mapid);
18148 data << uint8(reason); // transfer abort reason
18149 switch(reason)
18151 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18152 case TRANSFER_ABORT_DIFFICULTY:
18153 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18154 data << uint8(arg);
18155 break;
18157 GetSession()->SendPacket(&data);
18160 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
18162 // type of warning, based on the time remaining until reset
18163 uint32 type;
18164 if(time > 3600)
18165 type = RAID_INSTANCE_WELCOME;
18166 else if(time > 900 && time <= 3600)
18167 type = RAID_INSTANCE_WARNING_HOURS;
18168 else if(time > 300 && time <= 900)
18169 type = RAID_INSTANCE_WARNING_MIN;
18170 else
18171 type = RAID_INSTANCE_WARNING_MIN_SOON;
18172 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
18173 data << uint32(type);
18174 data << uint32(mapid);
18175 data << uint32(time);
18176 GetSession()->SendPacket(&data);
18179 void Player::ApplyEquipCooldown( Item * pItem )
18181 for(int i = 0; i <5; ++i)
18183 _Spell const& spellData = pItem->GetProto()->Spells[i];
18185 // no spell
18186 if( !spellData.SpellId )
18187 continue;
18189 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18190 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18191 continue;
18193 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18195 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18196 data << pItem->GetGUID();
18197 data << uint32(spellData.SpellId);
18198 GetSession()->SendPacket(&data);
18202 void Player::resetSpells()
18204 // not need after this call
18205 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18207 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
18208 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
18211 // make full copy of map (spells removed and marked as deleted at another spell remove
18212 // and we can't use original map for safe iterative with visit each spell at loop end
18213 PlayerSpellMap smap = GetSpellMap();
18215 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18216 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
18218 learnDefaultSpells();
18219 learnQuestRewardedSpells();
18222 void Player::learnDefaultSpells()
18224 // learn default race/class spells
18225 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18226 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18228 uint32 tspell = *itr;
18229 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18230 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18231 addSpell(tspell,true,true,true,false);
18232 else // but send in normal spell in game learn case
18233 learnSpell(tspell,true);
18237 void Player::learnQuestRewardedSpells(Quest const* quest)
18239 uint32 spell_id = quest->GetRewSpellCast();
18241 // skip quests without rewarded spell
18242 if( !spell_id )
18243 return;
18245 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18246 if(!spellInfo)
18247 return;
18249 // check learned spells state
18250 bool found = false;
18251 for(int i=0; i < 3; ++i)
18253 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18255 found = true;
18256 break;
18260 // skip quests with not teaching spell or already known spell
18261 if(!found)
18262 return;
18264 // prevent learn non first rank unknown profession and second specialization for same profession)
18265 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18266 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18268 // not have first rank learned (unlearned prof?)
18269 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18270 if( !HasSpell(first_spell) )
18271 return;
18273 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18274 if(!learnedInfo)
18275 return;
18277 // specialization
18278 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18280 // search other specialization for same prof
18281 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18283 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18284 continue;
18286 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18287 if(!itrInfo)
18288 return;
18290 // compare only specializations
18291 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18292 continue;
18294 // compare same chain spells
18295 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18296 continue;
18298 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18299 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18300 return;
18305 CastSpell( this, spell_id, true);
18308 void Player::learnQuestRewardedSpells()
18310 // learn spells received from quest completing
18311 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18313 // skip no rewarded quests
18314 if(!itr->second.m_rewarded)
18315 continue;
18317 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18318 if( !quest )
18319 continue;
18321 learnQuestRewardedSpells(quest);
18325 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18327 uint32 raceMask = getRaceMask();
18328 uint32 classMask = getClassMask();
18329 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18331 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18332 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18333 continue;
18334 // Check race if set
18335 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18336 continue;
18337 // Check class if set
18338 if (pAbility->classmask && !(pAbility->classmask & classMask))
18339 continue;
18341 if (sSpellStore.LookupEntry(pAbility->spellId))
18343 // need unlearn spell
18344 if (skill_value < pAbility->req_skill_value)
18345 removeSpell(pAbility->spellId);
18346 // need learn
18347 else if (!IsInWorld())
18348 addSpell(pAbility->spellId,true,true,true,false);
18349 else
18350 learnSpell(pAbility->spellId,true);
18355 void Player::learnSkillRewardedSpells()
18357 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
18359 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
18360 continue;
18362 uint32 pskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i)));
18363 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
18365 learnSkillRewardedSpells(pskill, vskill);
18369 void Player::SendAurasForTarget(Unit *target)
18371 if(target->GetVisibleAuras()->empty()) // speedup things
18372 return;
18374 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18375 data.append(target->GetPackGUID());
18377 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18378 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18380 for(uint32 j = 0; j < 3; ++j)
18382 if(Aura *aura = target->GetAura(itr->second, j))
18384 data << uint8(aura->GetAuraSlot());
18385 data << uint32(aura->GetId());
18387 if(aura->GetId())
18389 uint8 auraFlags = aura->GetAuraFlags();
18390 // flags
18391 data << uint8(auraFlags);
18392 // level
18393 data << uint8(aura->GetAuraLevel());
18394 // charges
18395 data << uint8(aura->GetAuraCharges());
18397 if(!(auraFlags & AFLAG_NOT_CASTER))
18399 data << uint8(0); // packed GUID of someone (caster?)
18402 if(auraFlags & AFLAG_DURATION) // include aura duration
18404 data << uint32(aura->GetAuraMaxDuration());
18405 data << uint32(aura->GetAuraDuration());
18408 break;
18413 GetSession()->SendPacket(&data);
18416 void Player::SetDailyQuestStatus( uint32 quest_id )
18418 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18420 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18422 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18423 m_lastDailyQuestTime = time(NULL); // last daily quest time
18424 m_DailyQuestChanged = true;
18425 break;
18430 void Player::ResetDailyQuestStatus()
18432 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18433 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18435 // DB data deleted in caller
18436 m_DailyQuestChanged = false;
18437 m_lastDailyQuestTime = 0;
18440 BattleGround* Player::GetBattleGround() const
18442 if(GetBattleGroundId()==0)
18443 return NULL;
18445 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
18448 bool Player::InArena() const
18450 BattleGround *bg = GetBattleGround();
18451 if(!bg || !bg->isArena())
18452 return false;
18454 return true;
18457 bool Player::GetBGAccessByLevel(uint32 bgTypeId) const
18459 // get a template bg instead of running one
18460 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18461 if(!bg)
18462 return false;
18464 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18465 return false;
18467 return true;
18470 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id)
18472 if(queue_id < 1)
18473 return 0;
18475 if(queue_id >=7)
18476 queue_id = 7;
18478 return 10*(queue_id+1);
18481 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id)
18483 if(queue_id >=7)
18484 return 255; // hardcoded max level
18486 return 10*(queue_id+2)-1;
18489 uint32 Player::GetBattleGroundQueueIdFromLevel() const
18491 uint32 level = getLevel();
18492 if(level <= 19)
18493 return 0;
18494 else if (level > 79)
18495 return 7;
18496 else
18497 return level/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
18499 assert(bgTypeId < MAX_BATTLEGROUND_TYPES);
18500 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18501 assert(bg);
18502 return (getLevel() - bg->GetMinLevel()) / 10;*/
18505 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18507 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18508 if(!vendor_faction)
18509 return 1.0f;
18511 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18512 if(rank <= REP_NEUTRAL)
18513 return 1.0f;
18515 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18518 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18520 uint32 racemask = getRaceMask();
18521 uint32 classmask = getClassMask();
18523 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18524 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18525 if(lower==upper)
18526 return true;
18528 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18530 // skip wrong race skills
18531 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18532 continue;
18534 // skip wrong class skills
18535 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18536 continue;
18538 return true;
18541 return false;
18544 bool Player::HasQuestForGO(int32 GOId)
18546 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
18548 QuestStatusData qs=i->second;
18549 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18551 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
18552 if(!qinfo)
18553 continue;
18555 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18556 continue;
18558 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
18560 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18561 continue;
18563 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18564 return true;
18568 return false;
18571 void Player::UpdateForQuestsGO()
18573 if(m_clientGUIDs.empty())
18574 return;
18576 UpdateData udata;
18577 WorldPacket packet;
18578 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18580 if(IS_GAMEOBJECT_GUID(*itr))
18582 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18583 if(obj)
18584 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18587 udata.BuildPacket(&packet);
18588 GetSession()->SendPacket(&packet);
18591 void Player::SummonIfPossible(bool agree)
18593 if(!agree)
18595 m_summon_expire = 0;
18596 return;
18599 // expire and auto declined
18600 if(m_summon_expire < time(NULL))
18601 return;
18603 // stop taxi flight at summon
18604 if(isInFlight())
18606 GetMotionMaster()->MovementExpired();
18607 m_taxi.ClearTaxiDestinations();
18610 // drop flag at summon
18611 if(BattleGround *bg = GetBattleGround())
18612 bg->EventPlayerDroppedFlag(this);
18614 m_summon_expire = 0;
18616 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18619 void Player::RemoveItemDurations( Item *item )
18621 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18623 if(*itr==item)
18625 m_itemDuration.erase(itr);
18626 break;
18631 void Player::AddItemDurations( Item *item )
18633 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18635 m_itemDuration.push_back(item);
18636 item->SendTimeUpdate(this);
18640 void Player::AutoUnequipOffhandIfNeed()
18642 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18643 if(!offItem)
18644 return;
18646 // need unequip for 2h-weapon without TitanGrip
18647 if (!IsTwoHandUsed())
18648 return;
18650 ItemPosCountVec off_dest;
18651 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18652 if( off_msg == EQUIP_ERR_OK )
18654 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18655 StoreItem( off_dest, offItem, true );
18657 else
18659 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18663 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18665 if(spellInfo->EquippedItemClass < 0)
18666 return true;
18668 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18669 // for optimize check 2 used cases only
18670 switch(spellInfo->EquippedItemClass)
18672 case ITEM_CLASS_WEAPON:
18674 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18675 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18676 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18677 return true;
18678 break;
18680 case ITEM_CLASS_ARMOR:
18682 // tabard not have dependent spells
18683 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18684 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18685 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18686 return true;
18688 // shields can be equipped to offhand slot
18689 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18690 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18691 return true;
18693 // ranged slot can have some armor subclasses
18694 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18695 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18696 return true;
18698 break;
18700 default:
18701 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18702 break;
18705 return false;
18708 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18710 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18711 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18712 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18713 return true;
18715 // Check no reagent use mask
18716 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18717 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18718 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18719 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18720 return true;
18722 return false;
18725 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18727 AuraMap& auras = GetAuras();
18728 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
18730 Aura* aura = itr->second;
18732 // skip passive (passive item dependent spells work in another way) and not self applied auras
18733 SpellEntry const* spellInfo = aura->GetSpellProto();
18734 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18736 ++itr;
18737 continue;
18740 // skip if not item dependent or have alternative item
18741 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18743 ++itr;
18744 continue;
18747 // no alt item, remove aura, restart check
18748 RemoveAurasDueToSpell(aura->GetId());
18749 itr = auras.begin();
18752 // currently casted spells can be dependent from item
18753 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
18755 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18756 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18757 InterruptSpell(i);
18761 uint32 Player::GetResurrectionSpellId()
18763 // search priceless resurrection possibilities
18764 uint32 prio = 0;
18765 uint32 spell_id = 0;
18766 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18767 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18769 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18770 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18772 switch((*itr)->GetId())
18774 case 20707: spell_id = 3026; break; // rank 1
18775 case 20762: spell_id = 20758; break; // rank 2
18776 case 20763: spell_id = 20759; break; // rank 3
18777 case 20764: spell_id = 20760; break; // rank 4
18778 case 20765: spell_id = 20761; break; // rank 5
18779 case 27239: spell_id = 27240; break; // rank 6
18780 default:
18781 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
18782 continue;
18785 prio = 3;
18787 // Twisting Nether // prio: 2 (max)
18788 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18790 prio = 2;
18791 spell_id = 23700;
18795 // Reincarnation (passive spell) // prio: 1
18796 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18797 spell_id = 21169;
18799 return spell_id;
18802 // Used in triggers for check "Only to targets that grant experience or honor" req
18803 bool Player::isHonorOrXPTarget(Unit* pVictim)
18805 uint32 v_level = pVictim->getLevel();
18806 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18808 // Victim level less gray level
18809 if(v_level<=k_grey)
18810 return false;
18812 if(pVictim->GetTypeId() == TYPEID_UNIT)
18814 if (((Creature*)pVictim)->isTotem() ||
18815 ((Creature*)pVictim)->isPet() ||
18816 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18817 return false;
18819 return true;
18822 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18824 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18826 // prepare data for near group iteration (PvP and !PvP cases)
18827 uint32 xp = 0;
18828 bool honored_kill = false;
18830 if(Group *pGroup = GetGroup())
18832 uint32 count = 0;
18833 uint32 sum_level = 0;
18834 Player* member_with_max_level = NULL;
18835 Player* not_gray_member_with_max_level = NULL;
18837 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18839 if(member_with_max_level)
18841 /// not get Xp in PvP or no not gray players in group
18842 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18844 /// skip in check PvP case (for speed, not used)
18845 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18846 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18847 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18849 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18851 Player* pGroupGuy = itr->getSource();
18852 if(!pGroupGuy)
18853 continue;
18855 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18856 continue; // member (alive or dead) or his corpse at req. distance
18858 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18859 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18860 honored_kill = true;
18862 // xp and reputation only in !PvP case
18863 if(!PvP)
18865 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18867 // if is in dungeon then all receive full reputation at kill
18868 // rewarded any alive/dead/near_corpse group member
18869 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18871 // XP updated only for alive group member
18872 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18873 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18875 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18877 pGroupGuy->GiveXP(itr_xp, pVictim);
18878 if(Pet* pet = pGroupGuy->GetPet())
18879 pet->GivePetXP(itr_xp/2);
18882 // quest objectives updated only for alive group member or dead but with not released body
18883 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18885 // normal creature (not pet/etc) can be only in !PvP case
18886 if(pVictim->GetTypeId()==TYPEID_UNIT)
18887 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18893 else // if (!pGroup)
18895 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18897 // honor can be in PvP and !PvP (racial leader) cases
18898 if(RewardHonor(pVictim,1))
18899 honored_kill = true;
18901 // xp and reputation only in !PvP case
18902 if(!PvP)
18904 RewardReputation(pVictim,1);
18905 GiveXP(xp, pVictim);
18907 if(Pet* pet = GetPet())
18908 pet->GivePetXP(xp);
18910 // normal creature (not pet/etc) can be only in !PvP case
18911 if(pVictim->GetTypeId()==TYPEID_UNIT)
18912 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18915 return xp || honored_kill;
18918 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18920 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
18921 return true;
18923 if(isAlive())
18924 return false;
18926 Corpse* corpse = GetCorpse();
18927 if(!corpse)
18928 return false;
18930 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
18933 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18935 Item* item = GetWeaponForAttack(attType,true);
18937 // unarmed only with base attack
18938 if(attType != BASE_ATTACK && !item)
18939 return 0;
18941 // weapon skill or (unarmed for base attack)
18942 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
18943 return GetBaseSkillValue(skill);
18946 void Player::ResurectUsingRequestData()
18948 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18949 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18951 ResurrectPlayer(0.0f,false);
18953 if(GetMaxHealth() > m_resurrectHealth)
18954 SetHealth( m_resurrectHealth );
18955 else
18956 SetHealth( GetMaxHealth() );
18958 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18959 SetPower(POWER_MANA, m_resurrectMana );
18960 else
18961 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18963 SetPower(POWER_RAGE, 0 );
18965 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18967 SpawnCorpseBones();
18970 void Player::SetClientControl(Unit* target, uint8 allowMove)
18972 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18973 data.append(target->GetPackGUID());
18974 data << uint8(allowMove);
18975 GetSession()->SendPacket(&data);
18978 void Player::UpdateZoneDependentAuras( uint32 newZone )
18980 // remove new continent flight forms
18981 if( !IsAllowUseFlyMountsHere() )
18983 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18984 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18987 // Some spells applied at enter into zone (with subzones)
18988 // Human Illusion
18989 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18990 if ( newZone == 2367 ) // Old Hillsbrad Foothills
18992 uint32 spellid = 0;
18993 // all horde races
18994 if( GetTeam() == HORDE )
18995 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
18996 // and some alliance races
18997 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
18998 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
19000 if(spellid && !HasAura(spellid,0) )
19001 CastSpell(this,spellid,true);
19005 void Player::UpdateAreaDependentAuras( uint32 newArea )
19007 // remove auras from spells with area limitations
19008 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
19010 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19011 if(GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea)!=0)
19012 RemoveAura(iter);
19013 else
19014 ++iter;
19017 // some auras applied at subzone enter
19018 switch(newArea)
19020 // Dragonmaw Illusion
19021 case 3759: // Netherwing Ledge
19022 case 3939: // Dragonmaw Fortress
19023 case 3966: // Dragonmaw Base Camp
19024 if( GetDummyAura(40214) )
19026 if( !HasAura(40216,0) )
19027 CastSpell(this,40216,true);
19028 if( !HasAura(42016,0) )
19029 CastSpell(this,42016,true);
19031 break;
19032 // Dominion Over Acherus
19033 case 4281: // Acherus: The Ebon Hold
19034 case 4342: // Acherus: The Ebon Hold
19035 if( HasSpell(51721) )
19036 if( !HasAura(51721,0) )
19037 CastSpell(this,51721,true);
19038 break;
19042 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
19044 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19045 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19047 return copseReclaimDelay[0];
19050 time_t now = time(NULL);
19051 // 0..2 full period
19052 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
19053 return copseReclaimDelay[count];
19056 void Player::UpdateCorpseReclaimDelay()
19058 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
19060 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19061 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19062 return;
19064 time_t now = time(NULL);
19065 if(now < m_deathExpireTime)
19067 // full and partly periods 1..3
19068 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
19069 if(count < MAX_DEATH_COUNT)
19070 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19071 else
19072 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19074 else
19075 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19078 void Player::SendCorpseReclaimDelay(bool load)
19080 Corpse* corpse = GetCorpse();
19081 if(!corpse)
19082 return;
19084 uint32 delay;
19085 if(load)
19087 if(corpse->GetGhostTime() > m_deathExpireTime)
19088 return;
19090 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19092 uint32 count;
19093 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19094 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19096 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19097 if(count>=MAX_DEATH_COUNT)
19098 count = MAX_DEATH_COUNT-1;
19100 else
19101 count=0;
19103 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19105 time_t now = time(NULL);
19106 if(now >= expected_time)
19107 return;
19109 delay = expected_time-now;
19111 else
19112 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19114 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19115 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19116 data << uint32(delay*1000);
19117 GetSession()->SendPacket( &data );
19120 Player* Player::GetNextRandomRaidMember(float radius)
19122 Group *pGroup = GetGroup();
19123 if(!pGroup)
19124 return NULL;
19126 std::vector<Player*> nearMembers;
19127 nearMembers.reserve(pGroup->GetMembersCount());
19129 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19131 Player* Target = itr->getSource();
19133 // IsHostileTo check duel and controlled by enemy
19134 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19135 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19136 nearMembers.push_back(Target);
19139 if (nearMembers.empty())
19140 return NULL;
19142 uint32 randTarget = urand(0,nearMembers.size()-1);
19143 return nearMembers[randTarget];
19146 PartyResult Player::CanUninviteFromGroup() const
19148 const Group* grp = GetGroup();
19149 if(!grp)
19150 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19152 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19153 return PARTY_RESULT_YOU_NOT_LEADER;
19155 if(InBattleGround())
19156 return PARTY_RESULT_INVITE_RESTRICTED;
19158 return PARTY_RESULT_OK;
19161 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19163 float water_z = m->GetWaterLevel(x,y);
19164 float terrain_z = m->GetHeight(x,y,z, false); // use .map base surface height
19165 uint8 flag1 = m->GetTerrainType(x,y);
19167 //!Underwater check, not in water if underground or above water level - take UC royal quater for example
19168 if (terrain_z <= INVALID_HEIGHT || z < (terrain_z-2) || z > (water_z - 2) )
19169 m_isunderwater &= ~UNDERWATER_INWATER;
19170 else if ((z < (water_z - 2)) && (flag1 & 0x01))
19171 m_isunderwater |= UNDERWATER_INWATER;
19173 //!in lava check, anywhere under lava level
19174 if ((terrain_z <= INVALID_HEIGHT || z < (terrain_z - 0)) && (flag1 == 0x00) && IsInWater())
19175 m_isunderwater |= UNDERWATER_INLAVA;
19176 else
19177 m_isunderwater &= ~UNDERWATER_INLAVA;
19180 void Player::SetCanParry( bool value )
19182 if(m_canParry==value)
19183 return;
19185 m_canParry = value;
19186 UpdateParryPercentage();
19189 void Player::SetCanBlock( bool value )
19191 if(m_canBlock==value)
19192 return;
19194 m_canBlock = value;
19195 UpdateBlockPercentage();
19198 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19200 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19201 if(itr->pos == pos)
19202 return true;
19204 return false;
19207 bool Player::isAllowUseBattleGroundObject()
19209 return ( //InBattleGround() && // in battleground - not need, check in other cases
19210 !IsMounted() && // not mounted
19211 !HasStealthAura() && // not stealthed
19212 !HasInvisibilityAura() && // not invisible
19213 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19214 isAlive() // live player
19218 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19220 uint32 level = getLevel();
19222 if(level > GT_MAX_LEVEL)
19223 level = GT_MAX_LEVEL; // max level in this dbc
19225 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19226 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19227 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19229 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19230 return 0;
19232 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19234 if(!bsc) // shouldn't happen
19235 return 0xFFFFFFFF;
19237 float cost = 0;
19239 if(hairstyle != newhairstyle)
19240 cost += bsc->cost; // full price
19242 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19243 cost += bsc->cost * 0.5f; // +1/2 of price
19245 if(facialhair != newfacialhair)
19246 cost += bsc->cost * 0.75f; // +3/4 of price
19248 return uint32(cost);
19251 void Player::InitGlyphsForLevel()
19253 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19254 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19255 if(gs->Order)
19256 SetGlyphSlot(gs->Order - 1, gs->Id);
19258 uint32 level = getLevel();
19259 uint32 value = 0;
19261 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19262 if(level >= 15)
19263 value |= (0x01 | 0x02);
19264 if(level >= 30)
19265 value |= 0x04;
19266 if(level >= 50)
19267 value |= 0x08;
19268 if(level >= 70)
19269 value |= 0x10;
19270 if(level >= 80)
19271 value |= 0x20;
19273 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19276 void Player::EnterVehicle(Vehicle *vehicle)
19278 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19279 if(!ve)
19280 return;
19282 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19283 if(!veSeat)
19284 return;
19286 vehicle->SetCharmerGUID(GetGUID());
19287 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19288 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19289 vehicle->setFaction(getFaction());
19291 SetCharm(vehicle); // charm
19292 SetFarSightGUID(vehicle->GetGUID()); // set view
19294 SetClientControl(vehicle, 1); // redirect controls to vehicle
19296 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19297 GetSession()->SendPacket(&data);
19299 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19300 data.append(GetPackGUID());
19301 data << uint32(0); // counter?
19302 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19303 data << uint16(0); // special flags
19304 data << uint32(getMSTime()); // time
19305 data << vehicle->GetPositionX(); // x
19306 data << vehicle->GetPositionY(); // y
19307 data << vehicle->GetPositionZ(); // z
19308 data << vehicle->GetOrientation(); // o
19309 // transport part, TODO: load/calculate seat offsets
19310 data << uint64(vehicle->GetGUID()); // transport guid
19311 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19312 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19313 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19314 data << float(0); // transport orientation
19315 data << uint32(getMSTime()); // transport time
19316 data << uint8(0); // seat
19317 // end of transport part
19318 data << uint32(0); // fall time
19319 GetSession()->SendPacket(&data);
19321 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
19322 data << uint64(vehicle->GetGUID());
19323 data << uint32(0x00000000);
19324 data << uint32(0x00000000);
19325 data << uint32(0x00000101);
19327 for(uint32 i = 0; i < 10; ++i)
19328 data << uint16(0) << uint8(0) << uint8(i+8);
19330 data << uint8(0);
19331 data << uint8(0);
19332 GetSession()->SendPacket(&data);
19335 void Player::ExitVehicle(Vehicle *vehicle)
19337 vehicle->SetCharmerGUID(0);
19338 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19339 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19340 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19342 SetCharm(NULL);
19343 SetFarSightGUID(0);
19345 SetClientControl(vehicle, 0);
19347 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19348 data.append(GetPackGUID());
19349 data << uint32(0); // counter?
19350 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19351 data << uint16(0x40); // special flags
19352 data << uint32(getMSTime()); // time
19353 data << vehicle->GetPositionX(); // x
19354 data << vehicle->GetPositionY(); // y
19355 data << vehicle->GetPositionZ(); // z
19356 data << vehicle->GetOrientation(); // o
19357 data << uint32(0); // fall time
19358 GetSession()->SendPacket(&data);
19360 data.Initialize(SMSG_PET_SPELLS, 8+4);
19361 data << uint64(0);
19362 data << uint32(0);
19363 GetSession()->SendPacket(&data);
19365 // only for flyable vehicles?
19366 CastSpell(this, 45472, true); // Parachute
19369 bool Player::HasTitle(uint32 bitIndex)
19371 if (bitIndex > 128)
19372 return false;
19374 uint32 fieldIndexOffset = bitIndex/32;
19375 uint32 flag = 1 << (bitIndex%32);
19376 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19379 void Player::SetTitle(CharTitlesEntry const* title)
19381 uint32 fieldIndexOffset = title->bit_index/32;
19382 uint32 flag = 1 << (title->bit_index%32);
19383 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19386 void Player::ConvertRune(uint8 index, uint8 newType)
19388 SetCurrentRune(index, newType);
19390 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19391 data << uint8(index);
19392 data << uint8(newType);
19393 GetSession()->SendPacket(&data);
19396 void Player::ResyncRunes(uint8 count)
19398 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19399 for(uint32 i = 0; i < count; ++i)
19401 data << uint8(GetCurrentRune(i)); // rune type
19402 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19404 GetSession()->SendPacket(&data);
19407 void Player::AddRunePower(uint8 index)
19409 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19410 data << uint32(1 << index); // mask (0x00-0x3F probably)
19411 GetSession()->SendPacket(&data);
19414 void Player::InitRunes()
19416 if(getClass() != CLASS_DEATH_KNIGHT)
19417 return;
19419 m_runes = new Runes;
19421 m_runes->runeState = 0;
19423 for(uint32 i = 0; i < MAX_RUNES; ++i)
19425 SetBaseRune(i, i / 2); // init base types
19426 SetCurrentRune(i, i / 2); // init current types
19427 SetRuneCooldown(i, 0); // reset cooldowns
19428 m_runes->SetRuneState(i);
19431 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19432 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19435 void Player::AutoStoreLootItem(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store)
19437 Loot loot;
19438 loot.FillLoot (loot_id,store,this);
19439 if(loot.items.empty ())
19440 return;
19441 LootItem const* lootItem = &loot.items[0];
19443 ItemPosCountVec dest;
19444 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19445 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19446 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19447 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19448 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19449 if(msg != EQUIP_ERR_OK)
19450 return;
19452 StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19455 uint32 Player::CalculateTalentsPoints() const
19457 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19459 if(getClass() != CLASS_DEATH_KNIGHT)
19460 return base_talent;
19462 uint32 talentPointsForLevel =
19463 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19464 + m_questRewardTalentCount;
19466 if(talentPointsForLevel > base_talent)
19467 talentPointsForLevel = base_talent;
19469 return talentPointsForLevel;
19472 bool Player::IsAllowUseFlyMountsHere() const
19474 if (isGameMaster())
19475 return true;
19477 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19478 return v_map == 530 || v_map == 571 && HasSpell(54197);