[7731] Some code cleanups, warrning fixes.
[getmangos.git] / src / game / Player.cpp
blobf4bd869a13aab77ea0f02161403beced32de6d55
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "SpellMgr.h"
25 #include "World.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #include "UpdateMask.h"
29 #include "Player.h"
30 #include "Vehicle.h"
31 #include "SkillDiscovery.h"
32 #include "QuestDef.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
35 #include "Channel.h"
36 #include "ChannelMgr.h"
37 #include "MapManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "GridNotifiers.h"
41 #include "GridNotifiersImpl.h"
42 #include "CellImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "CreatureAI.h"
46 #include "Formulas.h"
47 #include "Group.h"
48 #include "Guild.h"
49 #include "Pet.h"
50 #include "Util.h"
51 #include "Transports.h"
52 #include "Weather.h"
53 #include "BattleGround.h"
54 #include "BattleGroundMgr.h"
55 #include "ArenaTeam.h"
56 #include "Chat.h"
57 #include "Database/DatabaseImpl.h"
58 #include "Spell.h"
59 #include "SocialMgr.h"
60 #include "AchievementMgr.h"
62 #include <cmath>
64 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
78 enum CharacterFlags
80 CHARACTER_FLAG_NONE = 0x00000000,
81 CHARACTER_FLAG_UNK1 = 0x00000001,
82 CHARACTER_FLAG_UNK2 = 0x00000002,
83 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
84 CHARACTER_FLAG_UNK4 = 0x00000008,
85 CHARACTER_FLAG_UNK5 = 0x00000010,
86 CHARACTER_FLAG_UNK6 = 0x00000020,
87 CHARACTER_FLAG_UNK7 = 0x00000040,
88 CHARACTER_FLAG_UNK8 = 0x00000080,
89 CHARACTER_FLAG_UNK9 = 0x00000100,
90 CHARACTER_FLAG_UNK10 = 0x00000200,
91 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
92 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
93 CHARACTER_FLAG_UNK13 = 0x00001000,
94 CHARACTER_FLAG_GHOST = 0x00002000,
95 CHARACTER_FLAG_RENAME = 0x00004000,
96 CHARACTER_FLAG_UNK16 = 0x00008000,
97 CHARACTER_FLAG_UNK17 = 0x00010000,
98 CHARACTER_FLAG_UNK18 = 0x00020000,
99 CHARACTER_FLAG_UNK19 = 0x00040000,
100 CHARACTER_FLAG_UNK20 = 0x00080000,
101 CHARACTER_FLAG_UNK21 = 0x00100000,
102 CHARACTER_FLAG_UNK22 = 0x00200000,
103 CHARACTER_FLAG_UNK23 = 0x00400000,
104 CHARACTER_FLAG_UNK24 = 0x00800000,
105 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
106 CHARACTER_FLAG_DECLINED = 0x02000000,
107 CHARACTER_FLAG_UNK27 = 0x04000000,
108 CHARACTER_FLAG_UNK28 = 0x08000000,
109 CHARACTER_FLAG_UNK29 = 0x10000000,
110 CHARACTER_FLAG_UNK30 = 0x20000000,
111 CHARACTER_FLAG_UNK31 = 0x40000000,
112 CHARACTER_FLAG_UNK32 = 0x80000000
115 // corpse reclaim times
116 #define DEATH_EXPIRE_STEP (5*MINUTE)
117 #define MAX_DEATH_COUNT 3
119 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
121 //== PlayerTaxi ================================================
123 PlayerTaxi::PlayerTaxi()
125 // Taxi nodes
126 memset(m_taximask, 0, sizeof(m_taximask));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
131 // class specific initial known nodes
132 switch(chrClass)
134 case CLASS_DEATH_KNIGHT:
136 for(int i = 0; i < TaxiMaskSize; ++i)
137 m_taximask[i] |= sOldContinentsNodesMask[i];
138 break;
142 // race specific initial known nodes: capital and taxi hub masks
143 switch(race)
145 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
146 case RACE_ORC: SetTaximaskNode(23); break; // Orc
147 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
148 case RACE_NIGHTELF: SetTaximaskNode(26);
149 SetTaximaskNode(27); break; // Night Elf
150 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
151 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
152 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
153 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
154 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
155 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
158 // new continent starting masks (It will be accessible only at new map)
159 switch(Player::TeamForRace(race))
161 case ALLIANCE: SetTaximaskNode(100); break;
162 case HORDE: SetTaximaskNode(99); break;
164 // level dependent taxi hubs
165 if(level>=68)
166 SetTaximaskNode(213); //Shattered Sun Staging Area
169 void PlayerTaxi::LoadTaxiMask(const char* data)
171 Tokens tokens = StrSplit(data, " ");
173 int index;
174 Tokens::iterator iter;
175 for (iter = tokens.begin(), index = 0;
176 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
178 // load and set bits only for existed taxi nodes
179 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
183 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
185 if(all)
187 for (uint8 i=0; i<TaxiMaskSize; ++i)
188 data << uint32(sTaxiNodesMask[i]); // all existed nodes
190 else
192 for (uint8 i=0; i<TaxiMaskSize; ++i)
193 data << uint32(m_taximask[i]); // known nodes
197 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
199 ClearTaxiDestinations();
201 Tokens tokens = StrSplit(values," ");
203 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
205 uint32 node = uint32(atol(iter->c_str()));
206 AddTaxiDestination(node);
209 if(m_TaxiDestinations.empty())
210 return true;
212 // Check integrity
213 if(m_TaxiDestinations.size() < 2)
214 return false;
216 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
218 uint32 cost;
219 uint32 path;
220 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
221 if(!path)
222 return false;
225 // can't load taxi path without mount set (quest taxi path?)
226 if(!objmgr.GetTaxiMount(GetTaxiSource(),team))
227 return false;
229 return true;
232 std::string PlayerTaxi::SaveTaxiDestinationsToString()
234 if(m_TaxiDestinations.empty())
235 return "";
237 std::ostringstream ss;
239 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
240 ss << m_TaxiDestinations[i] << " ";
242 return ss.str();
245 uint32 PlayerTaxi::GetCurrentTaxiPath() const
247 if(m_TaxiDestinations.size() < 2)
248 return 0;
250 uint32 path;
251 uint32 cost;
253 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
255 return path;
258 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
260 ss << "'";
261 for(int i = 0; i < TaxiMaskSize; ++i)
262 ss << taxi.m_taximask[i] << " ";
263 ss << "'";
264 return ss;
267 //== Player ====================================================
269 UpdateMask Player::updateVisualBits;
271 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
273 m_transport = 0;
275 m_speakTime = 0;
276 m_speakCount = 0;
278 m_objectType |= TYPEMASK_PLAYER;
279 m_objectTypeId = TYPEID_PLAYER;
281 m_valuesCount = PLAYER_END;
283 m_session = session;
285 m_divider = 0;
287 m_ExtraFlags = 0;
288 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
289 SetAcceptTicket(true);
291 // players always accept
292 if(GetSession()->GetSecurity() == SEC_PLAYER)
293 SetAcceptWhispers(true);
295 m_curSelection = 0;
296 m_lootGuid = 0;
298 m_comboTarget = 0;
299 m_comboPoints = 0;
301 m_usedTalentCount = 0;
302 m_questRewardTalentCount = 0;
304 m_regenTimer = 0;
305 m_weaponChangeTimer = 0;
307 m_zoneUpdateId = 0;
308 m_zoneUpdateTimer = 0;
310 m_areaUpdateId = 0;
312 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
314 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
315 // this must help in case next save after mass player load after server startup
316 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
318 clearResurrectRequestData();
320 m_SpellModRemoveCount = 0;
322 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
324 m_social = NULL;
326 // group is initialized in the reference constructor
327 SetGroupInvite(NULL);
328 m_groupUpdateMask = 0;
329 m_auraUpdateMask = 0;
331 duel = NULL;
333 m_GuildIdInvited = 0;
334 m_ArenaTeamIdInvited = 0;
336 m_atLoginFlags = AT_LOGIN_NONE;
338 mSemaphoreTeleport_Near = false;
339 mSemaphoreTeleport_Far = false;
341 pTrader = 0;
342 ClearTrade();
344 m_cinematic = 0;
346 PlayerTalkClass = new PlayerMenu( GetSession() );
347 m_currentBuybackSlot = BUYBACK_SLOT_START;
349 for ( int aX = 0 ; aX < 8 ; aX++ )
350 m_Tutorials[ aX ] = 0x00;
351 m_TutorialsChanged = false;
353 m_DailyQuestChanged = false;
354 m_lastDailyQuestTime = 0;
356 for (int i=0; i<MAX_TIMERS; ++i)
357 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
359 m_MirrorTimerFlags = UNDERWATER_NONE;
360 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
361 m_isInWater = false;
362 m_drunkTimer = 0;
363 m_drunk = 0;
364 m_restTime = 0;
365 m_deathTimer = 0;
366 m_deathExpireTime = 0;
368 m_swingErrorMsg = 0;
370 m_DetectInvTimer = 1*IN_MILISECONDS;
372 m_bgBattleGroundID = 0;
373 m_bgTypeID = BATTLEGROUND_TYPE_NONE;
374 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
376 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
377 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
379 m_bgTeam = 0;
381 m_logintime = time(NULL);
382 m_Last_tick = m_logintime;
383 m_WeaponProficiency = 0;
384 m_ArmorProficiency = 0;
385 m_canParry = false;
386 m_canBlock = false;
387 m_canDualWield = false;
388 m_canTitanGrip = false;
389 m_ammoDPS = 0.0f;
391 m_temporaryUnsummonedPetNumber = 0;
392 //cache for UNIT_CREATED_BY_SPELL to allow
393 //returning reagents for temporarily removed pets
394 //when dying/logging out
395 m_oldpetspell = 0;
397 ////////////////////Rest System/////////////////////
398 time_inn_enter=0;
399 inn_pos_mapid=0;
400 inn_pos_x=0;
401 inn_pos_y=0;
402 inn_pos_z=0;
403 m_rest_bonus=0;
404 rest_type=REST_TYPE_NO;
405 ////////////////////Rest System/////////////////////
407 m_mailsLoaded = false;
408 m_mailsUpdated = false;
409 unReadMails = 0;
410 m_nextMailDelivereTime = 0;
412 m_resetTalentsCost = 0;
413 m_resetTalentsTime = 0;
414 m_itemUpdateQueueBlocked = false;
416 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
417 m_forced_speed_changes[i] = 0;
419 m_stableSlots = 0;
421 /////////////////// Instance System /////////////////////
423 m_HomebindTimer = 0;
424 m_InstanceValid = true;
425 m_dungeonDifficulty = DIFFICULTY_NORMAL;
427 m_lastPotionId = 0;
429 for (int i = 0; i < BASEMOD_END; ++i)
431 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
432 m_auraBaseMod[i][PCT_MOD] = 1.0f;
435 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
436 m_baseRatingValue[i] = 0;
438 m_baseSpellDamage = 0;
439 m_baseSpellHealing = 0;
440 m_baseFeralAP = 0;
441 m_baseManaRegen = 0;
443 // Honor System
444 m_lastHonorUpdateTime = time(NULL);
446 // Player summoning
447 m_summon_expire = 0;
448 m_summon_mapid = 0;
449 m_summon_x = 0.0f;
450 m_summon_y = 0.0f;
451 m_summon_z = 0.0f;
453 //Default movement to run mode
454 m_unit_movement_flags = 0;
456 m_mover = this;
458 m_miniPet = 0;
459 m_bgAfkReportedTimer = 0;
460 m_contestedPvPTimer = 0;
462 m_declinedname = NULL;
463 m_runes = NULL;
465 m_lastFallTime = 0;
466 m_lastFallZ = 0;
469 Player::~Player ()
471 CleanupsBeforeDelete();
473 // it must be unloaded already in PlayerLogout and accessed only for loggined player
474 //m_social = NULL;
476 // Note: buy back item already deleted from DB when player was saved
477 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
479 if(m_items[i])
480 delete m_items[i];
482 CleanupChannels();
484 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
485 delete itr->second;
487 //all mailed items should be deleted, also all mail should be deallocated
488 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
489 delete *itr;
491 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
492 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
494 delete PlayerTalkClass;
496 if (m_transport)
498 m_transport->RemovePassenger(this);
501 for(size_t x = 0; x < ItemSetEff.size(); x++)
502 if(ItemSetEff[x])
503 delete ItemSetEff[x];
505 // clean up player-instance binds, may unload some instance saves
506 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
507 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
508 itr->second.save->RemovePlayer(this);
510 delete m_declinedname;
511 delete m_runes;
514 void Player::CleanupsBeforeDelete()
516 if(m_uint32Values) // only for fully created Object
518 TradeCancel(false);
519 DuelComplete(DUEL_INTERUPTED);
521 Unit::CleanupsBeforeDelete();
524 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 )
526 //FIXME: outfitId not used in player creating
528 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
530 m_name = name;
532 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
533 if(!info)
535 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
536 return false;
539 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
540 m_items[i] = NULL;
542 m_race = race;
543 m_class = class_;
545 SetMapId(info->mapId);
546 Relocate(info->positionX,info->positionY,info->positionZ);
548 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
549 if(!cEntry)
551 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
552 return false;
555 uint8 powertype = cEntry->powerType;
557 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
558 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
560 switch(gender)
562 case GENDER_FEMALE:
563 SetDisplayId(info->displayId_f );
564 SetNativeDisplayId(info->displayId_f );
565 break;
566 case GENDER_MALE:
567 SetDisplayId(info->displayId_m );
568 SetNativeDisplayId(info->displayId_m );
569 break;
570 default:
571 sLog.outError("Invalid gender %u for player",gender);
572 return false;
573 break;
576 setFactionForRace(m_race);
578 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
580 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
581 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
582 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
583 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
584 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
585 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
587 // -1 is default value
588 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
590 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
591 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
592 SetByteValue(PLAYER_BYTES_3, 0, gender);
594 SetUInt32Value( PLAYER_GUILDID, 0 );
595 SetUInt32Value( PLAYER_GUILDRANK, 0 );
596 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
598 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
599 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
600 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
601 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
602 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
603 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
604 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
606 // set starting level
607 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
608 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
609 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
611 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
613 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
614 if(gm_level > start_level)
615 start_level = gm_level;
618 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
620 InitRunes();
622 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
623 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
624 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
626 // Played time
627 m_Last_tick = time(NULL);
628 m_Played_time[0] = 0;
629 m_Played_time[1] = 0;
631 // base stats and related field values
632 InitStatsForLevel();
633 InitTaxiNodesForLevel();
634 InitGlyphsForLevel();
635 InitTalentForLevel();
636 InitPrimaryProffesions(); // to max set before any spell added
638 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
639 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
640 SetHealth(GetMaxHealth());
641 if (getPowerType()==POWER_MANA)
643 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
644 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
647 if(getPowerType() == POWER_RUNIC_POWER)
649 SetPower(POWER_RUNE, 8);
650 SetMaxPower(POWER_RUNE, 8);
651 SetPower(POWER_RUNIC_POWER, 0);
652 SetMaxPower(POWER_RUNIC_POWER, 1000);
655 // original spells
656 learnDefaultSpells();
658 // original action bar
659 std::list<uint16>::const_iterator action_itr[4];
660 for(int i=0; i<4; ++i)
661 action_itr[i] = info->action[i].begin();
663 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
665 uint16 taction[4];
666 for(int i=0; i<4 ;++i)
667 taction[i] = (*action_itr[i]);
669 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
671 for(int i=0; i<4 ;++i)
672 ++action_itr[i];
675 // original items
676 CharStartOutfitEntry const* oEntry = NULL;
677 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
679 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
681 if(entry->RaceClassGender == RaceClassGender)
683 oEntry = entry;
684 break;
689 if(oEntry)
691 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
693 if(oEntry->ItemId[j] <= 0)
694 continue;
696 uint32 item_id = oEntry->ItemId[j];
699 // Hack for not existed item id in dbc 3.0.3
700 if(item_id==40582)
701 continue;
703 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
704 if(!iProto)
706 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
707 continue;
710 // max stack by default (mostly 1), 1 for infinity stackable
711 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
713 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
715 switch(iProto->Spells[0].SpellCategory)
717 case 11: // food
718 if(iProto->Stackable > 4)
719 count = 4;
720 break;
721 case 59: // drink
722 if(iProto->Stackable > 2)
723 count = 2;
724 break;
728 StoreNewItemInBestSlots(item_id, count);
732 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
733 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
735 // bags and main-hand weapon must equipped at this moment
736 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
737 // or ammo not equipped in special bag
738 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
740 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
742 uint16 eDest;
743 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
744 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
745 if( msg == EQUIP_ERR_OK )
747 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
748 EquipItem( eDest, pItem, true);
750 // move other items to more appropriate slots (ammo not equipped in special bag)
751 else
753 ItemPosCountVec sDest;
754 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
755 if( msg == EQUIP_ERR_OK )
757 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
758 pItem = StoreItem( sDest, pItem, true);
761 // if this is ammo then use it
762 msg = CanUseAmmo( pItem->GetEntry() );
763 if( msg == EQUIP_ERR_OK )
764 SetAmmo( pItem->GetEntry() );
768 // all item positions resolved
770 return true;
773 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
775 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
777 // attempt equip by one
778 while(titem_amount > 0)
780 uint16 eDest;
781 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
782 if( msg != EQUIP_ERR_OK )
783 break;
785 EquipNewItem( eDest, titem_id, true);
786 AutoUnequipOffhandIfNeed();
787 --titem_amount;
790 if(titem_amount == 0)
791 return true; // equipped
793 // attempt store
794 ItemPosCountVec sDest;
795 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
796 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
797 if( msg == EQUIP_ERR_OK )
799 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
800 return true; // stored
803 // item can't be added
804 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
805 return false;
808 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
810 if (MaxValue == DISABLED_MIRROR_TIMER)
812 if (CurrentValue!=DISABLED_MIRROR_TIMER)
813 StopMirrorTimer(Type);
814 return;
816 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
817 data << (uint32)Type;
818 data << CurrentValue;
819 data << MaxValue;
820 data << Regen;
821 data << (uint8)0;
822 data << (uint32)0; // spell id
823 GetSession()->SendPacket( &data );
826 void Player::StopMirrorTimer(MirrorTimerType Type)
828 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
829 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
830 data << (uint32)Type;
831 GetSession()->SendPacket( &data );
834 void Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
836 if(!isAlive() || isGameMaster())
837 return;
839 // Absorb, resist some environmental damage type
840 uint32 absorb = 0;
841 uint32 resist = 0;
842 if (type == DAMAGE_LAVA)
843 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
844 else if (type == DAMAGE_SLIME)
845 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
847 damage-=absorb+resist;
849 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
850 data << uint64(GetGUID());
851 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
852 data << uint32(damage);
853 data << uint32(absorb);
854 data << uint32(resist);
855 SendMessageToSet(&data, true);
857 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
859 if(!isAlive())
861 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
863 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
864 DurabilityLossAll(0.10f,false);
865 // durability lost message
866 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
867 GetSession()->SendPacket(&data2);
870 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
874 int32 Player::getMaxTimer(MirrorTimerType timer)
876 switch (timer)
878 case FATIGUE_TIMER:
879 return MINUTE*IN_MILISECONDS;
880 case BREATH_TIMER:
882 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
883 return DISABLED_MIRROR_TIMER;
884 int32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS;
885 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
886 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
887 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
888 return UnderWaterTime;
890 case FIRE_TIMER:
892 if (!isAlive())
893 return DISABLED_MIRROR_TIMER;
894 return 1*IN_MILISECONDS;
896 default:
897 return 0;
899 return 0;
902 void Player::UpdateMirrorTimers()
904 // Desync flags for update on next HandleDrowning
905 if (m_MirrorTimerFlags)
906 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
909 void Player::HandleDrowning(uint32 time_diff)
911 if (!m_MirrorTimerFlags)
912 return;
914 // In water
915 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
917 // Breath timer not activated - activate it
918 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
920 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
921 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
923 else // If activated - do tick
925 m_MirrorTimer[BREATH_TIMER]-=time_diff;
926 // Timer limit - need deal damage
927 if (m_MirrorTimer[BREATH_TIMER] < 0)
929 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
930 // Calculate and deal damage
931 // TODO: Check this formula
932 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
933 EnvironmentalDamage(DAMAGE_DROWNING, damage);
935 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
936 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
939 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
941 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
942 // Need breath regen
943 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
944 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
945 StopMirrorTimer(BREATH_TIMER);
946 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
947 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
950 // In dark water
951 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
953 // Fatigue timer not activated - activate it
954 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
956 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
957 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
959 else
961 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
962 // Timer limit - need deal damage or teleport ghost to graveyard
963 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
965 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
966 if (isAlive()) // Calculate and deal damage
968 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
969 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
971 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
972 RepopAtGraveyard();
974 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
975 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
978 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
980 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
981 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
982 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
983 StopMirrorTimer(FATIGUE_TIMER);
984 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
985 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
988 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
990 // Breath timer not activated - activate it
991 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
992 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
993 else
995 m_MirrorTimer[FIRE_TIMER]-=time_diff;
996 if (m_MirrorTimer[FIRE_TIMER] < 0)
998 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
999 // Calculate and deal damage
1000 // TODO: Check this formula
1001 uint32 damage = urand(600, 700);
1002 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
1003 EnvironmentalDamage(DAMAGE_LAVA, damage);
1004 else
1005 EnvironmentalDamage(DAMAGE_SLIME, damage);
1009 else
1010 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
1012 // Recheck timers flag
1013 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1014 for (int i = 0; i< MAX_TIMERS; ++i)
1015 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1017 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1018 break;
1020 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1023 ///The player sobers by 256 every 10 seconds
1024 void Player::HandleSobering()
1026 m_drunkTimer = 0;
1028 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1029 SetDrunkValue(drunk);
1032 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1034 if(value >= 23000)
1035 return DRUNKEN_SMASHED;
1036 if(value >= 12800)
1037 return DRUNKEN_DRUNK;
1038 if(value & 0xFFFE)
1039 return DRUNKEN_TIPSY;
1040 return DRUNKEN_SOBER;
1043 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1045 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1047 m_drunk = newDrunkenValue;
1048 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1050 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1052 // special drunk invisibility detection
1053 if(newDrunkenState >= DRUNKEN_DRUNK)
1054 m_detectInvisibilityMask |= (1<<6);
1055 else
1056 m_detectInvisibilityMask &= ~(1<<6);
1058 if(newDrunkenState == oldDrunkenState)
1059 return;
1061 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1062 data << uint64(GetGUID());
1063 data << uint32(newDrunkenState);
1064 data << uint32(itemId);
1066 SendMessageToSet(&data, true);
1069 void Player::Update( uint32 p_time )
1071 if(!IsInWorld())
1072 return;
1074 // undelivered mail
1075 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1077 SendNewMail();
1078 ++unReadMails;
1080 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1081 m_nextMailDelivereTime = 0;
1084 Unit::Update( p_time );
1086 // update player only attacks
1087 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1089 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1092 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1094 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1097 time_t now = time (NULL);
1099 UpdatePvPFlag(now);
1101 UpdateContestedPvP(p_time);
1103 UpdateDuelFlag(now);
1105 CheckDuelDistance(now);
1107 UpdateAfkReport(now);
1109 // Update items that have just a limited lifetime
1110 if (now>m_Last_tick)
1111 UpdateItemDuration(uint32(now- m_Last_tick));
1113 if (!m_timedquests.empty())
1115 std::set<uint32>::iterator iter = m_timedquests.begin();
1116 while (iter != m_timedquests.end())
1118 QuestStatusData& q_status = mQuestStatus[*iter];
1119 if( q_status.m_timer <= p_time )
1121 uint32 quest_id = *iter;
1122 ++iter; // current iter will be removed in FailTimedQuest
1123 FailTimedQuest( quest_id );
1125 else
1127 q_status.m_timer -= p_time;
1128 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1129 ++iter;
1134 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1136 Unit *pVictim = getVictim();
1137 if (pVictim && !IsNonMeleeSpellCasted(false))
1139 // default combat reach 10
1140 // TODO add weapon,skill check
1142 float pldistance = ATTACK_DISTANCE;
1144 if (isAttackReady(BASE_ATTACK))
1146 if(!IsWithinDistInMap(pVictim, pldistance))
1148 setAttackTimer(BASE_ATTACK,100);
1149 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1151 SendAttackSwingNotInRange();
1152 m_swingErrorMsg = 1;
1155 //120 degrees of radiant range
1156 else if( !HasInArc( 2*M_PI/3, pVictim ))
1158 setAttackTimer(BASE_ATTACK,100);
1159 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1161 SendAttackSwingBadFacingAttack();
1162 m_swingErrorMsg = 2;
1165 else
1167 m_swingErrorMsg = 0; // reset swing error state
1169 // prevent base and off attack in same time, delay attack at 0.2 sec
1170 if(haveOffhandWeapon())
1172 uint32 off_att = getAttackTimer(OFF_ATTACK);
1173 if(off_att < ATTACK_DISPLAY_DELAY)
1174 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1176 AttackerStateUpdate(pVictim, BASE_ATTACK);
1177 resetAttackTimer(BASE_ATTACK);
1181 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1183 if(!IsWithinDistInMap(pVictim, pldistance))
1185 setAttackTimer(OFF_ATTACK,100);
1187 else if( !HasInArc( 2*M_PI/3, pVictim ))
1189 setAttackTimer(OFF_ATTACK,100);
1191 else
1193 // prevent base and off attack in same time, delay attack at 0.2 sec
1194 uint32 base_att = getAttackTimer(BASE_ATTACK);
1195 if(base_att < ATTACK_DISPLAY_DELAY)
1196 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1197 // do attack
1198 AttackerStateUpdate(pVictim, OFF_ATTACK);
1199 resetAttackTimer(OFF_ATTACK);
1203 Unit *owner = pVictim->GetOwner();
1204 Unit *u = owner ? owner : pVictim;
1205 if(u->IsPvP() && (!duel || duel->opponent != u))
1207 UpdatePvP(true);
1208 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1213 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1215 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1217 int time_inn = time(NULL)-GetTimeInnEnter();
1218 if (time_inn >= 10) //freeze update
1220 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1221 //speed collect rest bonus (section/in hour)
1222 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1223 UpdateInnerTime(time(NULL));
1228 if(m_regenTimer > 0)
1230 if(p_time >= m_regenTimer)
1231 m_regenTimer = 0;
1232 else
1233 m_regenTimer -= p_time;
1236 if (m_weaponChangeTimer > 0)
1238 if(p_time >= m_weaponChangeTimer)
1239 m_weaponChangeTimer = 0;
1240 else
1241 m_weaponChangeTimer -= p_time;
1244 if (m_zoneUpdateTimer > 0)
1246 if(p_time >= m_zoneUpdateTimer)
1248 uint32 newzone, newarea;
1249 GetZoneAndAreaId(newzone,newarea);
1251 if( m_zoneUpdateId != newzone )
1252 UpdateZone(newzone,newarea); // also update area
1253 else
1255 // use area updates as well
1256 // needed for free far all arenas for example
1257 if( m_areaUpdateId != newarea )
1258 UpdateArea(newarea);
1260 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1263 else
1264 m_zoneUpdateTimer -= p_time;
1267 if (isAlive())
1269 RegenerateAll();
1272 if (m_deathState == JUST_DIED)
1274 KillPlayer();
1277 if(m_nextSave > 0)
1279 if(p_time >= m_nextSave)
1281 // m_nextSave reseted in SaveToDB call
1282 SaveToDB();
1283 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1285 else
1287 m_nextSave -= p_time;
1291 //Handle Water/drowning
1292 HandleDrowning(p_time);
1294 //Handle detect stealth players
1295 if (m_DetectInvTimer > 0)
1297 if (p_time >= m_DetectInvTimer)
1299 m_DetectInvTimer = 3000;
1300 HandleStealthedUnitsDetection();
1302 else
1303 m_DetectInvTimer -= p_time;
1306 // Played time
1307 if (now > m_Last_tick)
1309 uint32 elapsed = uint32(now - m_Last_tick);
1310 m_Played_time[0] += elapsed; // Total played time
1311 m_Played_time[1] += elapsed; // Level played time
1312 m_Last_tick = now;
1315 if (m_drunk)
1317 m_drunkTimer += p_time;
1319 if (m_drunkTimer > 10*IN_MILISECONDS)
1320 HandleSobering();
1323 // not auto-free ghost from body in instances
1324 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1326 if(p_time >= m_deathTimer)
1328 m_deathTimer = 0;
1329 BuildPlayerRepop();
1330 RepopAtGraveyard();
1332 else
1333 m_deathTimer -= p_time;
1336 UpdateEnchantTime(p_time);
1337 UpdateHomebindTime(p_time);
1339 // group update
1340 SendUpdateToOutOfRangeGroupMembers();
1342 Pet* pet = GetPet();
1343 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1345 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1346 return;
1350 void Player::setDeathState(DeathState s)
1352 uint32 ressSpellId = 0;
1354 bool cur = isAlive();
1356 if(s == JUST_DIED && cur)
1358 // drunken state is cleared on death
1359 SetDrunkValue(0);
1360 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1361 ClearComboPoints();
1363 clearResurrectRequestData();
1365 // remove form before other mods to prevent incorrect stats calculation
1366 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1368 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1369 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1371 // remove uncontrolled pets
1372 RemoveMiniPet();
1373 RemoveGuardians();
1375 // save value before aura remove in Unit::setDeathState
1376 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1378 // passive spell
1379 if(!ressSpellId)
1380 ressSpellId = GetResurrectionSpellId();
1381 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1382 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1383 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1385 Unit::setDeathState(s);
1387 // restore resurrection spell id for player after aura remove
1388 if(s == JUST_DIED && cur && ressSpellId)
1389 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1391 if(isAlive() && !cur)
1393 //clear aura case after resurrection by another way (spells will be applied before next death)
1394 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1396 // restore default warrior stance
1397 if(getClass()== CLASS_WARRIOR)
1398 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1402 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1404 Field *fields = result->Fetch();
1406 *p_data << uint64(GetGUID());
1407 *p_data << m_name;
1409 *p_data << uint8(getRace());
1410 uint8 pClass = getClass();
1411 *p_data << uint8(pClass);
1412 *p_data << uint8(getGender());
1414 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1415 *p_data << uint8(bytes);
1416 *p_data << uint8(bytes >> 8);
1417 *p_data << uint8(bytes >> 16);
1418 *p_data << uint8(bytes >> 24);
1420 bytes = GetUInt32Value(PLAYER_BYTES_2);
1421 *p_data << uint8(bytes);
1423 *p_data << uint8(getLevel()); // player level
1424 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1425 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1426 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1427 *p_data << uint32(zoneId);
1428 *p_data << uint32(GetMapId());
1430 *p_data << GetPositionX();
1431 *p_data << GetPositionY();
1432 *p_data << GetPositionZ();
1434 // guild id
1435 *p_data << (result ? fields[13].GetUInt32() : 0);
1437 uint32 char_flags = 0;
1438 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1439 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1440 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1441 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1442 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1443 char_flags |= CHARACTER_FLAG_GHOST;
1444 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1445 char_flags |= CHARACTER_FLAG_RENAME;
1446 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1447 char_flags |= CHARACTER_FLAG_DECLINED;
1449 *p_data << uint32(char_flags); // character flags
1450 // character customize (flags?)
1451 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1452 *p_data << uint8(1); // unknown
1454 // Pets info
1456 uint32 petDisplayId = 0;
1457 uint32 petLevel = 0;
1458 uint32 petFamily = 0;
1460 // show pet at selection character in character list only for non-ghost character
1461 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1463 uint32 entry = fields[10].GetUInt32();
1464 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1465 if(cInfo)
1467 petDisplayId = fields[11].GetUInt32();
1468 petLevel = fields[12].GetUInt32();
1469 petFamily = cInfo->family;
1473 *p_data << uint32(petDisplayId);
1474 *p_data << uint32(petLevel);
1475 *p_data << uint32(petFamily);
1478 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1480 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1481 uint32 item_id = GetUInt32Value(visualbase);
1482 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1483 SpellItemEnchantmentEntry const *enchant = NULL;
1485 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1487 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1488 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1489 break;
1492 if (proto != NULL)
1494 *p_data << uint32(proto->DisplayInfoID);
1495 *p_data << uint8(proto->InventoryType);
1496 *p_data << uint32(enchant ? enchant->aura_id : 0);
1498 else
1500 *p_data << uint32(0);
1501 *p_data << uint8(0);
1502 *p_data << uint32(0); // enchant?
1505 *p_data << uint32(0); // first bag display id
1506 *p_data << uint8(0); // first bag inventory type
1507 *p_data << uint32(0); // enchant?
1510 bool Player::ToggleAFK()
1512 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1514 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1516 // afk player not allowed in battleground
1517 if(state && InBattleGround())
1518 LeaveBattleground();
1520 return state;
1523 bool Player::ToggleDND()
1525 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1527 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1530 uint8 Player::chatTag() const
1532 // it's bitmask
1533 // 0x8 - ??
1534 // 0x4 - gm
1535 // 0x2 - dnd
1536 // 0x1 - afk
1537 if(isGMChat())
1538 return 4;
1539 else if(isDND())
1540 return 3;
1541 if(isAFK())
1542 return 1;
1543 else
1544 return 0;
1547 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1549 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1551 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1552 return false;
1555 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1556 Pet* pet = GetPet();
1558 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1560 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1561 // don't let gm level > 1 either
1562 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1563 return false;
1565 // client without expansion support
1566 if(GetSession()->Expansion() < mEntry->Expansion())
1568 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1570 if(GetTransport())
1571 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1573 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1575 return false; // normal client can't teleport to this map...
1577 else
1579 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1582 // if we were on a transport, leave
1583 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1585 m_transport->RemovePassenger(this);
1586 m_transport = NULL;
1587 m_movementInfo.t_x = 0.0f;
1588 m_movementInfo.t_y = 0.0f;
1589 m_movementInfo.t_z = 0.0f;
1590 m_movementInfo.t_o = 0.0f;
1591 m_movementInfo.t_time = 0;
1594 // The player was ported to another map and looses the duel immediately.
1595 // We have to perform this check before the teleport, otherwise the
1596 // ObjectAccessor won't find the flag.
1597 if (duel && GetMapId()!=mapid)
1599 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1600 if (obj)
1601 DuelComplete(DUEL_FLED);
1604 // reset movement flags at teleport, because player will continue move with these flags after teleport
1605 SetUnitMovementFlags(0);
1607 if ((GetMapId() == mapid) && (!m_transport))
1609 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1611 //same map, only remove pet if out of range for new position
1612 if(pet && pet->GetDistance(x,y,z) >= OWNER_MAX_DISTANCE)
1613 UnsummonPetTemporaryIfAny();
1616 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1617 CombatStop();
1619 // this will be used instead of the current location in SaveToDB
1620 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1621 SetFallInformation(0, z);
1623 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1624 // at client packet MSG_MOVE_TELEPORT_ACK
1625 SetSemaphoreTeleportNear(true);
1626 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1627 if(!GetSession()->PlayerLogout())
1629 WorldPacket data;
1630 BuildTeleportAckMsg(&data, x, y, z, orientation);
1631 GetSession()->SendPacket(&data);
1634 else
1636 // far teleport to another map
1637 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1638 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1640 // Check enter rights before map getting to avoid creating instance copy for player
1641 // this check not dependent from map instance copy and same for all instance copies of selected map
1642 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1643 return false;
1645 // If the map is not created, assume it is possible to enter it.
1646 // It will be created in the WorldPortAck.
1647 Map *map = MapManager::Instance().FindMap(mapid);
1648 if (!map || map->CanEnter(this))
1650 SetSelection(0);
1652 CombatStop();
1654 ResetContestedPvP();
1656 // remove player from battleground on far teleport (when changing maps)
1657 if(BattleGround const* bg = GetBattleGround())
1659 // Note: at battleground join battleground id set before teleport
1660 // and we already will found "current" battleground
1661 // just need check that this is targeted map or leave
1662 if(bg->GetMapId() != mapid)
1663 LeaveBattleground(false); // don't teleport to entry point
1666 // remove pet on map change
1667 if (pet)
1668 UnsummonPetTemporaryIfAny();
1670 // remove all dyn objects
1671 RemoveAllDynObjects();
1673 // stop spellcasting
1674 // not attempt interrupt teleportation spell at caster teleport
1675 if(!(options & TELE_TO_SPELL))
1676 if(IsNonMeleeSpellCasted(true))
1677 InterruptNonMeleeSpells(true);
1679 if(!GetSession()->PlayerLogout())
1681 // send transfer packets
1682 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1683 data << uint32(mapid);
1684 if (m_transport)
1686 data << m_transport->GetEntry() << GetMapId();
1688 GetSession()->SendPacket(&data);
1690 data.Initialize(SMSG_NEW_WORLD, (20));
1691 if (m_transport)
1693 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1695 else
1697 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1699 GetSession()->SendPacket( &data );
1700 SendSavedInstances();
1702 // remove from old map now
1703 if(oldmap) oldmap->Remove(this, false);
1706 // new final coordinates
1707 float final_x = x;
1708 float final_y = y;
1709 float final_z = z;
1710 float final_o = orientation;
1712 if(m_transport)
1714 final_x += m_movementInfo.t_x;
1715 final_y += m_movementInfo.t_y;
1716 final_z += m_movementInfo.t_z;
1717 final_o += m_movementInfo.t_o;
1720 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1721 SetFallInformation(0, final_z);
1722 // if the player is saved before worldportack (at logout for example)
1723 // this will be used instead of the current location in SaveToDB
1725 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1727 // move packet sent by client always after far teleport
1728 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1729 SetSemaphoreTeleportFar(true);
1731 else
1732 return false;
1734 return true;
1737 void Player::AddToWorld()
1739 ///- Do not add/remove the player from the object storage
1740 ///- It will crash when updating the ObjectAccessor
1741 ///- The player should only be added when logging in
1742 Unit::AddToWorld();
1744 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1746 if(m_items[i])
1747 m_items[i]->AddToWorld();
1751 void Player::RemoveFromWorld()
1753 // cleanup
1754 if(IsInWorld())
1756 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1757 Uncharm();
1758 UnsummonAllTotems();
1759 RemoveMiniPet();
1760 RemoveGuardians();
1763 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1765 if(m_items[i])
1766 m_items[i]->RemoveFromWorld();
1769 ///- Do not add/remove the player from the object storage
1770 ///- It will crash when updating the ObjectAccessor
1771 ///- The player should only be removed when logging out
1772 Unit::RemoveFromWorld();
1775 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1777 float addRage;
1779 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1781 if(attacker)
1783 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1785 // talent who gave more rage on attack
1786 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1788 else
1790 addRage = damage/rageconversion*2.5;
1792 // Berserker Rage effect
1793 if(HasAura(18499,0))
1794 addRage *= 1.3;
1797 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1799 ModifyPower(POWER_RAGE, uint32(addRage*10));
1802 void Player::RegenerateAll()
1804 if (m_regenTimer != 0)
1805 return;
1806 uint32 regenDelay = 2000;
1808 // Not in combat or they have regeneration
1809 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1810 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1812 RegenerateHealth();
1813 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1815 Regenerate(POWER_RAGE);
1816 if(getClass() == CLASS_DEATH_KNIGHT)
1817 Regenerate(POWER_RUNIC_POWER);
1821 Regenerate( POWER_ENERGY );
1823 Regenerate( POWER_MANA );
1825 if(getClass() == CLASS_DEATH_KNIGHT)
1826 Regenerate( POWER_RUNE );
1828 m_regenTimer = regenDelay;
1831 void Player::Regenerate(Powers power)
1833 uint32 curValue = GetPower(power);
1834 uint32 maxValue = GetMaxPower(power);
1836 float addvalue = 0.0f;
1838 switch (power)
1840 case POWER_MANA:
1842 bool recentCast = IsUnderLastManaUseEffect();
1843 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1844 if (recentCast)
1846 // Mangos Updates Mana in intervals of 2s, which is correct
1847 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1849 else
1851 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1853 } break;
1854 case POWER_RAGE: // Regenerate rage
1856 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1857 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1858 } break;
1859 case POWER_ENERGY: // Regenerate energy (rogue)
1860 addvalue = 20;
1861 break;
1862 case POWER_RUNIC_POWER:
1864 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1865 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1866 } break;
1867 case POWER_RUNE:
1869 for(uint32 i = 0; i < MAX_RUNES; ++i)
1870 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1871 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1872 } break;
1873 case POWER_FOCUS:
1874 case POWER_HAPPINESS:
1875 break;
1878 // Mana regen calculated in Player::UpdateManaRegen()
1879 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1880 if(power != POWER_MANA)
1882 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1883 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1884 if ((*i)->GetModifier()->m_miscvalue == power)
1885 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1888 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1890 curValue += uint32(addvalue);
1891 if (curValue > maxValue)
1892 curValue = maxValue;
1894 else
1896 if(curValue <= uint32(addvalue))
1897 curValue = 0;
1898 else
1899 curValue -= uint32(addvalue);
1901 SetPower(power, curValue);
1904 void Player::RegenerateHealth()
1906 uint32 curValue = GetHealth();
1907 uint32 maxValue = GetMaxHealth();
1909 if (curValue >= maxValue) return;
1911 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1913 float addvalue = 0.0f;
1915 // polymorphed case
1916 if ( IsPolymorphed() )
1917 addvalue = GetMaxHealth()/3;
1918 // normal regen case (maybe partly in combat case)
1919 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1921 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1922 if (!isInCombat())
1924 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1925 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1926 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1928 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1929 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1931 if(!IsStandState())
1932 addvalue *= 1.5;
1935 // always regeneration bonus (including combat)
1936 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1938 if(addvalue < 0)
1939 addvalue = 0;
1941 ModifyHealth(int32(addvalue));
1944 bool Player::CanInteractWithNPCs(bool alive) const
1946 if(alive && !isAlive())
1947 return false;
1948 if(isInFlight())
1949 return false;
1951 return true;
1954 Creature*
1955 Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
1957 // unit checks
1958 if (!guid)
1959 return NULL;
1961 if(!IsInWorld())
1962 return NULL;
1964 // exist
1965 Creature *unit = GetMap()->GetCreature(guid);
1966 if (!unit)
1967 return NULL;
1969 // player check
1970 if(!CanInteractWithNPCs(!unit->isSpiritService()))
1971 return NULL;
1973 // appropriate npc type
1974 if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
1975 return NULL;
1977 // alive or spirit healer
1978 if(!unit->isAlive() && (!unit->isSpiritService() || isAlive() ))
1979 return NULL;
1981 // not allow interaction under control
1982 if(unit->GetCharmerOrOwnerGUID())
1983 return NULL;
1985 // not enemy
1986 if( unit->IsHostileTo(this))
1987 return NULL;
1989 // not unfriendly
1990 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
1991 if(factionTemplate->faction)
1992 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
1993 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
1994 return NULL;
1996 // not too far
1997 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
1998 return NULL;
2000 return unit;
2003 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
2005 if(GameObject *go = GetMap()->GetGameObject(guid))
2007 if(go->GetGoType() == type)
2009 float maxdist;
2010 switch(type)
2012 // TODO: find out how the client calculates the maximal usage distance to spellless working
2013 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2014 case GAMEOBJECT_TYPE_GUILD_BANK:
2015 case GAMEOBJECT_TYPE_MAILBOX:
2016 maxdist = 10.0f;
2017 break;
2018 case GAMEOBJECT_TYPE_FISHINGHOLE:
2019 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2020 break;
2021 default:
2022 maxdist = INTERACTION_DISTANCE;
2023 break;
2026 if (go->IsWithinDistInMap(this, maxdist))
2027 return go;
2029 sLog.outError("IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go->GetGOInfo()->name,
2030 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2033 return NULL;
2036 bool Player::IsUnderWater() const
2038 return IsInWater() &&
2039 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2042 void Player::SetInWater(bool apply)
2044 if(m_isInWater==apply)
2045 return;
2047 //define player in water by opcodes
2048 //move player's guid into HateOfflineList of those mobs
2049 //which can't swim and move guid back into ThreatList when
2050 //on surface.
2051 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2052 m_isInWater = apply;
2054 // remove auras that need water/land
2055 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2057 getHostilRefManager().updateThreatTables();
2060 void Player::SetGameMaster(bool on)
2062 if(on)
2064 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2065 setFaction(35);
2066 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2068 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2069 ResetContestedPvP();
2071 getHostilRefManager().setOnlineOfflineState(false);
2072 CombatStop();
2074 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2076 else
2078 // restore phase
2079 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2080 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2082 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2083 setFactionForRace(getRace());
2084 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2086 // restore FFA PvP Server state
2087 if(sWorld.IsFFAPvPRealm())
2088 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2090 // restore FFA PvP area state, remove not allowed for GM mounts
2091 UpdateArea(m_areaUpdateId);
2093 getHostilRefManager().setOnlineOfflineState(true);
2096 ObjectAccessor::UpdateVisibilityForPlayer(this);
2099 void Player::SetGMVisible(bool on)
2101 if(on)
2103 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2105 // Reapply stealth/invisibility if active or show if not any
2106 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2107 SetVisibility(VISIBILITY_GROUP_STEALTH);
2108 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2109 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2110 else
2111 SetVisibility(VISIBILITY_ON);
2113 else
2115 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2117 SetAcceptWhispers(false);
2118 SetGameMaster(true);
2120 SetVisibility(VISIBILITY_OFF);
2124 bool Player::IsGroupVisibleFor(Player* p) const
2126 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2128 default: return IsInSameGroupWith(p);
2129 case 1: return IsInSameRaidWith(p);
2130 case 2: return GetTeam()==p->GetTeam();
2134 bool Player::IsInSameGroupWith(Player const* p) const
2136 return p==this || GetGroup() != NULL &&
2137 GetGroup() == p->GetGroup() &&
2138 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2141 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2142 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2143 void Player::UninviteFromGroup()
2145 Group* group = GetGroupInvite();
2146 if(!group)
2147 return;
2149 group->RemoveInvite(this);
2151 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2153 if(group->IsCreated())
2155 group->Disband(true);
2156 objmgr.RemoveGroup(group);
2158 else
2159 group->RemoveAllInvites();
2161 delete group;
2165 void Player::RemoveFromGroup(Group* group, uint64 guid)
2167 if(group)
2169 if (group->RemoveMember(guid, 0) <= 1)
2171 // group->Disband(); already disbanded in RemoveMember
2172 objmgr.RemoveGroup(group);
2173 delete group;
2174 // removemember sets the player's group pointer to NULL
2179 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2181 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2182 data << uint64(victim ? victim->GetGUID() : 0); // guid
2183 data << uint32(GivenXP+RestXP); // given experience
2184 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2185 if(victim)
2187 data << uint32(GivenXP); // experience without rested bonus
2188 data << float(1); // 1 - none 0 - 100% group bonus output
2190 data << uint8(0); // new 2.4.0
2191 GetSession()->SendPacket(&data);
2194 void Player::GiveXP(uint32 xp, Unit* victim)
2196 if ( xp < 1 )
2197 return;
2199 if(!isAlive())
2200 return;
2202 uint32 level = getLevel();
2204 // XP to money conversion processed in Player::RewardQuest
2205 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2206 return;
2208 // handle SPELL_AURA_MOD_XP_PCT auras
2209 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2210 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2211 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2213 // XP resting bonus for kill
2214 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2216 SendLogXPGain(xp,victim,rested_bonus_xp);
2218 uint32 curXP = GetUInt32Value(PLAYER_XP);
2219 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2220 uint32 newXP = curXP + xp + rested_bonus_xp;
2222 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2224 newXP -= nextLvlXP;
2226 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2227 GiveLevel(level + 1);
2229 level = getLevel();
2230 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2233 SetUInt32Value(PLAYER_XP, newXP);
2236 // Update player to next level
2237 // Current player experience not update (must be update by caller)
2238 void Player::GiveLevel(uint32 level)
2240 if ( level == getLevel() )
2241 return;
2243 PlayerLevelInfo info;
2244 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2246 PlayerClassLevelInfo classInfo;
2247 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2249 // send levelup info to client
2250 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2251 data << uint32(level);
2252 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2253 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2254 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2255 data << uint32(0);
2256 data << uint32(0);
2257 data << uint32(0);
2258 data << uint32(0);
2259 data << uint32(0);
2260 data << uint32(0);
2261 // end for
2262 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2263 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2265 GetSession()->SendPacket(&data);
2267 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2269 //update level, max level of skills
2270 if(getLevel()!= level)
2271 m_Played_time[1] = 0; // Level Played Time reset
2272 SetLevel(level);
2273 UpdateSkillsForLevel ();
2275 // save base values (bonuses already included in stored stats
2276 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2277 SetCreateStat(Stats(i), info.stats[i]);
2279 SetCreateHealth(classInfo.basehealth);
2280 SetCreateMana(classInfo.basemana);
2282 InitTalentForLevel();
2283 InitTaxiNodesForLevel();
2284 InitGlyphsForLevel();
2286 UpdateAllStats();
2288 // set current level health and mana/energy to maximum after applying all mods.
2289 SetHealth(GetMaxHealth());
2290 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2291 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2292 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2293 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2294 SetPower(POWER_FOCUS, 0);
2295 SetPower(POWER_HAPPINESS, 0);
2297 // give level to summoned pet
2298 Pet* pet = GetPet();
2299 if(pet && pet->getPetType()==SUMMON_PET)
2300 pet->GivePetLevel(level);
2301 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2304 void Player::InitTalentForLevel()
2306 uint32 level = getLevel();
2307 // talents base at level diff ( talents = level - 9 but some can be used already)
2308 if(level < 10)
2310 // Remove all talent points
2311 if(m_usedTalentCount > 0) // Free any used talents
2313 resetTalents(true);
2314 SetFreeTalentPoints(0);
2317 else
2319 uint32 talentPointsForLevel = CalculateTalentsPoints();
2321 // if used more that have then reset
2322 if(m_usedTalentCount > talentPointsForLevel)
2324 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2325 resetTalents(true);
2326 else
2327 SetFreeTalentPoints(0);
2329 // else update amount of free points
2330 else
2331 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2335 void Player::InitStatsForLevel(bool reapplyMods)
2337 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2338 _RemoveAllStatBonuses();
2340 PlayerClassLevelInfo classInfo;
2341 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2343 PlayerLevelInfo info;
2344 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2346 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2347 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2349 UpdateSkillsForLevel ();
2351 // set default cast time multiplier
2352 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2354 // reset size before reapply auras
2355 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2357 // save base values (bonuses already included in stored stats
2358 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2359 SetCreateStat(Stats(i), info.stats[i]);
2361 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2362 SetStat(Stats(i), info.stats[i]);
2364 SetCreateHealth(classInfo.basehealth);
2366 //set create powers
2367 SetCreateMana(classInfo.basemana);
2369 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2371 InitStatBuffMods();
2373 //reset rating fields values
2374 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2375 SetUInt32Value(index, 0);
2377 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2378 for (int i = 0; i < 7; ++i)
2380 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2381 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2382 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2385 //reset attack power, damage and attack speed fields
2386 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2387 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2388 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2390 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2391 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2392 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2393 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2394 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2395 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2397 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2398 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2399 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2400 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2401 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2402 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2404 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2405 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2406 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2407 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2409 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2410 for (uint8 i = 0; i < 7; ++i)
2411 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2413 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2414 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2415 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2417 // Dodge percentage
2418 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2420 // set armor (resistance 0) to original value (create_agility*2)
2421 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2422 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2423 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2424 // set other resistance to original value (0)
2425 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2427 SetResistance(SpellSchools(i), 0);
2428 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2429 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2432 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2433 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2434 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2436 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2437 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2439 // Reset no reagent cost field
2440 for(int i = 0; i < 3; ++i)
2441 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2442 // Init data for form but skip reapply item mods for form
2443 InitDataForForm(reapplyMods);
2445 // save new stats
2446 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2447 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2449 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2451 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2452 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2454 // cleanup unit flags (will be re-applied if need at aura load).
2455 RemoveFlag( UNIT_FIELD_FLAGS,
2456 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2457 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2458 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2459 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2460 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2461 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2463 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2465 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2466 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2468 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2469 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2471 // restore if need some important flags
2472 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2474 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2475 _ApplyAllStatBonuses();
2477 // set current level health and mana/energy to maximum after applying all mods.
2478 SetHealth(GetMaxHealth());
2479 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2480 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2481 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2482 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2483 SetPower(POWER_FOCUS, 0);
2484 SetPower(POWER_HAPPINESS, 0);
2485 SetPower(POWER_RUNIC_POWER, 0);
2488 void Player::SendInitialSpells()
2490 time_t curTime = time(NULL);
2491 time_t infTime = curTime + MONTH/2;
2493 uint16 spellCount = 0;
2495 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2496 data << uint8(0);
2498 size_t countPos = data.wpos();
2499 data << uint16(spellCount); // spell count placeholder
2501 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2503 if(itr->second->state == PLAYERSPELL_REMOVED)
2504 continue;
2506 if(!itr->second->active || itr->second->disabled)
2507 continue;
2509 data << uint16(itr->first);
2510 data << uint16(0); // it's not slot id
2512 spellCount +=1;
2515 data.put<uint16>(countPos,spellCount); // write real count value
2517 uint16 spellCooldowns = m_spellCooldowns.size();
2518 data << uint16(spellCooldowns);
2519 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2521 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2522 if(!sEntry)
2523 continue;
2525 // not send infinity cooldown
2526 if(itr->second.end > infTime)
2527 continue;
2529 data << uint16(itr->first);
2531 time_t cooldown = 0;
2532 if(itr->second.end > curTime)
2533 cooldown = (itr->second.end-curTime)*IN_MILISECONDS;
2535 data << uint16(itr->second.itemid); // cast item id
2536 data << uint16(sEntry->Category); // spell category
2537 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2539 data << uint32(0); // cooldown
2540 data << uint32(cooldown); // category cooldown
2542 else
2544 data << uint32(cooldown); // cooldown
2545 data << uint32(0); // category cooldown
2549 GetSession()->SendPacket(&data);
2551 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2554 void Player::RemoveMail(uint32 id)
2556 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2558 if ((*itr)->messageID == id)
2560 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2561 m_mail.erase(itr);
2562 return;
2567 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2569 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2570 data << (uint32) mailId;
2571 data << (uint32) mailAction;
2572 data << (uint32) mailError;
2573 if ( mailError == MAIL_ERR_BAG_FULL )
2574 data << (uint32) equipError;
2575 else if( mailAction == MAIL_ITEM_TAKEN )
2577 data << (uint32) item_guid; // item guid low?
2578 data << (uint32) item_count; // item count?
2580 GetSession()->SendPacket(&data);
2583 void Player::SendNewMail()
2585 // deliver undelivered mail
2586 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2587 data << (uint32) 0;
2588 GetSession()->SendPacket(&data);
2591 void Player::UpdateNextMailTimeAndUnreads()
2593 // calculate next delivery time (min. from non-delivered mails
2594 // and recalculate unReadMail
2595 time_t cTime = time(NULL);
2596 m_nextMailDelivereTime = 0;
2597 unReadMails = 0;
2598 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2600 if((*itr)->deliver_time > cTime)
2602 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2603 m_nextMailDelivereTime = (*itr)->deliver_time;
2605 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2606 ++unReadMails;
2610 void Player::AddNewMailDeliverTime(time_t deliver_time)
2612 if(deliver_time <= time(NULL)) // ready now
2614 ++unReadMails;
2615 SendNewMail();
2617 else // not ready and no have ready mails
2619 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2620 m_nextMailDelivereTime = deliver_time;
2624 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2626 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2627 if (!spellInfo)
2629 // do character spell book cleanup (all characters)
2630 if(!IsInWorld() && !learning) // spell load case
2632 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2633 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2635 else
2636 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2638 return false;
2641 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2643 // do character spell book cleanup (all characters)
2644 if(!IsInWorld() && !learning) // spell load case
2646 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2647 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2649 else
2650 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2652 return false;
2655 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2657 bool dependent_set = false;
2658 bool disabled_case = false;
2659 bool superceded_old = false;
2661 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2662 if (itr != m_spells.end())
2664 uint32 next_active_spell_id = 0;
2665 // fix activate state for non-stackable low rank (and find next spell for !active case)
2666 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2668 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2669 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2671 if(HasSpell(next_itr->second))
2673 // high rank already known so this must !active
2674 active = false;
2675 next_active_spell_id = next_itr->second;
2676 break;
2681 // not do anything if already known in expected state
2682 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2683 itr->second->dependent == dependent && itr->second->disabled == disabled)
2685 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2686 itr->second->state = PLAYERSPELL_UNCHANGED;
2688 return false;
2691 // dependent spell known as not dependent, overwrite state
2692 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2694 itr->second->dependent = dependent;
2695 if (itr->second->state != PLAYERSPELL_NEW)
2696 itr->second->state = PLAYERSPELL_CHANGED;
2697 dependent_set = true;
2700 // update active state for known spell
2701 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2703 itr->second->active = active;
2705 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2706 itr->second->state = PLAYERSPELL_UNCHANGED;
2707 else if(itr->second->state != PLAYERSPELL_NEW)
2708 itr->second->state = PLAYERSPELL_CHANGED;
2710 if(active)
2712 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2713 CastSpell (this,spell_id,true);
2715 else if(IsInWorld())
2717 if(next_active_spell_id)
2719 // update spell ranks in spellbook and action bar
2720 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2721 data << uint16(spell_id);
2722 data << uint16(next_active_spell_id);
2723 GetSession()->SendPacket( &data );
2725 else
2727 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2728 data << uint16(spell_id);
2729 GetSession()->SendPacket(&data);
2733 return active; // learn (show in spell book if active now)
2736 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2738 if(itr->second->state != PLAYERSPELL_NEW)
2739 itr->second->state = PLAYERSPELL_CHANGED;
2740 itr->second->disabled = disabled;
2742 if(disabled)
2743 return false;
2745 disabled_case = true;
2747 else switch(itr->second->state)
2749 case PLAYERSPELL_UNCHANGED: // known saved spell
2750 return false;
2751 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2753 delete itr->second;
2754 m_spells.erase(itr);
2755 state = PLAYERSPELL_CHANGED;
2756 break; // need re-add
2758 default: // known not saved yet spell (new or modified)
2760 // can be in case spell loading but learned at some previous spell loading
2761 if(!IsInWorld() && !learning && !dependent_set)
2762 itr->second->state = PLAYERSPELL_UNCHANGED;
2764 return false;
2769 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2771 // talent: unlearn all other talent ranks (high and low)
2772 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2774 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2776 for(int i=0; i < MAX_TALENT_RANK; ++i)
2778 // skip learning spell and no rank spell case
2779 uint32 rankSpellId = talentInfo->RankID[i];
2780 if(!rankSpellId || rankSpellId==spell_id)
2781 continue;
2783 removeSpell(rankSpellId);
2787 // non talent spell: learn low ranks (recursive call)
2788 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2790 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2791 addSpell(prev_spell,active,true,true,disabled);
2792 else // at normal learning
2793 learnSpell(prev_spell,true);
2796 PlayerSpell *newspell = new PlayerSpell;
2797 newspell->state = state;
2798 newspell->active = active;
2799 newspell->dependent = dependent;
2800 newspell->disabled = disabled;
2802 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2803 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2805 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
2807 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
2808 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
2809 if(!i_spellInfo) continue;
2811 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
2813 if(itr2->second->active)
2815 if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
2817 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2819 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2820 data << uint16(itr2->first);
2821 data << uint16(spell_id);
2822 GetSession()->SendPacket( &data );
2825 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2826 itr2->second->active = false;
2827 if(itr2->second->state != PLAYERSPELL_NEW)
2828 itr2->second->state = PLAYERSPELL_CHANGED;
2829 superceded_old = true; // new spell replace old in action bars and spell book.
2831 else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
2833 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2835 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2836 data << uint16(spell_id);
2837 data << uint16(itr2->first);
2838 GetSession()->SendPacket( &data );
2841 // mark new spell as disable (not learned yet for client and will not learned)
2842 newspell->active = false;
2843 if(newspell->state != PLAYERSPELL_NEW)
2844 newspell->state = PLAYERSPELL_CHANGED;
2851 m_spells[spell_id] = newspell;
2853 // return false if spell disabled
2854 if (newspell->disabled)
2855 return false;
2858 uint32 talentCost = GetTalentSpellCost(spell_id);
2860 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2861 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2862 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2864 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2865 CastSpell(this, spell_id, true);
2867 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2868 else if (IsPassiveSpell(spell_id))
2870 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2871 CastSpell(this, spell_id, true);
2873 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2875 CastSpell(this, spell_id, true);
2876 return false;
2879 // update used talent points count
2880 m_usedTalentCount += talentCost;
2882 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2883 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2885 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2886 SetFreePrimaryProffesions(freeProfs-1);
2889 // add dependent skills
2890 uint16 maxskill = GetMaxSkillValueForLevel();
2892 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2894 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2895 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2897 if(spellLearnSkill)
2899 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2900 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2902 if(skill_value < spellLearnSkill->value)
2903 skill_value = spellLearnSkill->value;
2905 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2907 if(skill_max_value < new_skill_max_value)
2908 skill_max_value = new_skill_max_value;
2910 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2912 else
2914 // not ranked skills
2915 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2917 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2918 if(!pSkill)
2919 continue;
2921 if(HasSkill(pSkill->id))
2922 continue;
2924 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2925 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2926 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
2928 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2930 case SKILL_RANGE_LANGUAGE:
2931 SetSkill(pSkill->id, 300, 300 );
2932 break;
2933 case SKILL_RANGE_LEVEL:
2934 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2935 break;
2936 case SKILL_RANGE_MONO:
2937 SetSkill(pSkill->id, 1, 1 );
2938 break;
2939 default:
2940 break;
2946 // learn dependent spells
2947 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2948 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2950 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2952 if(!itr2->second.autoLearned)
2954 if(!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
2955 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
2956 else // at normal learning
2957 learnSpell(itr2->second.spell,true);
2961 if(!GetSession()->PlayerLoading())
2963 // not ranked skills
2964 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2966 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
2967 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
2970 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
2973 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2974 return active && !disabled && !superceded_old;
2977 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
2979 bool need_cast = false;
2981 switch(spellInfo->Id)
2983 // some spells not have stance data expacted cast at form change or present
2984 case 5420: need_cast = (m_form == FORM_TREE); break;
2985 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
2986 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
2987 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
2988 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
2989 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
2990 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
2991 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
2992 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2993 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2994 // another spells have proper stance data
2995 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
2998 //Check CasterAuraStates
2999 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3002 void Player::learnSpell(uint32 spell_id, bool dependent)
3004 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3006 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3007 bool active = disabled ? itr->second->active : true;
3009 bool learning = addSpell(spell_id,active,true,dependent,false);
3011 // learn all disabled higher ranks (recursive)
3012 if(disabled)
3014 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3015 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3017 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3018 if (iter != m_spells.end() && iter->second->disabled)
3019 learnSpell(i->second,false);
3023 // prevent duplicated entires in spell book, also not send if not in world (loading)
3024 if(!learning || !IsInWorld ())
3025 return;
3027 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3028 data << uint32(spell_id);
3029 GetSession()->SendPacket(&data);
3032 void Player::removeSpell(uint32 spell_id, bool disabled, bool update_action_bar_for_low_rank)
3034 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3035 if (itr == m_spells.end())
3036 return;
3038 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
3039 return;
3041 // unlearn non talent higher ranks (recursive)
3042 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3043 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3044 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3045 removeSpell(itr2->second,disabled);
3047 bool cur_active = itr->second->active;
3048 bool cur_dependent = itr->second->dependent;
3050 if (disabled)
3052 itr->second->disabled = disabled;
3053 if(itr->second->state != PLAYERSPELL_NEW)
3054 itr->second->state = PLAYERSPELL_CHANGED;
3056 else
3058 if(itr->second->state == PLAYERSPELL_NEW)
3060 delete itr->second;
3061 m_spells.erase(itr);
3063 else
3064 itr->second->state = PLAYERSPELL_REMOVED;
3067 RemoveAurasDueToSpell(spell_id);
3069 // remove pet auras
3070 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
3071 RemovePetAura(petSpell);
3073 // free talent points
3074 uint32 talentCosts = GetTalentSpellCost(spell_id);
3075 if(talentCosts > 0)
3077 if(talentCosts < m_usedTalentCount)
3078 m_usedTalentCount -= talentCosts;
3079 else
3080 m_usedTalentCount = 0;
3083 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3084 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3086 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
3087 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3088 SetFreePrimaryProffesions(freeProfs);
3091 // remove dependent skill
3092 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3093 if(spellLearnSkill)
3095 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3096 if(!prev_spell) // first rank, remove skill
3097 SetSkill(spellLearnSkill->skill,0,0);
3098 else
3100 // search prev. skill setting by spell ranks chain
3101 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3102 while(!prevSkill && prev_spell)
3104 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3105 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3108 if(!prevSkill) // not found prev skill setting, remove skill
3109 SetSkill(spellLearnSkill->skill,0,0);
3110 else // set to prev. skill setting values
3112 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3113 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3115 if(skill_value > prevSkill->value)
3116 skill_value = prevSkill->value;
3118 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3120 if(skill_max_value > new_skill_max_value)
3121 skill_max_value = new_skill_max_value;
3123 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3128 else
3130 // not ranked skills
3131 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3132 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3134 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3136 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3137 if(!pSkill)
3138 continue;
3140 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3141 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3142 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
3144 // not reset skills for professions and racial abilities
3145 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3146 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3147 continue;
3149 SetSkill(pSkill->id, 0, 0 );
3154 // remove dependent spells
3155 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3156 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3158 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3159 removeSpell(itr2->second.spell, disabled);
3161 // activate lesser rank in spellbook/action bar, and cast it if need
3162 bool prev_activate = false;
3164 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3166 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3168 // if talent then lesser rank also talent and need learn
3169 if(talentCosts)
3170 learnSpell (prev_id,false);
3171 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3172 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3174 // need manually update dependence state (learn spell ignore like attempts)
3175 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3176 if (prev_itr != m_spells.end())
3178 if(prev_itr->second->dependent != cur_dependent)
3180 prev_itr->second->dependent = cur_dependent;
3181 if(prev_itr->second->state != PLAYERSPELL_NEW)
3182 prev_itr->second->state = PLAYERSPELL_CHANGED;
3185 // now re-learn if need re-activate
3186 if(cur_active && !prev_itr->second->active)
3188 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3190 if(update_action_bar_for_low_rank)
3192 // downgrade spell ranks in spellbook and action bar
3193 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
3194 data << uint16(spell_id);
3195 data << uint16(prev_id);
3196 GetSession()->SendPacket( &data );
3197 prev_activate = true;
3205 // remove from spell book if not replaced by lesser rank
3206 if(!prev_activate)
3208 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3209 data << uint16(spell_id);
3210 GetSession()->SendPacket(&data);
3214 void Player::RemoveArenaSpellCooldowns()
3216 // remove cooldowns on spells that has < 15 min CD
3217 SpellCooldowns::iterator itr, next;
3218 // iterate spell cooldowns
3219 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3221 next = itr;
3222 ++next;
3223 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3224 // check if spellentry is present and if the cooldown is less than 15 mins
3225 if( entry &&
3226 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3227 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3229 // notify player
3230 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3231 data << uint32(itr->first);
3232 data << uint64(GetGUID());
3233 GetSession()->SendPacket(&data);
3234 // remove cooldown
3235 m_spellCooldowns.erase(itr);
3240 void Player::RemoveAllSpellCooldown()
3242 if(!m_spellCooldowns.empty())
3244 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3246 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3247 data << uint32(itr->first);
3248 data << uint64(GetGUID());
3249 GetSession()->SendPacket(&data);
3251 m_spellCooldowns.clear();
3255 void Player::_LoadSpellCooldowns(QueryResult *result)
3257 // some cooldowns can be already set at aura loading...
3259 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3261 if(result)
3263 time_t curTime = time(NULL);
3267 Field *fields = result->Fetch();
3269 uint32 spell_id = fields[0].GetUInt32();
3270 uint32 item_id = fields[1].GetUInt32();
3271 time_t db_time = (time_t)fields[2].GetUInt64();
3273 if(!sSpellStore.LookupEntry(spell_id))
3275 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3276 continue;
3279 // skip outdated cooldown
3280 if(db_time <= curTime)
3281 continue;
3283 AddSpellCooldown(spell_id, item_id, db_time);
3285 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3287 while( result->NextRow() );
3289 delete result;
3293 void Player::_SaveSpellCooldowns()
3295 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3297 time_t curTime = time(NULL);
3298 time_t infTime = curTime + MONTH/2;
3300 // remove outdated and save active
3301 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3303 if(itr->second.end <= curTime)
3304 m_spellCooldowns.erase(itr++);
3305 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3307 CharacterDatabase.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" I64FMTD "')", GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
3308 ++itr;
3310 else
3311 ++itr;
3315 uint32 Player::resetTalentsCost() const
3317 // The first time reset costs 1 gold
3318 if(m_resetTalentsCost < 1*GOLD)
3319 return 1*GOLD;
3320 // then 5 gold
3321 else if(m_resetTalentsCost < 5*GOLD)
3322 return 5*GOLD;
3323 // After that it increases in increments of 5 gold
3324 else if(m_resetTalentsCost < 10*GOLD)
3325 return 10*GOLD;
3326 else
3328 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3329 if(months > 0)
3331 // This cost will be reduced by a rate of 5 gold per month
3332 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3333 // to a minimum of 10 gold.
3334 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3336 else
3338 // After that it increases in increments of 5 gold
3339 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3340 // until it hits a cap of 50 gold.
3341 if(new_cost > 50*GOLD)
3342 new_cost = 50*GOLD;
3343 return new_cost;
3348 bool Player::resetTalents(bool no_cost)
3350 // not need after this call
3351 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3353 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3354 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3357 uint32 talentPointsForLevel = CalculateTalentsPoints();
3359 if (m_usedTalentCount == 0)
3361 SetFreeTalentPoints(talentPointsForLevel);
3362 return false;
3365 uint32 cost = 0;
3367 if(!no_cost)
3369 cost = resetTalentsCost();
3371 if (GetMoney() < cost)
3373 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3374 return false;
3378 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3380 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3382 if (!talentInfo) continue;
3384 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3386 if(!talentTabInfo)
3387 continue;
3389 // unlearn only talents for character class
3390 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3391 // to prevent unexpected lost normal learned spell skip another class talents
3392 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3393 continue;
3395 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3397 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3399 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3401 ++itr;
3402 continue;
3405 // remove learned spells (all ranks)
3406 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3408 // unlearn if first rank is talent or learned by talent
3409 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3411 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3412 itr = GetSpellMap().begin();
3413 continue;
3415 else
3416 ++itr;
3421 SetFreeTalentPoints(talentPointsForLevel);
3423 if(!no_cost)
3425 ModifyMoney(-(int32)cost);
3426 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3428 m_resetTalentsCost = cost;
3429 m_resetTalentsTime = time(NULL);
3432 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3433 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3435 if(m_canTitanGrip)
3437 m_canTitanGrip = false;
3438 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3439 AutoUnequipOffhandIfNeed();
3442 return true;
3445 Mail* Player::GetMail(uint32 id)
3447 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3449 if ((*itr)->messageID == id)
3451 return (*itr);
3454 return NULL;
3457 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3459 if(target == this)
3461 Object::_SetCreateBits(updateMask, target);
3463 else
3465 for(uint16 index = 0; index < m_valuesCount; index++)
3467 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3468 updateMask->SetBit(index);
3473 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3475 if(target == this)
3477 Object::_SetUpdateBits(updateMask, target);
3479 else
3481 Object::_SetUpdateBits(updateMask, target);
3482 *updateMask &= updateVisualBits;
3486 void Player::InitVisibleBits()
3488 updateVisualBits.SetCount(PLAYER_END);
3490 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3491 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3492 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3493 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3494 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3495 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3496 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3497 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3498 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3499 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3500 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3501 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3502 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3503 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3504 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3505 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3506 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3507 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3508 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3509 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3510 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3511 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3512 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3513 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3514 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3515 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3516 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3517 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3518 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3519 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3520 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3521 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3522 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3523 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3524 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3525 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3526 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3527 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3528 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3529 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3530 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3531 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3532 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3533 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3534 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3535 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3536 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3537 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3538 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3539 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3540 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3541 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3542 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3543 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3544 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3546 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3547 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3548 updateVisualBits.SetBit(PLAYER_FLAGS);
3549 updateVisualBits.SetBit(PLAYER_GUILDID);
3550 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3551 updateVisualBits.SetBit(PLAYER_BYTES);
3552 updateVisualBits.SetBit(PLAYER_BYTES_2);
3553 updateVisualBits.SetBit(PLAYER_BYTES_3);
3554 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3555 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3557 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3558 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3559 updateVisualBits.SetBit(i);
3561 // Players visible items are not inventory stuff
3562 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3564 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3566 // item creator
3567 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3568 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3570 // item entry
3571 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3573 // item enchantments
3574 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3575 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3577 // random properties
3578 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3579 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3580 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3583 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3586 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3588 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3590 if(m_items[i] == NULL)
3591 continue;
3593 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3596 if(target == this)
3598 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3600 if(m_items[i] == NULL)
3601 continue;
3603 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3605 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
3607 if(m_items[i] == NULL)
3608 continue;
3610 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3614 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3617 void Player::DestroyForPlayer( Player *target ) const
3619 Unit::DestroyForPlayer( target );
3621 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3623 if(m_items[i] == NULL)
3624 continue;
3626 m_items[i]->DestroyForPlayer( target );
3629 if(target == this)
3631 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3633 if(m_items[i] == NULL)
3634 continue;
3636 m_items[i]->DestroyForPlayer( target );
3638 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
3640 if(m_items[i] == NULL)
3641 continue;
3643 m_items[i]->DestroyForPlayer( target );
3648 bool Player::HasSpell(uint32 spell) const
3650 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3651 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3652 !itr->second->disabled);
3655 bool Player::HasActiveSpell(uint32 spell) const
3657 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3658 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3659 itr->second->active && !itr->second->disabled);
3662 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3664 if (!trainer_spell)
3665 return TRAINER_SPELL_RED;
3667 if (!trainer_spell->learnedSpell)
3668 return TRAINER_SPELL_RED;
3670 // known spell
3671 if(HasSpell(trainer_spell->learnedSpell))
3672 return TRAINER_SPELL_GRAY;
3674 // check race/class requirement
3675 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3676 return TRAINER_SPELL_RED;
3678 // check level requirement
3679 if(getLevel() < trainer_spell->reqLevel)
3680 return TRAINER_SPELL_RED;
3682 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3684 // check prev.rank requirement
3685 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3686 return TRAINER_SPELL_RED;
3688 // check additional spell requirement
3689 if(spell_chain->req && !HasSpell(spell_chain->req))
3690 return TRAINER_SPELL_RED;
3693 // check skill requirement
3694 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3695 return TRAINER_SPELL_RED;
3697 // exist, already checked at loading
3698 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3700 // secondary prof. or not prof. spell
3701 uint32 skill = spell->EffectMiscValue[1];
3703 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3704 return TRAINER_SPELL_GREEN;
3706 // check primary prof. limit
3707 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3708 return TRAINER_SPELL_RED;
3710 return TRAINER_SPELL_GREEN;
3713 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3715 uint32 guid = GUID_LOPART(playerguid);
3717 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3718 // bones will be deleted by corpse/bones deleting thread shortly
3719 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3721 // remove from guild
3722 uint32 guildId = GetGuildIdFromDB(playerguid);
3723 if(guildId != 0)
3725 Guild* guild = objmgr.GetGuildById(guildId);
3726 if(guild)
3727 guild->DelMember(guid);
3730 // remove from arena teams
3731 LeaveAllArenaTeams(playerguid);
3733 // the player was uninvited already on logout so just remove from group
3734 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3735 if(resultGroup)
3737 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3738 delete resultGroup;
3739 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3740 if(group)
3742 RemoveFromGroup(group, playerguid);
3746 // remove signs from petitions (also remove petitions if owner);
3747 RemovePetitionsAndSigns(playerguid, 10);
3749 // return back all mails with COD and Item 0 1 2 3 4 5 6
3750 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);
3751 if(resultMail)
3755 Field *fields = resultMail->Fetch();
3757 uint32 mail_id = fields[0].GetUInt32();
3758 uint16 mailTemplateId= fields[1].GetUInt16();
3759 uint32 sender = fields[2].GetUInt32();
3760 std::string subject = fields[3].GetCppString();
3761 uint32 itemTextId = fields[4].GetUInt32();
3762 uint32 money = fields[5].GetUInt32();
3763 bool has_items = fields[6].GetBool();
3765 //we can return mail now
3766 //so firstly delete the old one
3767 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3769 MailItemsInfo mi;
3770 if(has_items)
3772 // data needs to be at first place for Item::LoadFromDB
3773 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);
3774 if(resultItems)
3778 Field *fields2 = resultItems->Fetch();
3780 uint32 item_guidlow = fields2[1].GetUInt32();
3781 uint32 item_template = fields2[2].GetUInt32();
3783 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3784 if(!itemProto)
3786 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3787 continue;
3790 Item *pItem = NewItemOrBag(itemProto);
3791 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3793 pItem->FSetState(ITEM_REMOVED);
3794 pItem->SaveToDB(); // it also deletes item object !
3795 continue;
3798 mi.AddItem(item_guidlow, item_template, pItem);
3800 while (resultItems->NextRow());
3802 delete resultItems;
3806 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3808 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3810 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3812 while (resultMail->NextRow());
3814 delete resultMail;
3817 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3818 // Get guids of character's pets, will deleted in transaction
3819 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3821 // NOW we can finally clear other DB data related to character
3822 CharacterDatabase.BeginTransaction();
3823 if (resultPets)
3827 Field *fields3 = resultPets->Fetch();
3828 uint32 petguidlow = fields3[0].GetUInt32();
3829 Pet::DeleteFromDB(petguidlow);
3830 } while (resultPets->NextRow());
3831 delete resultPets;
3834 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3835 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3836 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3837 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3838 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3839 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3840 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3841 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3842 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3843 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3844 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3845 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3846 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3847 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3848 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3849 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3850 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3851 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3852 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3853 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3854 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3855 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3856 CharacterDatabase.CommitTransaction();
3858 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3859 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3862 void Player::SetMovement(PlayerMovementType pType)
3864 WorldPacket data;
3865 switch(pType)
3867 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3868 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3869 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3870 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3871 default:
3872 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3873 return;
3875 data.append(GetPackGUID());
3876 data << uint32(0);
3877 GetSession()->SendPacket( &data );
3880 /* Preconditions:
3881 - a resurrectable corpse must not be loaded for the player (only bones)
3882 - the player must be in world
3884 void Player::BuildPlayerRepop()
3886 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3887 data.append(GetPackGUID());
3888 GetSession()->SendPacket(&data);
3890 if(getRace() == RACE_NIGHTELF)
3891 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)
3892 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3894 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3895 // there must be SMSG.STOP_MIRROR_TIMER
3896 // there we must send 888 opcode
3898 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3899 if(GetCorpse())
3901 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3902 assert(false);
3905 // create a corpse and place it at the player's location
3906 CreateCorpse();
3907 Corpse *corpse = GetCorpse();
3908 if(!corpse)
3910 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3911 return;
3913 GetMap()->Add(corpse);
3915 // convert player body to ghost
3916 SetHealth( 1 );
3918 SetMovement(MOVE_WATER_WALK);
3919 if(!GetSession()->isLogingOut())
3920 SetMovement(MOVE_UNROOT);
3922 // BG - remove insignia related
3923 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3925 SendCorpseReclaimDelay();
3927 // to prevent cheating
3928 corpse->ResetGhostTime();
3930 StopMirrorTimers(); //disable timers(bars)
3932 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3934 // set and clear other
3935 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
3938 void Player::SendDelayResponse(const uint32 ml_seconds)
3940 //FIXME: is this delay time arg really need? 50msec by default in code
3941 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3942 data << (uint32)time(NULL);
3943 data << (uint32)0;
3944 GetSession()->SendPacket( &data );
3947 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3949 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3950 data << uint32(-1);
3951 data << float(0);
3952 data << float(0);
3953 data << float(0);
3954 GetSession()->SendPacket(&data);
3956 // speed change, land walk
3958 // remove death flag + set aura
3959 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3960 if(getRace() == RACE_NIGHTELF)
3961 RemoveAurasDueToSpell(20584); // speed bonuses
3962 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3964 setDeathState(ALIVE);
3966 SetMovement(MOVE_LAND_WALK);
3967 SetMovement(MOVE_UNROOT);
3969 m_deathTimer = 0;
3971 // set health/powers (0- will be set in caller)
3972 if(restore_percent>0.0f)
3974 SetHealth(uint32(GetMaxHealth()*restore_percent));
3975 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3976 SetPower(POWER_RAGE, 0);
3977 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3980 // trigger update zone for alive state zone updates
3981 uint32 newzone, newarea;
3982 GetZoneAndAreaId(newzone,newarea);
3983 UpdateZone(newzone,newarea);
3985 // update visibility
3986 ObjectAccessor::UpdateVisibilityForPlayer(this);
3988 if(!applySickness)
3989 return;
3991 //Characters from level 1-10 are not affected by resurrection sickness.
3992 //Characters from level 11-19 will suffer from one minute of sickness
3993 //for each level they are above 10.
3994 //Characters level 20 and up suffer from ten minutes of sickness.
3995 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3997 if(int32(getLevel()) >= startLevel)
3999 // set resurrection sickness
4000 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4002 // not full duration
4003 if(int32(getLevel()) < startLevel+9)
4005 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4007 for(int i =0; i < 3; ++i)
4009 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4011 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4012 Aur->SendAuraUpdate(false);
4019 void Player::KillPlayer()
4021 SetMovement(MOVE_ROOT);
4023 StopMirrorTimers(); //disable timers(bars)
4025 setDeathState(CORPSE);
4026 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4028 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4029 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4031 // 6 minutes until repop at graveyard
4032 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4034 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4036 // don't create corpse at this moment, player might be falling
4038 // update visibility
4039 ObjectAccessor::UpdateObjectVisibility(this);
4042 void Player::CreateCorpse()
4044 // prevent existence 2 corpse for player
4045 SpawnCorpseBones();
4047 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4049 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4050 SetPvPDeath(false);
4052 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4054 delete corpse;
4055 return;
4058 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4059 _pb = GetUInt32Value(PLAYER_BYTES);
4060 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4062 uint8 race = (uint8)(_uf);
4063 uint8 skin = (uint8)(_pb);
4064 uint8 face = (uint8)(_pb >> 8);
4065 uint8 hairstyle = (uint8)(_pb >> 16);
4066 uint8 haircolor = (uint8)(_pb >> 24);
4067 uint8 facialhair = (uint8)(_pb2);
4069 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4070 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4072 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4073 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4075 uint32 flags = CORPSE_FLAG_UNK2;
4076 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4077 flags |= CORPSE_FLAG_HIDE_HELM;
4078 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4079 flags |= CORPSE_FLAG_HIDE_CLOAK;
4080 if(InBattleGround() && !InArena())
4081 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4082 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4084 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4086 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4088 uint32 iDisplayID;
4089 uint16 iIventoryType;
4090 uint32 _cfi;
4091 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4093 if(m_items[i])
4095 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4096 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4098 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4099 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4103 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4104 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4105 assert(entry);
4106 if(entry->map_type != MAP_BATTLEGROUND)
4107 corpse->SaveToDB();
4109 // register for player, but not show
4110 ObjectAccessor::Instance().AddCorpse(corpse);
4113 void Player::SpawnCorpseBones()
4115 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4116 SaveToDB(); // prevent loading as ghost without corpse
4119 Corpse* Player::GetCorpse() const
4121 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4124 void Player::DurabilityLossAll(double percent, bool inventory)
4126 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4127 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4128 DurabilityLoss(pItem,percent);
4130 if(inventory)
4132 // bags not have durability
4133 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4135 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4136 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4137 DurabilityLoss(pItem,percent);
4139 // keys not have durability
4140 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4142 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4143 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4144 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4145 if(Item* pItem = GetItemByPos( i, j ))
4146 DurabilityLoss(pItem,percent);
4150 void Player::DurabilityLoss(Item* item, double percent)
4152 if(!item )
4153 return;
4155 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4157 if(!pMaxDurability)
4158 return;
4160 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4162 if(pDurabilityLoss < 1 )
4163 pDurabilityLoss = 1;
4165 DurabilityPointsLoss(item,pDurabilityLoss);
4168 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4170 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4171 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4172 DurabilityPointsLoss(pItem,points);
4174 if(inventory)
4176 // bags not have durability
4177 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4179 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4180 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4181 DurabilityPointsLoss(pItem,points);
4183 // keys not have durability
4184 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4186 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4187 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4188 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4189 if(Item* pItem = GetItemByPos( i, j ))
4190 DurabilityPointsLoss(pItem,points);
4194 void Player::DurabilityPointsLoss(Item* item, int32 points)
4196 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4197 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4198 int32 pNewDurability = pOldDurability - points;
4200 if (pNewDurability < 0)
4201 pNewDurability = 0;
4202 else if (pNewDurability > pMaxDurability)
4203 pNewDurability = pMaxDurability;
4205 if (pOldDurability != pNewDurability)
4207 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4208 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4209 _ApplyItemMods(item,item->GetSlot(), false);
4211 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4213 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4214 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4215 _ApplyItemMods(item,item->GetSlot(), true);
4217 item->SetState(ITEM_CHANGED, this);
4221 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4223 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4224 DurabilityPointsLoss(pItem,1);
4227 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4229 uint32 TotalCost = 0;
4230 // equipped, backpack, bags itself
4231 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4232 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4234 // bank, buyback and keys not repaired
4236 // items in inventory bags
4237 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4238 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4239 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4240 return TotalCost;
4243 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4245 Item* item = GetItemByPos(pos);
4247 uint32 TotalCost = 0;
4248 if(!item)
4249 return TotalCost;
4251 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4252 if(!maxDurability)
4253 return TotalCost;
4255 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4257 if(cost)
4259 uint32 LostDurability = maxDurability - curDurability;
4260 if(LostDurability>0)
4262 ItemPrototype const *ditemProto = item->GetProto();
4264 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4265 if(!dcost)
4267 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4268 return TotalCost;
4271 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4272 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4273 if(!dQualitymodEntry)
4275 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4276 return TotalCost;
4279 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4280 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4282 costs = uint32(costs * discountMod);
4284 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4285 costs = 1;
4287 if (guildBank)
4289 if (GetGuildId()==0)
4291 DEBUG_LOG("You are not member of a guild");
4292 return TotalCost;
4295 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4296 if (!pGuild)
4297 return TotalCost;
4299 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4301 DEBUG_LOG("You do not have rights to withdraw for repairs");
4302 return TotalCost;
4305 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4307 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4308 return TotalCost;
4311 if (pGuild->GetGuildBankMoney() < costs)
4313 DEBUG_LOG("There is not enough money in bank");
4314 return TotalCost;
4317 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4318 TotalCost = costs;
4320 else if (GetMoney() < costs)
4322 DEBUG_LOG("You do not have enough money");
4323 return TotalCost;
4325 else
4326 ModifyMoney( -int32(costs) );
4330 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4331 item->SetState(ITEM_CHANGED, this);
4333 // reapply mods for total broken and repaired item if equipped
4334 if(IsEquipmentPos(pos) && !curDurability)
4335 _ApplyItemMods(item,pos & 255, true);
4336 return TotalCost;
4339 void Player::RepopAtGraveyard()
4341 // note: this can be called also when the player is alive
4342 // for example from WorldSession::HandleMovementOpcodes
4344 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4346 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4347 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4349 ResurrectPlayer(0.5f);
4350 SpawnCorpseBones();
4353 WorldSafeLocsEntry const *ClosestGrave = NULL;
4355 // Special handle for battleground maps
4356 if( BattleGround *bg = GetBattleGround() )
4357 ClosestGrave = bg->GetClosestGraveYard(this);
4358 else
4359 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4361 // stop countdown until repop
4362 m_deathTimer = 0;
4364 // if no grave found, stay at the current location
4365 // and don't show spirit healer location
4366 if(ClosestGrave)
4368 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4369 if(isDead()) // not send if alive, because it used in TeleportTo()
4371 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4372 data << ClosestGrave->map_id;
4373 data << ClosestGrave->x;
4374 data << ClosestGrave->y;
4375 data << ClosestGrave->z;
4376 GetSession()->SendPacket(&data);
4381 void Player::JoinedChannel(Channel *c)
4383 m_channels.push_back(c);
4386 void Player::LeftChannel(Channel *c)
4388 m_channels.remove(c);
4391 void Player::CleanupChannels()
4393 while(!m_channels.empty())
4395 Channel* ch = *m_channels.begin();
4396 m_channels.erase(m_channels.begin()); // remove from player's channel list
4397 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4398 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4399 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4402 sLog.outDebug("Player: channels cleaned up!");
4405 void Player::UpdateLocalChannels(uint32 newZone )
4407 if(m_channels.empty())
4408 return;
4410 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4411 if(!current_zone)
4412 return;
4414 ChannelMgr* cMgr = channelMgr(GetTeam());
4415 if(!cMgr)
4416 return;
4418 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4420 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4422 next = i; ++next;
4424 // skip non built-in channels
4425 if(!(*i)->IsConstant())
4426 continue;
4428 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4429 if(!ch)
4430 continue;
4432 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4433 continue;
4435 // new channel
4436 char new_channel_name_buf[100];
4437 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4438 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4440 if((*i)!=new_channel)
4442 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4444 // leave old channel
4445 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4446 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4447 LeftChannel(*i); // remove from player's channel list
4448 cMgr->LeftChannel(name); // delete if empty
4451 sLog.outDebug("Player: channels cleaned up!");
4454 void Player::LeaveLFGChannel()
4456 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4458 if((*i)->IsLFG())
4460 (*i)->Leave(GetGUID());
4461 break;
4466 void Player::UpdateDefense()
4468 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4470 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4472 // update dependent from defense skill part
4473 UpdateDefenseBonusesMod();
4477 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4479 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4481 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4482 return;
4485 float val = 1.0f;
4487 switch(modType)
4489 case FLAT_MOD:
4490 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4491 break;
4492 case PCT_MOD:
4493 if(amount <= -100.0f)
4494 amount = -200.0f;
4496 val = (100.0f + amount) / 100.0f;
4497 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4498 break;
4501 if(!CanModifyStats())
4502 return;
4504 switch(modGroup)
4506 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4507 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4508 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4509 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4510 default: break;
4514 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4516 if(modGroup >= BASEMOD_END || modType > MOD_END)
4518 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4519 return 0.0f;
4522 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4523 return 0.0f;
4525 return m_auraBaseMod[modGroup][modType];
4528 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4530 if(modGroup >= BASEMOD_END)
4532 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4533 return 0.0f;
4536 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4537 return 0.0f;
4539 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4542 uint32 Player::GetShieldBlockValue() const
4544 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4546 value = (value < 0) ? 0 : value;
4548 return uint32(value);
4551 float Player::GetMeleeCritFromAgility()
4553 uint32 level = getLevel();
4554 uint32 pclass = getClass();
4556 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4558 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4559 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4560 if (critBase==NULL || critRatio==NULL)
4561 return 0.0f;
4563 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4564 return crit*100.0f;
4567 float Player::GetDodgeFromAgility()
4569 // Table for base dodge values
4570 float dodge_base[MAX_CLASSES] = {
4571 0.0075f, // Warrior
4572 0.00652f, // Paladin
4573 -0.0545f, // Hunter
4574 -0.0059f, // Rogue
4575 0.03183f, // Priest
4576 0.0114f, // DK
4577 0.0167f, // Shaman
4578 0.034575f, // Mage
4579 0.02011f, // Warlock
4580 0.0f, // ??
4581 -0.0187f // Druid
4583 // Crit/agility to dodge/agility coefficient multipliers
4584 float crit_to_dodge[MAX_CLASSES] = {
4585 1.1f, // Warrior
4586 1.0f, // Paladin
4587 1.6f, // Hunter
4588 2.0f, // Rogue
4589 1.0f, // Priest
4590 1.0f, // DK?
4591 1.0f, // Shaman
4592 1.0f, // Mage
4593 1.0f, // Warlock
4594 0.0f, // ??
4595 1.7f // Druid
4598 uint32 level = getLevel();
4599 uint32 pclass = getClass();
4601 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4603 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4604 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4605 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4606 return 0.0f;
4608 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4609 return dodge*100.0f;
4612 float Player::GetSpellCritFromIntellect()
4614 uint32 level = getLevel();
4615 uint32 pclass = getClass();
4617 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4619 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4620 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4621 if (critBase==NULL || critRatio==NULL)
4622 return 0.0f;
4624 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4625 return crit*100.0f;
4628 float Player::GetRatingCoefficient(CombatRating cr) const
4630 uint32 level = getLevel();
4632 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4634 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4635 if (Rating == NULL)
4636 return 1.0f; // By default use minimum coefficient (not must be called)
4638 return Rating->ratio;
4641 float Player::GetRatingBonusValue(CombatRating cr) const
4643 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4646 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4648 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f;
4649 if (melee>33.0f) melee = 33.0f;
4650 return uint32 (melee * damage /100.0f);
4653 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4655 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f;
4656 if (ranged>33.0f) ranged=33.0f;
4657 return uint32 (ranged * damage /100.0f);
4660 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4662 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f;
4663 // In wow script resilience limited to 33%
4664 if (spell>33.0f)
4665 spell = 33.0f;
4666 return uint32 (spell * damage / 100.0f);
4669 uint32 Player::GetDotDamageReduction(uint32 damage) const
4671 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4672 // Dot resilience not limited (limit it by 100%)
4673 if (spellDot > 100.0f)
4674 spellDot = 100.0f;
4675 return uint32 (spellDot * damage / 100.0f);
4678 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4680 switch (attType)
4682 case BASE_ATTACK:
4683 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4684 case OFF_ATTACK:
4685 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4686 default:
4687 break;
4689 return 0.0f;
4692 float Player::OCTRegenHPPerSpirit()
4694 uint32 level = getLevel();
4695 uint32 pclass = getClass();
4697 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4699 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4700 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4701 if (baseRatio==NULL || moreRatio==NULL)
4702 return 0.0f;
4704 // Formula from PaperDollFrame script
4705 float spirit = GetStat(STAT_SPIRIT);
4706 float baseSpirit = spirit;
4707 if (baseSpirit>50) baseSpirit = 50;
4708 float moreSpirit = spirit - baseSpirit;
4709 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4710 return regen;
4713 float Player::OCTRegenMPPerSpirit()
4715 uint32 level = getLevel();
4716 uint32 pclass = getClass();
4718 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4720 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4721 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4722 if (moreRatio==NULL)
4723 return 0.0f;
4725 // Formula get from PaperDollFrame script
4726 float spirit = GetStat(STAT_SPIRIT);
4727 float regen = spirit * moreRatio->ratio;
4728 return regen;
4731 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4733 m_baseRatingValue[cr]+=(apply ? value : -value);
4735 int32 amount = uint32(m_baseRatingValue[cr]);
4736 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4737 // stat used stored in miscValueB for this aura
4738 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4739 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4740 if ((*i)->GetMiscValue() & (1<<cr))
4741 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4742 if (amount < 0)
4743 amount = 0;
4744 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4746 float RatingCoeffecient = GetRatingCoefficient(cr);
4747 float RatingChange = 0.0f;
4749 bool affectStats = CanModifyStats();
4751 switch (cr)
4753 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4754 case CR_DEFENSE_SKILL:
4755 UpdateDefenseBonusesMod();
4756 break;
4757 case CR_DODGE:
4758 UpdateDodgePercentage();
4759 break;
4760 case CR_PARRY:
4761 UpdateParryPercentage();
4762 break;
4763 case CR_BLOCK:
4764 UpdateBlockPercentage();
4765 break;
4766 case CR_HIT_MELEE:
4767 UpdateMeleeHitChances();
4768 break;
4769 case CR_HIT_RANGED:
4770 UpdateRangedHitChances();
4771 break;
4772 case CR_HIT_SPELL:
4773 UpdateSpellHitChances();
4774 break;
4775 case CR_CRIT_MELEE:
4776 if(affectStats)
4778 UpdateCritPercentage(BASE_ATTACK);
4779 UpdateCritPercentage(OFF_ATTACK);
4781 break;
4782 case CR_CRIT_RANGED:
4783 if(affectStats)
4784 UpdateCritPercentage(RANGED_ATTACK);
4785 break;
4786 case CR_CRIT_SPELL:
4787 if(affectStats)
4788 UpdateAllSpellCritChances();
4789 break;
4790 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4791 case CR_HIT_TAKEN_RANGED:
4792 break;
4793 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4794 break;
4795 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4796 case CR_CRIT_TAKEN_RANGED:
4797 break;
4798 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4799 break;
4800 case CR_HASTE_MELEE:
4801 RatingChange = value / RatingCoeffecient;
4802 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4803 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4804 break;
4805 case CR_HASTE_RANGED:
4806 RatingChange = value / RatingCoeffecient;
4807 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4808 break;
4809 case CR_HASTE_SPELL:
4810 RatingChange = value / RatingCoeffecient;
4811 ApplyCastTimePercentMod(RatingChange,apply);
4812 break;
4813 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4814 case CR_WEAPON_SKILL_OFFHAND:
4815 case CR_WEAPON_SKILL_RANGED:
4816 break;
4817 case CR_EXPERTISE:
4818 if(affectStats)
4820 UpdateExpertise(BASE_ATTACK);
4821 UpdateExpertise(OFF_ATTACK);
4823 break;
4827 void Player::SetRegularAttackTime()
4829 for(int i = 0; i < MAX_ATTACK; ++i)
4831 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4832 if(tmpitem && !tmpitem->IsBroken())
4834 ItemPrototype const *proto = tmpitem->GetProto();
4835 if(proto->Delay)
4836 SetAttackTime(WeaponAttackType(i), proto->Delay);
4837 else
4838 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4843 //skill+step, checking for max value
4844 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4846 if(!skill_id)
4847 return false;
4849 uint16 i=0;
4850 for (; i < PLAYER_MAX_SKILLS; ++i)
4851 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4852 break;
4854 if(i>=PLAYER_MAX_SKILLS)
4855 return false;
4857 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4858 uint32 value = SKILL_VALUE(data);
4859 uint32 max = SKILL_MAX(data);
4861 if ((!max) || (!value) || (value >= max))
4862 return false;
4864 if (value*512 < max*urand(0,512))
4866 uint32 new_value = value+step;
4867 if(new_value > max)
4868 new_value = max;
4870 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4871 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
4872 return true;
4875 return false;
4878 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4880 if ( SkillValue >= GrayLevel )
4881 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4882 if ( SkillValue >= GreenLevel )
4883 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4884 if ( SkillValue >= YellowLevel )
4885 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4886 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4889 bool Player::UpdateCraftSkill(uint32 spellid)
4891 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4893 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4894 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4896 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4898 if(_spell_idx->second->skillId)
4900 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4902 // Alchemy Discoveries here
4903 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4904 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4906 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4907 learnSpell(discoveredSpell,false);
4910 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4912 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4913 _spell_idx->second->max_value,
4914 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4915 _spell_idx->second->min_value),
4916 craft_skill_gain);
4919 return false;
4922 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4924 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4926 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4928 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4929 switch (SkillId)
4931 case SKILL_HERBALISM:
4932 case SKILL_LOCKPICKING:
4933 case SKILL_JEWELCRAFTING:
4934 case SKILL_INSCRIPTION:
4935 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4936 case SKILL_SKINNING:
4937 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4938 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4939 else
4940 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4941 case SKILL_MINING:
4942 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4943 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4944 else
4945 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4947 return false;
4950 bool Player::UpdateFishingSkill()
4952 sLog.outDebug("UpdateFishingSkill");
4954 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4956 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4958 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4960 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4963 // levels sync. with spell requirement for skill levels to learn
4964 // bonus abilities in sSkillLineAbilityStore
4965 // Used only to avoid scan DBC at each skill grow
4966 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
4968 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4970 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4971 if ( !SkillId )
4972 return false;
4974 if(Chance <= 0) // speedup in 0 chance case
4976 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4977 return false;
4980 uint16 i=0;
4981 for (; i < PLAYER_MAX_SKILLS; ++i)
4982 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4983 if ( i >= PLAYER_MAX_SKILLS )
4984 return false;
4986 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4987 uint16 SkillValue = SKILL_VALUE(data);
4988 uint16 MaxValue = SKILL_MAX(data);
4990 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4991 return false;
4993 int32 Roll = irand(1,1000);
4995 if ( Roll <= Chance )
4997 uint32 new_value = SkillValue+step;
4998 if(new_value > MaxValue)
4999 new_value = MaxValue;
5001 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
5002 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5004 if((SkillValue < *bsl && new_value >= *bsl))
5006 learnSkillRewardedSpells( SkillId, new_value);
5007 break;
5010 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5011 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5012 return true;
5015 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5016 return false;
5019 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5021 // no skill gain in pvp
5022 Unit *pVictim = getVictim();
5023 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5024 return;
5026 if(IsInFeralForm())
5027 return; // always maximized SKILL_FERAL_COMBAT in fact
5029 if(m_form == FORM_TREE)
5030 return; // use weapon but not skill up
5032 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5034 switch(attType)
5036 case BASE_ATTACK:
5038 Item *tmpitem = GetWeaponForAttack(attType,true);
5040 if (!tmpitem)
5041 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5042 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5043 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5044 break;
5046 case OFF_ATTACK:
5047 case RANGED_ATTACK:
5049 Item *tmpitem = GetWeaponForAttack(attType,true);
5050 if (tmpitem)
5051 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5052 break;
5055 UpdateAllCritPercentages();
5058 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5060 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5061 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5062 uint32 moblevel = pVictim->getLevelForTarget(this);
5063 if(moblevel < greylevel)
5064 return;
5066 if (moblevel > plevel + 5)
5067 moblevel = plevel + 5;
5069 uint32 lvldif = moblevel - greylevel;
5070 if(lvldif < 3)
5071 lvldif = 3;
5073 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5074 if(skilldif <= 0)
5075 return;
5077 float chance = float(3 * lvldif * skilldif) / plevel;
5078 if(!defence)
5080 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5081 chance *= 0.1f * GetStat(STAT_INTELLECT);
5084 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5086 if(roll_chance_f(chance))
5088 if(defence)
5089 UpdateDefense();
5090 else
5091 UpdateWeaponSkill(attType);
5093 else
5094 return;
5097 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5099 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5100 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5102 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5103 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5104 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5106 if(talent) // permanent bonus stored in high part
5107 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5108 else // temporary/item bonus stored in low part
5109 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5110 return;
5114 void Player::UpdateSkillsForLevel()
5116 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5117 uint32 maxSkill = GetMaxSkillValueForLevel();
5119 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5121 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5122 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5124 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5126 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5127 if(!pSkill)
5128 continue;
5130 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5131 continue;
5133 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5134 uint32 max = SKILL_MAX(data);
5135 uint32 val = SKILL_VALUE(data);
5137 /// update only level dependent max skill values
5138 if(max!=1)
5140 /// miximize skill always
5141 if(alwaysMaxSkill)
5142 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5143 /// update max skill value if current max skill not maximized
5144 else if(max != maxconfskill)
5145 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5150 void Player::UpdateSkillsToMaxSkillsForLevel()
5152 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5153 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5155 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5156 if( IsProfessionOrRidingSkill(pskill))
5157 continue;
5158 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5160 uint32 max = SKILL_MAX(data);
5162 if(max > 1)
5163 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5165 if(pskill == SKILL_DEFENSE)
5166 UpdateDefenseBonusesMod();
5170 // This functions sets a skill line value (and adds if doesn't exist yet)
5171 // To "remove" a skill line, set it's values to zero
5172 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5174 if(!id)
5175 return;
5177 uint16 i=0;
5178 for (; i < PLAYER_MAX_SKILLS; ++i)
5179 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5181 if(i<PLAYER_MAX_SKILLS) //has skill
5183 if(currVal)
5185 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5186 learnSkillRewardedSpells(id, currVal);
5187 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5188 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5190 else //remove
5192 // clear skill fields
5193 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5194 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5195 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5197 // remove all spells that related to this skill
5198 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5199 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5200 if (pAbility->skillId==id)
5201 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5204 else if(currVal) //add
5206 for (i=0; i < PLAYER_MAX_SKILLS; ++i)
5207 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5209 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5210 if(!pSkill)
5212 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5213 return;
5215 // enable unlearn button for primary professions only
5216 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5217 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5218 else
5219 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5220 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5221 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5222 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5224 // apply skill bonuses
5225 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5227 // temporary bonuses
5228 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5229 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5230 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5231 (*j)->ApplyModifier(true);
5233 // permanent bonuses
5234 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5235 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5236 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5237 (*j)->ApplyModifier(true);
5239 // Learn all spells for skill
5240 learnSkillRewardedSpells(id, currVal);
5241 return;
5246 bool Player::HasSkill(uint32 skill) const
5248 if(!skill)return false;
5249 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5251 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5253 return true;
5256 return false;
5259 uint16 Player::GetSkillValue(uint32 skill) const
5261 if(!skill)
5262 return 0;
5264 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5266 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5268 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5270 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5271 result += SKILL_TEMP_BONUS(bonus);
5272 result += SKILL_PERM_BONUS(bonus);
5273 return result < 0 ? 0 : result;
5276 return 0;
5279 uint16 Player::GetMaxSkillValue(uint32 skill) const
5281 if(!skill)return 0;
5282 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5284 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5286 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5288 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5289 result += SKILL_TEMP_BONUS(bonus);
5290 result += SKILL_PERM_BONUS(bonus);
5291 return result < 0 ? 0 : result;
5294 return 0;
5297 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5299 if(!skill)return 0;
5300 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5302 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5304 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5307 return 0;
5310 uint16 Player::GetBaseSkillValue(uint32 skill) const
5312 if(!skill)return 0;
5313 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5315 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5317 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5318 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5319 return result < 0 ? 0 : result;
5322 return 0;
5325 uint16 Player::GetPureSkillValue(uint32 skill) const
5327 if(!skill)return 0;
5328 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5330 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5332 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5335 return 0;
5338 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5340 if(!skill)
5341 return 0;
5343 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5345 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5347 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5351 return 0;
5354 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5356 if(!skill)
5357 return 0;
5359 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5361 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5363 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5367 return 0;
5370 void Player::SendInitialActionButtons()
5372 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5374 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5375 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5377 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5378 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5380 data << uint16(itr->second.action);
5381 data << uint8(itr->second.misc);
5382 data << uint8(itr->second.type);
5384 else
5386 data << uint32(0);
5390 GetSession()->SendPacket( &data );
5391 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5394 bool Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5396 if(button >= MAX_ACTION_BUTTONS)
5398 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5399 return false;
5402 // check cheating with adding non-known spells to action bar
5403 if(type==ACTION_BUTTON_SPELL)
5405 if(!sSpellStore.LookupEntry(action))
5407 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5408 return false;
5411 if(!HasSpell(action))
5413 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5414 return false;
5418 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5420 if (buttonItr==m_actionButtons.end())
5421 { // just add new button
5422 m_actionButtons[button] = ActionButton(action,type,misc);
5424 else
5425 { // change state of current button
5426 ActionButtonUpdateState uState = buttonItr->second.uState;
5427 buttonItr->second = ActionButton(action,type,misc);
5428 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5431 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5432 return true;
5435 void Player::removeActionButton(uint8 button)
5437 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5438 if (buttonItr==m_actionButtons.end())
5439 return;
5441 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5442 m_actionButtons.erase(buttonItr); // new and not saved
5443 else
5444 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5446 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5449 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5451 // prevent crash when a bad coord is sent by the client
5452 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5454 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5455 return false;
5458 Map *m = GetMap();
5460 const float old_x = GetPositionX();
5461 const float old_y = GetPositionY();
5462 const float old_z = GetPositionZ();
5463 const float old_r = GetOrientation();
5465 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5467 if (teleport || old_x != x || old_y != y || old_z != z)
5468 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5469 else
5470 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5472 // move and update visible state if need
5473 m->PlayerRelocation(this, x, y, z, orientation);
5475 // reread after Map::Relocation
5476 m = GetMap();
5477 x = GetPositionX();
5478 y = GetPositionY();
5479 z = GetPositionZ();
5481 // group update
5482 if(GetGroup() && (old_x != x || old_y != y))
5483 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5486 // code block for underwater state update
5487 UpdateUnderwaterState(m, x, y, z);
5489 CheckExploreSystem();
5491 return true;
5494 void Player::SaveRecallPosition()
5496 m_recallMap = GetMapId();
5497 m_recallX = GetPositionX();
5498 m_recallY = GetPositionY();
5499 m_recallZ = GetPositionZ();
5500 m_recallO = GetOrientation();
5503 void Player::SendMessageToSet(WorldPacket *data, bool self)
5505 GetMap()->MessageBroadcast(this, data, self);
5508 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5510 GetMap()->MessageDistBroadcast(this, data, dist, self);
5513 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5515 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5518 void Player::SendDirectMessage(WorldPacket *data)
5520 GetSession()->SendPacket(data);
5523 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5525 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5526 data << uint32(CinematicSequenceId);
5527 SendDirectMessage(&data);
5530 void Player::SendMovieStart(uint32 MovieId)
5532 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5533 data << uint32(MovieId);
5534 SendDirectMessage(&data);
5537 void Player::CheckExploreSystem()
5539 if (!isAlive())
5540 return;
5542 if (isInFlight())
5543 return;
5545 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5546 if(areaFlag==0xffff)
5547 return;
5548 int offset = areaFlag / 32;
5550 if(offset >= 128)
5552 sLog.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset);
5553 return;
5556 uint32 val = (uint32)(1 << (areaFlag % 32));
5557 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5559 if( !(currFields & val) )
5561 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5563 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5565 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5566 if(!p)
5568 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5570 else if(p->area_level > 0)
5572 uint32 area = p->ID;
5573 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5575 SendExplorationExperience(area,0);
5577 else
5579 int32 diff = int32(getLevel()) - p->area_level;
5580 uint32 XP = 0;
5581 if (diff < -5)
5583 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5585 else if (diff > 5)
5587 int32 exploration_percent = (100-((diff-5)*5));
5588 if (exploration_percent > 100)
5589 exploration_percent = 100;
5590 else if (exploration_percent < 0)
5591 exploration_percent = 0;
5593 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5595 else
5597 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5600 GiveXP( XP, NULL );
5601 SendExplorationExperience(area,XP);
5603 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5608 uint32 Player::TeamForRace(uint8 race)
5610 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5611 if(!rEntry)
5613 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5614 return ALLIANCE;
5617 switch(rEntry->TeamID)
5619 case 7: return ALLIANCE;
5620 case 1: return HORDE;
5623 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5624 return ALLIANCE;
5627 uint32 Player::getFactionForRace(uint8 race)
5629 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5630 if(!rEntry)
5632 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5633 return 0;
5636 return rEntry->FactionID;
5639 void Player::setFactionForRace(uint8 race)
5641 m_team = TeamForRace(race);
5642 setFaction( getFactionForRace(race) );
5645 ReputationRank Player::GetReputationRank(uint32 faction) const
5647 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5648 return GetReputationMgr().GetRank(factionEntry);
5651 //Calculate total reputation percent player gain with quest/creature level
5652 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5654 float percent = 100.0f;
5656 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5658 if(rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5659 percent *= rate;
5661 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5663 percent += rep > 0 ? repMod : -repMod;
5665 if(percent <= 0.0f)
5666 return 0;
5668 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5671 //Calculates how many reputation points player gains in victim's enemy factions
5672 void Player::RewardReputation(Unit *pVictim, float rate)
5674 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5675 return;
5677 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5679 if(!Rep)
5680 return;
5682 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5684 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5685 donerep1 = int32(donerep1*rate);
5686 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5687 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5688 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5689 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5691 // Wiki: Team factions value divided by 2
5692 if (factionEntry1 && Rep->is_teamaward1)
5694 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5695 if(team1_factionEntry)
5696 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5700 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5702 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5703 donerep2 = int32(donerep2*rate);
5704 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5705 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5706 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5707 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5709 // Wiki: Team factions value divided by 2
5710 if (factionEntry2 && Rep->is_teamaward2)
5712 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5713 if(team2_factionEntry)
5714 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5719 //Calculate how many reputation points player gain with the quest
5720 void Player::RewardReputation(Quest const *pQuest)
5722 // quest reputation reward/loss
5723 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5725 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5727 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest),pQuest->RewRepValue[i],true);
5728 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5729 if(factionEntry)
5730 GetReputationMgr().ModifyReputation(factionEntry, rep);
5734 // TODO: implement reputation spillover
5737 void Player::UpdateArenaFields(void)
5739 /* arena calcs go here */
5742 void Player::UpdateHonorFields()
5744 /// called when rewarding honor and at each save
5745 uint64 now = time(NULL);
5746 uint64 today = uint64(time(NULL) / DAY) * DAY;
5748 if(m_lastHonorUpdateTime < today)
5750 uint64 yesterday = today - DAY;
5752 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5754 // update yesterday's contribution
5755 if(m_lastHonorUpdateTime >= yesterday )
5757 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5759 // this is the first update today, reset today's contribution
5760 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5761 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5763 else
5765 // no honor/kills yesterday or today, reset
5766 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5767 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5771 m_lastHonorUpdateTime = now;
5774 ///Calculate the amount of honor gained based on the victim
5775 ///and the size of the group for which the honor is divided
5776 ///An exact honor value can also be given (overriding the calcs)
5777 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5779 // do not reward honor in arenas, but enable onkill spellproc
5780 if(InArena())
5782 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5783 return false;
5785 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5786 return false;
5788 return true;
5791 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5792 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5793 return false;
5795 uint64 victim_guid = 0;
5796 uint32 victim_rank = 0;
5798 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5799 UpdateHonorFields();
5801 if(honor <= 0)
5803 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5804 return false;
5806 victim_guid = uVictim->GetGUID();
5808 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5810 Player *pVictim = (Player *)uVictim;
5812 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5813 return false;
5815 float f = 1; //need for total kills (?? need more info)
5816 uint32 k_grey = 0;
5817 uint32 k_level = getLevel();
5818 uint32 v_level = pVictim->getLevel();
5821 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5822 // [0] Just name
5823 // [1..14] Alliance honor titles and player name
5824 // [15..28] Horde honor titles and player name
5825 // [29..38] Other title and player name
5826 // [39+] Nothing
5827 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5828 // Get Killer titles, CharTitlesEntry::bit_index
5829 // Ranks:
5830 // title[1..14] -> rank[5..18]
5831 // title[15..28] -> rank[5..18]
5832 // title[other] -> 0
5833 if (victim_title == 0)
5834 victim_guid = 0; // Don't show HK: <rank> message, only log.
5835 else if (victim_title < 15)
5836 victim_rank = victim_title + 4;
5837 else if (victim_title < 29)
5838 victim_rank = victim_title - 14 + 4;
5839 else
5840 victim_guid = 0; // Don't show HK: <rank> message, only log.
5843 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
5845 if(v_level<=k_grey)
5846 return false;
5848 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5850 int32 v_rank =1; //need more info
5852 honor = ((f * diff_level * (190 + v_rank*10))/6);
5853 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5855 // count the number of playerkills in one day
5856 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5857 // and those in a lifetime
5858 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5859 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
5861 else
5863 Creature *cVictim = (Creature *)uVictim;
5865 if (!cVictim->isRacialLeader())
5866 return false;
5868 honor = 100; // ??? need more info
5869 victim_rank = 19; // HK: Leader
5873 if (uVictim != NULL)
5875 honor *= sWorld.getRate(RATE_HONOR);
5877 if(groupsize > 1)
5878 honor /= groupsize;
5880 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5883 // honor - for show honor points in log
5884 // victim_guid - for show victim name in log
5885 // victim_rank [1..4] HK: <dishonored rank>
5886 // victim_rank [5..19] HK: <alliance\horde rank>
5887 // victim_rank [0,20+] HK: <>
5888 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5889 data << (uint32) honor;
5890 data << (uint64) victim_guid;
5891 data << (uint32) victim_rank;
5893 GetSession()->SendPacket(&data);
5895 // add honor points
5896 ModifyHonorPoints(int32(honor));
5898 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5899 return true;
5902 void Player::ModifyHonorPoints( int32 value )
5904 if(value < 0)
5906 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5907 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
5908 else
5909 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
5911 else
5912 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
5915 void Player::ModifyArenaPoints( int32 value )
5917 if(value < 0)
5919 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
5920 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
5921 else
5922 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
5924 else
5925 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
5928 uint32 Player::GetGuildIdFromDB(uint64 guid)
5930 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
5931 if(!result)
5932 return 0;
5934 uint32 id = result->Fetch()[0].GetUInt32();
5935 delete result;
5936 return id;
5939 uint32 Player::GetRankFromDB(uint64 guid)
5941 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
5942 if( result )
5944 uint32 v = result->Fetch()[0].GetUInt32();
5945 delete result;
5946 return v;
5948 else
5949 return 0;
5952 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
5954 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);
5955 if(!result)
5956 return 0;
5958 uint32 id = (*result)[0].GetUInt32();
5959 delete result;
5960 return id;
5963 uint32 Player::GetZoneIdFromDB(uint64 guid)
5965 uint32 guidLow = GUID_LOPART(guid);
5966 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
5967 if (!result)
5968 return 0;
5969 Field* fields = result->Fetch();
5970 uint32 zone = fields[0].GetUInt32();
5971 delete result;
5973 if (!zone)
5975 // stored zone is zero, use generic and slow zone detection
5976 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
5977 if( !result )
5978 return 0;
5979 fields = result->Fetch();
5980 uint32 map = fields[0].GetUInt32();
5981 float posx = fields[1].GetFloat();
5982 float posy = fields[2].GetFloat();
5983 float posz = fields[3].GetFloat();
5984 delete result;
5986 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
5988 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
5991 return zone;
5994 void Player::UpdateArea(uint32 newArea)
5996 // FFA_PVP flags are area and not zone id dependent
5997 // so apply them accordingly
5998 m_areaUpdateId = newArea;
6000 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6002 if(area && (area->flags & AREA_FLAG_ARENA))
6004 if(!isGameMaster())
6005 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6007 else
6009 // remove ffa flag only if not ffapvp realm
6010 // removal in sanctuaries and capitals is handled in zone update
6011 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6012 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6015 UpdateAreaDependentAuras(newArea);
6018 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6020 if(m_zoneUpdateId != newZone)
6021 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6023 m_zoneUpdateId = newZone;
6024 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6026 // zone changed, so area changed as well, update it
6027 UpdateArea(newArea);
6029 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6030 if(!zone)
6031 return;
6033 if (sWorld.getConfig(CONFIG_WEATHER))
6035 Weather *wth = sWorld.FindWeather(zone->ID);
6036 if(wth)
6038 wth->SendWeatherUpdateToPlayer(this);
6040 else
6042 if(!sWorld.AddWeather(zone->ID))
6044 // send fine weather packet to remove old zone's weather
6045 Weather::SendFineWeatherUpdateToPlayer(this);
6050 pvpInfo.inHostileArea =
6051 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6052 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6053 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6054 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6056 if(pvpInfo.inHostileArea) // in hostile area
6058 if(!IsPvP() || pvpInfo.endTimer != 0)
6059 UpdatePvP(true, true);
6061 else // in friendly area
6063 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6064 pvpInfo.endTimer = time(0); // start toggle-off
6067 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6069 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6070 if(sWorld.IsFFAPvPRealm())
6071 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6073 else
6075 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6078 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6080 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6081 SetRestType(REST_TYPE_IN_CITY);
6082 InnEnter(time(0),GetMapId(),0,0,0);
6084 if(sWorld.IsFFAPvPRealm())
6085 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6087 else // anywhere else
6089 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6091 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6093 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6095 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6096 SetRestType(REST_TYPE_NO);
6098 if(sWorld.IsFFAPvPRealm())
6099 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6102 else // not in tavern (leave city then)
6104 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6105 SetRestType(REST_TYPE_NO);
6107 // Set player to FFA PVP when not in rested environment.
6108 if(sWorld.IsFFAPvPRealm())
6109 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6114 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6115 // if player resurrected at teleport this will be applied in resurrect code
6116 if(isAlive())
6117 DestroyZoneLimitedItem( true, newZone );
6119 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6120 AutoUnequipOffhandIfNeed();
6122 // recent client version not send leave/join channel packets for built-in local channels
6123 UpdateLocalChannels( newZone );
6125 // group update
6126 if(GetGroup())
6127 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6129 UpdateZoneDependentAuras(newZone);
6132 //If players are too far way of duel flag... then player loose the duel
6133 void Player::CheckDuelDistance(time_t currTime)
6135 if(!duel)
6136 return;
6138 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6139 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6140 if(!obj)
6141 return;
6143 if(duel->outOfBound == 0)
6145 if(!IsWithinDistInMap(obj, 50))
6147 duel->outOfBound = currTime;
6149 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6150 GetSession()->SendPacket(&data);
6153 else
6155 if(IsWithinDistInMap(obj, 40))
6157 duel->outOfBound = 0;
6159 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6160 GetSession()->SendPacket(&data);
6162 else if(currTime >= (duel->outOfBound+10))
6164 DuelComplete(DUEL_FLED);
6169 void Player::DuelComplete(DuelCompleteType type)
6171 // duel not requested
6172 if(!duel)
6173 return;
6175 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6176 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6177 GetSession()->SendPacket(&data);
6178 duel->opponent->GetSession()->SendPacket(&data);
6180 if(type != DUEL_INTERUPTED)
6182 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6183 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6184 data << duel->opponent->GetName();
6185 data << GetName();
6186 SendMessageToSet(&data,true);
6189 // cool-down duel spell
6190 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6192 data<<GetGUID();
6193 data<<uint8(0x0);
6195 data<<(uint32)7266;
6196 data<<uint32(0x0);
6197 GetSession()->SendPacket(&data);
6198 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6199 data<<duel->opponent->GetGUID();
6200 data<<uint8(0x0);
6201 data<<(uint32)7266;
6202 data<<uint32(0x0);
6203 duel->opponent->GetSession()->SendPacket(&data);*/
6205 //Remove Duel Flag object
6206 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6207 if(obj)
6208 duel->initiator->RemoveGameObject(obj,true);
6210 /* remove auras */
6211 std::vector<uint32> auras2remove;
6212 AuraMap const& vAuras = duel->opponent->GetAuras();
6213 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6215 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6216 auras2remove.push_back(i->second->GetId());
6219 for(size_t i=0; i<auras2remove.size(); ++i)
6220 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6222 auras2remove.clear();
6223 AuraMap const& auras = GetAuras();
6224 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6226 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6227 auras2remove.push_back(i->second->GetId());
6229 for(size_t i=0; i<auras2remove.size(); ++i)
6230 RemoveAurasDueToSpell(auras2remove[i]);
6232 // cleanup combo points
6233 if(GetComboTarget()==duel->opponent->GetGUID())
6234 ClearComboPoints();
6235 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6236 ClearComboPoints();
6238 if(duel->opponent->GetComboTarget()==GetGUID())
6239 duel->opponent->ClearComboPoints();
6240 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6241 duel->opponent->ClearComboPoints();
6243 //cleanups
6244 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6245 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6246 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6247 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6249 delete duel->opponent->duel;
6250 duel->opponent->duel = NULL;
6251 delete duel;
6252 duel = NULL;
6255 //---------------------------------------------------------//
6257 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6259 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6260 return;
6262 // not apply/remove mods for broken item
6263 if(item->IsBroken())
6264 return;
6266 ItemPrototype const *proto = item->GetProto();
6268 if(!proto)
6269 return;
6271 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6273 uint32 attacktype = Player::GetAttackBySlot(slot);
6274 if(attacktype < MAX_ATTACK)
6275 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6277 _ApplyItemBonuses(proto,slot,apply);
6279 if( slot==EQUIPMENT_SLOT_RANGED )
6280 _ApplyAmmoBonuses();
6282 ApplyItemEquipSpell(item,apply);
6283 ApplyEnchantment(item, apply);
6285 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6286 CorrectMetaGemEnchants(slot, apply);
6288 sLog.outDebug("_ApplyItemMods complete.");
6291 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6293 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6294 return;
6296 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6298 uint32 statType = 0;
6299 int32 val = 0;
6301 if(proto->ScalingStatDistribution)
6303 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6305 statType = ssd->StatMod[i];
6307 if(uint32 modifier = ssd->Modifier[i])
6309 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6310 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6312 uint32 multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6313 val = (multiplier * modifier) / 10000;
6318 else
6320 statType = proto->ItemStat[i].ItemStatType;
6321 val = proto->ItemStat[i].ItemStatValue;
6324 if(val == 0)
6325 continue;
6327 switch (statType)
6329 case ITEM_MOD_MANA:
6330 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6331 break;
6332 case ITEM_MOD_HEALTH: // modify HP
6333 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6334 break;
6335 case ITEM_MOD_AGILITY: // modify agility
6336 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6337 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6338 break;
6339 case ITEM_MOD_STRENGTH: //modify strength
6340 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6341 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6342 break;
6343 case ITEM_MOD_INTELLECT: //modify intellect
6344 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6345 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6346 break;
6347 case ITEM_MOD_SPIRIT: //modify spirit
6348 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6349 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6350 break;
6351 case ITEM_MOD_STAMINA: //modify stamina
6352 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6353 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6354 break;
6355 case ITEM_MOD_DEFENSE_SKILL_RATING:
6356 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6357 break;
6358 case ITEM_MOD_DODGE_RATING:
6359 ApplyRatingMod(CR_DODGE, int32(val), apply);
6360 break;
6361 case ITEM_MOD_PARRY_RATING:
6362 ApplyRatingMod(CR_PARRY, int32(val), apply);
6363 break;
6364 case ITEM_MOD_BLOCK_RATING:
6365 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6366 break;
6367 case ITEM_MOD_HIT_MELEE_RATING:
6368 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6369 break;
6370 case ITEM_MOD_HIT_RANGED_RATING:
6371 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6372 break;
6373 case ITEM_MOD_HIT_SPELL_RATING:
6374 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6375 break;
6376 case ITEM_MOD_CRIT_MELEE_RATING:
6377 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6378 break;
6379 case ITEM_MOD_CRIT_RANGED_RATING:
6380 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6381 break;
6382 case ITEM_MOD_CRIT_SPELL_RATING:
6383 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6384 break;
6385 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6386 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6387 break;
6388 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6389 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6390 break;
6391 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6392 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6393 break;
6394 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6395 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6396 break;
6397 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6398 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6399 break;
6400 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6401 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6402 break;
6403 case ITEM_MOD_HASTE_MELEE_RATING:
6404 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6405 break;
6406 case ITEM_MOD_HASTE_RANGED_RATING:
6407 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6408 break;
6409 case ITEM_MOD_HASTE_SPELL_RATING:
6410 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6411 break;
6412 case ITEM_MOD_HIT_RATING:
6413 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6414 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6415 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6416 break;
6417 case ITEM_MOD_CRIT_RATING:
6418 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6419 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6420 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6421 break;
6422 case ITEM_MOD_HIT_TAKEN_RATING:
6423 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6424 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6425 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6426 break;
6427 case ITEM_MOD_CRIT_TAKEN_RATING:
6428 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6429 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6430 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6431 break;
6432 case ITEM_MOD_RESILIENCE_RATING:
6433 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6434 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6435 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6436 break;
6437 case ITEM_MOD_HASTE_RATING:
6438 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6439 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6440 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6441 break;
6442 case ITEM_MOD_EXPERTISE_RATING:
6443 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6444 break;
6445 case ITEM_MOD_ATTACK_POWER:
6446 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6447 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6448 break;
6449 case ITEM_MOD_RANGED_ATTACK_POWER:
6450 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6451 break;
6452 case ITEM_MOD_FERAL_ATTACK_POWER:
6453 ApplyFeralAPBonus(int32(val), apply);
6454 break;
6455 case ITEM_MOD_SPELL_HEALING_DONE:
6456 ApplySpellHealingBonus(int32(val), apply);
6457 break;
6458 case ITEM_MOD_SPELL_DAMAGE_DONE:
6459 ApplySpellDamageBonus(int32(val), apply);
6460 break;
6461 case ITEM_MOD_MANA_REGENERATION:
6462 ApplyManaRegenBonus(int32(val), apply);
6463 break;
6464 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6465 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6466 break;
6467 case ITEM_MOD_SPELL_POWER:
6468 ApplySpellHealingBonus(int32(val), apply);
6469 ApplySpellDamageBonus(int32(val), apply);
6470 break;
6474 if (proto->Armor)
6475 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6477 if (proto->Block)
6478 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6480 if (proto->HolyRes)
6481 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6483 if (proto->FireRes)
6484 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6486 if (proto->NatureRes)
6487 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6489 if (proto->FrostRes)
6490 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6492 if (proto->ShadowRes)
6493 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6495 if (proto->ArcaneRes)
6496 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6498 WeaponAttackType attType = BASE_ATTACK;
6499 float damage = 0.0f;
6501 if( slot == EQUIPMENT_SLOT_RANGED && (
6502 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6503 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6505 attType = RANGED_ATTACK;
6507 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6509 attType = OFF_ATTACK;
6512 if (proto->Damage[0].DamageMin > 0 )
6514 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6515 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6516 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6519 if (proto->Damage[0].DamageMax > 0 )
6521 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6522 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6525 // Druids get feral AP bonus from weapon dps
6526 if(getClass() == CLASS_DRUID)
6528 int32 feral_bonus = proto->getFeralBonus();
6529 if (feral_bonus > 0)
6530 ApplyFeralAPBonus(feral_bonus, apply);
6533 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6534 return;
6536 if (proto->Delay)
6538 if(slot == EQUIPMENT_SLOT_RANGED)
6539 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6540 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6541 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6542 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6543 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6546 if(CanModifyStats() && (damage || proto->Delay))
6547 UpdateDamagePhysical(attType);
6550 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6552 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6553 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6554 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6556 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6557 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6558 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6560 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6561 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6562 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6565 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6567 // generic not weapon specific case processes in aura code
6568 if(aura->GetSpellProto()->EquippedItemClass == -1)
6569 return;
6571 BaseModGroup mod = BASEMOD_END;
6572 switch(attackType)
6574 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6575 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6576 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6577 default: return;
6580 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6582 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6586 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6588 // ignore spell mods for not wands
6589 Modifier const* modifier = aura->GetModifier();
6590 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6591 return;
6593 // generic not weapon specific case processes in aura code
6594 if(aura->GetSpellProto()->EquippedItemClass == -1)
6595 return;
6597 UnitMods unitMod = UNIT_MOD_END;
6598 switch(attackType)
6600 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6601 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6602 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6603 default: return;
6606 UnitModifierType unitModType = TOTAL_VALUE;
6607 switch(modifier->m_auraname)
6609 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6610 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6611 default: return;
6614 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6616 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6620 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6622 if(!item)
6623 return;
6625 ItemPrototype const *proto = item->GetProto();
6626 if(!proto)
6627 return;
6629 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6631 _Spell const& spellData = proto->Spells[i];
6633 // no spell
6634 if(!spellData.SpellId )
6635 continue;
6637 // wrong triggering type
6638 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6639 continue;
6641 // check if it is valid spell
6642 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6643 if(!spellproto)
6644 continue;
6646 ApplyEquipSpell(spellproto,item,apply,form_change);
6650 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6652 if(apply)
6654 // Cannot be used in this stance/form
6655 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6656 return;
6658 if(form_change) // check aura active state from other form
6660 bool found = false;
6661 for (int k=0; k < 3; ++k)
6663 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6664 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6666 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6668 found = true;
6669 break;
6672 if(found)
6673 break;
6676 if(found) // and skip re-cast already active aura at form change
6677 return;
6680 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6682 CastSpell(this,spellInfo,true,item);
6684 else
6686 if(form_change) // check aura compatibility
6688 // Cannot be used in this stance/form
6689 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6690 return; // and remove only not compatible at form change
6693 if(item)
6694 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6695 else
6696 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6700 void Player::UpdateEquipSpellsAtFormChange()
6702 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6704 if(m_items[i] && !m_items[i]->IsBroken())
6706 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6707 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6711 // item set bonuses not dependent from item broken state
6712 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6714 ItemSetEffect* eff = ItemSetEff[setindex];
6715 if(!eff)
6716 continue;
6718 for(uint32 y=0;y<8; ++y)
6720 SpellEntry const* spellInfo = eff->spells[y];
6721 if(!spellInfo)
6722 continue;
6724 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6725 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6730 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6732 if(!item || item->IsBroken())
6733 return;
6735 ItemPrototype const *proto = item->GetProto();
6736 if(!proto)
6737 return;
6739 if (!Target || Target == this )
6740 return;
6742 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6744 _Spell const& spellData = proto->Spells[i];
6746 // no spell
6747 if(!spellData.SpellId )
6748 continue;
6750 // wrong triggering type
6751 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6752 continue;
6754 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6755 if(!spellInfo)
6757 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6758 continue;
6761 // not allow proc extra attack spell at extra attack
6762 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6763 return;
6765 float chance = spellInfo->procChance;
6767 if(spellData.SpellPPMRate)
6769 uint32 WeaponSpeed = GetAttackTime(attType);
6770 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6772 else if(chance > 100.0f)
6774 chance = GetWeaponProcChance();
6777 if (roll_chance_f(chance))
6778 CastSpell(Target, spellInfo->Id, true, item);
6781 // item combat enchantments
6782 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6784 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6785 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6786 if(!pEnchant) continue;
6787 for (int s=0;s<3;s++)
6789 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6790 continue;
6792 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6793 if (!spellInfo)
6795 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6796 continue;
6799 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6800 if (roll_chance_f(chance))
6802 if(IsPositiveSpell(pEnchant->spellid[s]))
6803 CastSpell(this, pEnchant->spellid[s], true, item);
6804 else
6805 CastSpell(Target, pEnchant->spellid[s], true, item);
6811 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
6813 ItemPrototype const* proto = item->GetProto();
6814 // special learning case
6815 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
6817 uint32 learn_spell_id = proto->Spells[0].SpellId;
6818 uint32 learning_spell_id = proto->Spells[1].SpellId;
6820 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
6821 if(!spellInfo)
6823 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
6824 SendEquipError(EQUIP_ERR_NONE,item,NULL);
6825 return;
6828 Spell *spell = new Spell(this, spellInfo, false);
6829 spell->m_CastItem = item;
6830 spell->m_cast_count = cast_count; //set count of casts
6831 spell->m_currentBasePoints[0] = learning_spell_id;
6832 spell->prepare(&targets);
6833 return;
6836 // use triggered flag only for items with many spell casts and for not first cast
6837 int count = 0;
6839 // item spells casted at use
6840 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6842 _Spell const& spellData = proto->Spells[i];
6844 // no spell
6845 if(!spellData.SpellId)
6846 continue;
6848 // wrong triggering type
6849 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
6850 continue;
6852 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6853 if(!spellInfo)
6855 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
6856 continue;
6859 Spell *spell = new Spell(this, spellInfo, (count > 0));
6860 spell->m_CastItem = item;
6861 spell->m_cast_count = cast_count; // set count of casts
6862 spell->m_glyphIndex = glyphIndex; // glyph index
6863 spell->prepare(&targets);
6865 ++count;
6868 // Item enchantments spells casted at use
6869 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6871 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6872 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6873 if(!pEnchant) continue;
6874 for (int s=0;s<3;s++)
6876 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
6877 continue;
6879 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6880 if (!spellInfo)
6882 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6883 continue;
6886 Spell *spell = new Spell(this, spellInfo, (count > 0));
6887 spell->m_CastItem = item;
6888 spell->m_cast_count = cast_count; // set count of casts
6889 spell->m_glyphIndex = glyphIndex; // glyph index
6890 spell->prepare(&targets);
6892 ++count;
6897 void Player::_RemoveAllItemMods()
6899 sLog.outDebug("_RemoveAllItemMods start.");
6901 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6903 if(m_items[i])
6905 ItemPrototype const *proto = m_items[i]->GetProto();
6906 if(!proto)
6907 continue;
6909 // item set bonuses not dependent from item broken state
6910 if(proto->ItemSet)
6911 RemoveItemsSetItem(this,proto);
6913 if(m_items[i]->IsBroken())
6914 continue;
6916 ApplyItemEquipSpell(m_items[i],false);
6917 ApplyEnchantment(m_items[i], false);
6921 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6923 if(m_items[i])
6925 if(m_items[i]->IsBroken())
6926 continue;
6927 ItemPrototype const *proto = m_items[i]->GetProto();
6928 if(!proto)
6929 continue;
6931 uint32 attacktype = Player::GetAttackBySlot(i);
6932 if(attacktype < MAX_ATTACK)
6933 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6935 _ApplyItemBonuses(proto,i, false);
6937 if( i == EQUIPMENT_SLOT_RANGED )
6938 _ApplyAmmoBonuses();
6942 sLog.outDebug("_RemoveAllItemMods complete.");
6945 void Player::_ApplyAllItemMods()
6947 sLog.outDebug("_ApplyAllItemMods start.");
6949 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6951 if(m_items[i])
6953 if(m_items[i]->IsBroken())
6954 continue;
6956 ItemPrototype const *proto = m_items[i]->GetProto();
6957 if(!proto)
6958 continue;
6960 uint32 attacktype = Player::GetAttackBySlot(i);
6961 if(attacktype < MAX_ATTACK)
6962 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
6964 _ApplyItemBonuses(proto,i, true);
6966 if( i == EQUIPMENT_SLOT_RANGED )
6967 _ApplyAmmoBonuses();
6971 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6973 if(m_items[i])
6975 ItemPrototype const *proto = m_items[i]->GetProto();
6976 if(!proto)
6977 continue;
6979 // item set bonuses not dependent from item broken state
6980 if(proto->ItemSet)
6981 AddItemsSetItem(this,m_items[i]);
6983 if(m_items[i]->IsBroken())
6984 continue;
6986 ApplyItemEquipSpell(m_items[i],true);
6987 ApplyEnchantment(m_items[i], true);
6991 sLog.outDebug("_ApplyAllItemMods complete.");
6994 void Player::_ApplyAmmoBonuses()
6996 // check ammo
6997 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
6998 if(!ammo_id)
6999 return;
7001 float currentAmmoDPS;
7003 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7004 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7005 currentAmmoDPS = 0.0f;
7006 else
7007 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7009 if(currentAmmoDPS == GetAmmoDPS())
7010 return;
7012 m_ammoDPS = currentAmmoDPS;
7014 if(CanModifyStats())
7015 UpdateDamagePhysical(RANGED_ATTACK);
7018 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7020 if(!ammo_proto)
7021 return false;
7023 // check ranged weapon
7024 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7025 if(!weapon || weapon->IsBroken() )
7026 return false;
7028 ItemPrototype const* weapon_proto = weapon->GetProto();
7029 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7030 return false;
7032 // check ammo ws. weapon compatibility
7033 switch(weapon_proto->SubClass)
7035 case ITEM_SUBCLASS_WEAPON_BOW:
7036 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7037 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7038 return false;
7039 break;
7040 case ITEM_SUBCLASS_WEAPON_GUN:
7041 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7042 return false;
7043 break;
7044 default:
7045 return false;
7048 return true;
7051 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7052 Called by remove insignia spell effect */
7053 void Player::RemovedInsignia(Player* looterPlr)
7055 if (!GetBattleGroundId())
7056 return;
7058 // If not released spirit, do it !
7059 if(m_deathTimer > 0)
7061 m_deathTimer = 0;
7062 BuildPlayerRepop();
7063 RepopAtGraveyard();
7066 Corpse *corpse = GetCorpse();
7067 if (!corpse)
7068 return;
7070 // We have to convert player corpse to bones, not to be able to resurrect there
7071 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7072 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7073 if (!bones)
7074 return;
7076 // Now we must make bones lootable, and send player loot
7077 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7079 // We store the level of our player in the gold field
7080 // We retrieve this information at Player::SendLoot()
7081 bones->loot.gold = getLevel();
7082 bones->lootRecipient = looterPlr;
7083 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7086 void Player::SendLootRelease( uint64 guid )
7088 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7089 data << uint64(guid) << uint8(1);
7090 SendDirectMessage( &data );
7093 void Player::SendLoot(uint64 guid, LootType loot_type)
7095 if (uint64 lguid = GetLootGUID())
7096 m_session->DoLootRelease(lguid);
7098 Loot *loot = 0;
7099 PermissionTypes permission = ALL_PERMISSION;
7101 sLog.outDebug("Player::SendLoot");
7102 if (IS_GAMEOBJECT_GUID(guid))
7104 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7105 GameObject *go = GetMap()->GetGameObject(guid);
7107 // not check distance for GO in case owned GO (fishing bobber case, for example)
7108 // And permit out of range GO with no owner in case fishing hole
7109 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7111 SendLootRelease(guid);
7112 return;
7115 loot = &go->loot;
7117 if (go->getLootState() == GO_READY)
7119 uint32 lootid = go->GetLootId();
7121 if (lootid)
7123 sLog.outDebug(" if(lootid)");
7124 loot->clear();
7125 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7128 if (loot_type == LOOT_FISHING)
7129 go->getFishLoot(loot,this);
7131 go->SetLootState(GO_ACTIVATED);
7134 else if (IS_ITEM_GUID(guid))
7136 Item *item = GetItemByGuid( guid );
7138 if (!item)
7140 SendLootRelease(guid);
7141 return;
7144 loot = &item->loot;
7146 if (!item->m_lootGenerated)
7148 item->m_lootGenerated = true;
7149 loot->clear();
7151 switch(loot_type)
7153 case LOOT_DISENCHANTING:
7154 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7155 break;
7156 case LOOT_PROSPECTING:
7157 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7158 break;
7159 case LOOT_MILLING:
7160 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7161 break;
7162 default:
7163 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7164 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7165 break;
7169 else if (IS_CORPSE_GUID(guid)) // remove insignia
7171 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7173 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7175 SendLootRelease(guid);
7176 return;
7179 loot = &bones->loot;
7181 if (!bones->lootForBody)
7183 bones->lootForBody = true;
7184 uint32 pLevel = bones->loot.gold;
7185 bones->loot.clear();
7186 // It may need a better formula
7187 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7188 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7191 if (bones->lootRecipient != this)
7192 permission = NONE_PERMISSION;
7194 else
7196 Creature *creature = GetMap()->GetCreature(guid);
7198 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7199 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7201 SendLootRelease(guid);
7202 return;
7205 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7207 SendLootRelease(guid);
7208 return;
7211 loot = &creature->loot;
7213 if (loot_type == LOOT_PICKPOCKETING)
7215 if (!creature->lootForPickPocketed)
7217 creature->lootForPickPocketed = true;
7218 loot->clear();
7220 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7221 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7223 // Generate extra money for pick pocket loot
7224 const uint32 a = urand(0, creature->getLevel()/2);
7225 const uint32 b = urand(0, getLevel()/2);
7226 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7229 else
7231 // the player whose group may loot the corpse
7232 Player *recipient = creature->GetLootRecipient();
7233 if (!recipient)
7235 creature->SetLootRecipient(this);
7236 recipient = this;
7239 if (creature->lootForPickPocketed)
7241 creature->lootForPickPocketed = false;
7242 loot->clear();
7245 if (!creature->lootForBody)
7247 creature->lootForBody = true;
7248 loot->clear();
7250 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7251 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7253 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7255 if (Group* group = recipient->GetGroup())
7257 group->UpdateLooterGuid(creature,true);
7259 switch (group->GetLootMethod())
7261 case GROUP_LOOT:
7262 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7263 group->GroupLoot(recipient->GetGUID(), loot, creature);
7264 break;
7265 case NEED_BEFORE_GREED:
7266 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7267 break;
7268 case MASTER_LOOT:
7269 group->MasterLoot(recipient->GetGUID(), loot, creature);
7270 break;
7271 default:
7272 break;
7277 // possible only if creature->lootForBody && loot->empty() at spell cast check
7278 if (loot_type == LOOT_SKINNING)
7280 loot->clear();
7281 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7283 // set group rights only for loot_type != LOOT_SKINNING
7284 else
7286 if(Group* group = GetGroup())
7288 if (group == recipient->GetGroup())
7290 if (group->GetLootMethod() == FREE_FOR_ALL)
7291 permission = ALL_PERMISSION;
7292 else if (group->GetLooterGuid() == GetGUID())
7294 if (group->GetLootMethod() == MASTER_LOOT)
7295 permission = MASTER_PERMISSION;
7296 else
7297 permission = ALL_PERMISSION;
7299 else
7300 permission = GROUP_PERMISSION;
7302 else
7303 permission = NONE_PERMISSION;
7305 else if (recipient == this)
7306 permission = ALL_PERMISSION;
7307 else
7308 permission = NONE_PERMISSION;
7313 SetLootGUID(guid);
7315 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7316 switch(loot_type)
7318 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7319 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7320 default: break;
7323 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7325 data << uint64(guid);
7326 data << uint8(loot_type);
7327 data << LootView(*loot, this, permission);
7329 SendDirectMessage(&data);
7331 // add 'this' player as one of the players that are looting 'loot'
7332 if (permission != NONE_PERMISSION)
7333 loot->AddLooter(GetGUID());
7335 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7336 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7339 void Player::SendNotifyLootMoneyRemoved()
7341 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7342 GetSession()->SendPacket( &data );
7345 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7347 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7348 data << uint8(lootSlot);
7349 GetSession()->SendPacket( &data );
7352 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7354 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7355 data << Field;
7356 data << Value;
7357 GetSession()->SendPacket(&data);
7360 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7362 // data depends on zoneid/mapid...
7363 BattleGround* bg = GetBattleGround();
7364 uint16 NumberOfFields = 0;
7365 uint32 mapid = GetMapId();
7367 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7369 // may be exist better way to do this...
7370 switch(zoneid)
7372 case 0:
7373 case 1:
7374 case 4:
7375 case 8:
7376 case 10:
7377 case 11:
7378 case 12:
7379 case 36:
7380 case 38:
7381 case 40:
7382 case 41:
7383 case 51:
7384 case 267:
7385 case 1519:
7386 case 1537:
7387 case 2257:
7388 case 2918:
7389 NumberOfFields = 8;
7390 break;
7391 case 139:
7392 NumberOfFields = 41;
7393 break;
7394 case 1377:
7395 NumberOfFields = 15;
7396 break;
7397 case 2597:
7398 NumberOfFields = 83;
7399 break;
7400 case 3277:
7401 NumberOfFields = 16;
7402 break;
7403 case 3358:
7404 case 3820:
7405 NumberOfFields = 40;
7406 break;
7407 case 3483:
7408 NumberOfFields = 27;
7409 break;
7410 case 3518:
7411 NumberOfFields = 39;
7412 break;
7413 case 3519:
7414 NumberOfFields = 38;
7415 break;
7416 case 3521:
7417 NumberOfFields = 37;
7418 break;
7419 case 3698:
7420 case 3702:
7421 case 3968:
7422 NumberOfFields = 11;
7423 break;
7424 case 3703:
7425 NumberOfFields = 11;
7426 break;
7427 default:
7428 NumberOfFields = 12;
7429 break;
7432 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7433 data << uint32(mapid); // mapid
7434 data << uint32(zoneid); // zone id
7435 data << uint32(areaid); // area id, new 2.1.0
7436 data << uint16(NumberOfFields); // count of uint64 blocks
7437 data << uint32(0x8d8) << uint32(0x0); // 1
7438 data << uint32(0x8d7) << uint32(0x0); // 2
7439 data << uint32(0x8d6) << uint32(0x0); // 3
7440 data << uint32(0x8d5) << uint32(0x0); // 4
7441 data << uint32(0x8d4) << uint32(0x0); // 5
7442 data << uint32(0x8d3) << uint32(0x0); // 6
7443 // 7 1 - Arena season in progress, 0 - end of season
7444 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7445 // 8 Arena season id
7446 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7447 if(mapid == 530) // Outland
7449 data << uint32(0x9bf) << uint32(0x0); // 7
7450 data << uint32(0x9bd) << uint32(0xF); // 8
7451 data << uint32(0x9bb) << uint32(0xF); // 9
7453 switch(zoneid)
7455 case 1:
7456 case 11:
7457 case 12:
7458 case 38:
7459 case 40:
7460 case 51:
7461 case 1519:
7462 case 1537:
7463 case 2257:
7464 break;
7465 case 2597: // AV
7466 data << uint32(0x7ae) << uint32(0x1); // 7
7467 data << uint32(0x532) << uint32(0x1); // 8
7468 data << uint32(0x531) << uint32(0x0); // 9
7469 data << uint32(0x52e) << uint32(0x0); // 10
7470 data << uint32(0x571) << uint32(0x0); // 11
7471 data << uint32(0x570) << uint32(0x0); // 12
7472 data << uint32(0x567) << uint32(0x1); // 13
7473 data << uint32(0x566) << uint32(0x1); // 14
7474 data << uint32(0x550) << uint32(0x1); // 15
7475 data << uint32(0x544) << uint32(0x0); // 16
7476 data << uint32(0x536) << uint32(0x0); // 17
7477 data << uint32(0x535) << uint32(0x1); // 18
7478 data << uint32(0x518) << uint32(0x0); // 19
7479 data << uint32(0x517) << uint32(0x0); // 20
7480 data << uint32(0x574) << uint32(0x0); // 21
7481 data << uint32(0x573) << uint32(0x0); // 22
7482 data << uint32(0x572) << uint32(0x0); // 23
7483 data << uint32(0x56f) << uint32(0x0); // 24
7484 data << uint32(0x56e) << uint32(0x0); // 25
7485 data << uint32(0x56d) << uint32(0x0); // 26
7486 data << uint32(0x56c) << uint32(0x0); // 27
7487 data << uint32(0x56b) << uint32(0x0); // 28
7488 data << uint32(0x56a) << uint32(0x1); // 29
7489 data << uint32(0x569) << uint32(0x1); // 30
7490 data << uint32(0x568) << uint32(0x1); // 13
7491 data << uint32(0x565) << uint32(0x0); // 32
7492 data << uint32(0x564) << uint32(0x0); // 33
7493 data << uint32(0x563) << uint32(0x0); // 34
7494 data << uint32(0x562) << uint32(0x0); // 35
7495 data << uint32(0x561) << uint32(0x0); // 36
7496 data << uint32(0x560) << uint32(0x0); // 37
7497 data << uint32(0x55f) << uint32(0x0); // 38
7498 data << uint32(0x55e) << uint32(0x0); // 39
7499 data << uint32(0x55d) << uint32(0x0); // 40
7500 data << uint32(0x3c6) << uint32(0x4); // 41
7501 data << uint32(0x3c4) << uint32(0x6); // 42
7502 data << uint32(0x3c2) << uint32(0x4); // 43
7503 data << uint32(0x516) << uint32(0x1); // 44
7504 data << uint32(0x515) << uint32(0x0); // 45
7505 data << uint32(0x3b6) << uint32(0x6); // 46
7506 data << uint32(0x55c) << uint32(0x0); // 47
7507 data << uint32(0x55b) << uint32(0x0); // 48
7508 data << uint32(0x55a) << uint32(0x0); // 49
7509 data << uint32(0x559) << uint32(0x0); // 50
7510 data << uint32(0x558) << uint32(0x0); // 51
7511 data << uint32(0x557) << uint32(0x0); // 52
7512 data << uint32(0x556) << uint32(0x0); // 53
7513 data << uint32(0x555) << uint32(0x0); // 54
7514 data << uint32(0x554) << uint32(0x1); // 55
7515 data << uint32(0x553) << uint32(0x1); // 56
7516 data << uint32(0x552) << uint32(0x1); // 57
7517 data << uint32(0x551) << uint32(0x1); // 58
7518 data << uint32(0x54f) << uint32(0x0); // 59
7519 data << uint32(0x54e) << uint32(0x0); // 60
7520 data << uint32(0x54d) << uint32(0x1); // 61
7521 data << uint32(0x54c) << uint32(0x0); // 62
7522 data << uint32(0x54b) << uint32(0x0); // 63
7523 data << uint32(0x545) << uint32(0x0); // 64
7524 data << uint32(0x543) << uint32(0x1); // 65
7525 data << uint32(0x542) << uint32(0x0); // 66
7526 data << uint32(0x540) << uint32(0x0); // 67
7527 data << uint32(0x53f) << uint32(0x0); // 68
7528 data << uint32(0x53e) << uint32(0x0); // 69
7529 data << uint32(0x53d) << uint32(0x0); // 70
7530 data << uint32(0x53c) << uint32(0x0); // 71
7531 data << uint32(0x53b) << uint32(0x0); // 72
7532 data << uint32(0x53a) << uint32(0x1); // 73
7533 data << uint32(0x539) << uint32(0x0); // 74
7534 data << uint32(0x538) << uint32(0x0); // 75
7535 data << uint32(0x537) << uint32(0x0); // 76
7536 data << uint32(0x534) << uint32(0x0); // 77
7537 data << uint32(0x533) << uint32(0x0); // 78
7538 data << uint32(0x530) << uint32(0x0); // 79
7539 data << uint32(0x52f) << uint32(0x0); // 80
7540 data << uint32(0x52d) << uint32(0x1); // 81
7541 break;
7542 case 3277: // WS
7543 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7544 bg->FillInitialWorldStates(data);
7545 else
7547 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7548 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7549 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7550 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7551 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7552 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7553 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7554 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7556 break;
7557 case 3358: // AB
7558 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7559 bg->FillInitialWorldStates(data);
7560 else
7562 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7563 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7564 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7565 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7566 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7567 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7568 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7569 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7570 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7571 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7572 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7573 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7574 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7575 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7576 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7577 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7578 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7579 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7580 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7581 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7582 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7583 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7584 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7585 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7586 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7587 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7588 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7589 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7590 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7591 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7592 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7593 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7595 break;
7596 case 3820: // EY
7597 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7598 bg->FillInitialWorldStates(data);
7599 else
7601 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7602 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7603 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7604 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7605 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7606 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7607 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7608 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7609 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7610 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7611 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7612 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7613 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7614 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7615 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7616 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7617 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7618 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7619 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7620 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7621 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7622 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7623 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7624 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7625 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7626 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7627 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7628 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7629 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7630 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7631 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7632 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7633 // and some more ... unknown
7635 break;
7636 case 3483: // Hellfire Peninsula
7637 data << uint32(0x9ba) << uint32(0x1); // 10
7638 data << uint32(0x9b9) << uint32(0x1); // 11
7639 data << uint32(0x9b5) << uint32(0x0); // 12
7640 data << uint32(0x9b4) << uint32(0x1); // 13
7641 data << uint32(0x9b3) << uint32(0x0); // 14
7642 data << uint32(0x9b2) << uint32(0x0); // 15
7643 data << uint32(0x9b1) << uint32(0x1); // 16
7644 data << uint32(0x9b0) << uint32(0x0); // 17
7645 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7646 data << uint32(0x9ac) << uint32(0x0); // 19
7647 data << uint32(0x9a8) << uint32(0x0); // 20
7648 data << uint32(0x9a7) << uint32(0x0); // 21
7649 data << uint32(0x9a6) << uint32(0x1); // 22
7650 break;
7651 case 3519: // Terokkar Forest
7652 data << uint32(0xa41) << uint32(0x0); // 10
7653 data << uint32(0xa40) << uint32(0x14); // 11
7654 data << uint32(0xa3f) << uint32(0x0); // 12
7655 data << uint32(0xa3e) << uint32(0x0); // 13
7656 data << uint32(0xa3d) << uint32(0x5); // 14
7657 data << uint32(0xa3c) << uint32(0x0); // 15
7658 data << uint32(0xa87) << uint32(0x0); // 16
7659 data << uint32(0xa86) << uint32(0x0); // 17
7660 data << uint32(0xa85) << uint32(0x0); // 18
7661 data << uint32(0xa84) << uint32(0x0); // 19
7662 data << uint32(0xa83) << uint32(0x0); // 20
7663 data << uint32(0xa82) << uint32(0x0); // 21
7664 data << uint32(0xa81) << uint32(0x0); // 22
7665 data << uint32(0xa80) << uint32(0x0); // 23
7666 data << uint32(0xa7e) << uint32(0x0); // 24
7667 data << uint32(0xa7d) << uint32(0x0); // 25
7668 data << uint32(0xa7c) << uint32(0x0); // 26
7669 data << uint32(0xa7b) << uint32(0x0); // 27
7670 data << uint32(0xa7a) << uint32(0x0); // 28
7671 data << uint32(0xa79) << uint32(0x0); // 29
7672 data << uint32(0x9d0) << uint32(0x5); // 30
7673 data << uint32(0x9ce) << uint32(0x0); // 31
7674 data << uint32(0x9cd) << uint32(0x0); // 32
7675 data << uint32(0x9cc) << uint32(0x0); // 33
7676 data << uint32(0xa88) << uint32(0x0); // 34
7677 data << uint32(0xad0) << uint32(0x0); // 35
7678 data << uint32(0xacf) << uint32(0x1); // 36
7679 break;
7680 case 3521: // Zangarmarsh
7681 data << uint32(0x9e1) << uint32(0x0); // 10
7682 data << uint32(0x9e0) << uint32(0x0); // 11
7683 data << uint32(0x9df) << uint32(0x0); // 12
7684 data << uint32(0xa5d) << uint32(0x1); // 13
7685 data << uint32(0xa5c) << uint32(0x0); // 14
7686 data << uint32(0xa5b) << uint32(0x1); // 15
7687 data << uint32(0xa5a) << uint32(0x0); // 16
7688 data << uint32(0xa59) << uint32(0x1); // 17
7689 data << uint32(0xa58) << uint32(0x0); // 18
7690 data << uint32(0xa57) << uint32(0x0); // 19
7691 data << uint32(0xa56) << uint32(0x0); // 20
7692 data << uint32(0xa55) << uint32(0x1); // 21
7693 data << uint32(0xa54) << uint32(0x0); // 22
7694 data << uint32(0x9e7) << uint32(0x0); // 23
7695 data << uint32(0x9e6) << uint32(0x0); // 24
7696 data << uint32(0x9e5) << uint32(0x0); // 25
7697 data << uint32(0xa00) << uint32(0x0); // 26
7698 data << uint32(0x9ff) << uint32(0x1); // 27
7699 data << uint32(0x9fe) << uint32(0x0); // 28
7700 data << uint32(0x9fd) << uint32(0x0); // 29
7701 data << uint32(0x9fc) << uint32(0x1); // 30
7702 data << uint32(0x9fb) << uint32(0x0); // 31
7703 data << uint32(0xa62) << uint32(0x0); // 32
7704 data << uint32(0xa61) << uint32(0x1); // 33
7705 data << uint32(0xa60) << uint32(0x1); // 34
7706 data << uint32(0xa5f) << uint32(0x0); // 35
7707 break;
7708 case 3698: // Nagrand Arena
7709 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7710 bg->FillInitialWorldStates(data);
7711 else
7713 data << uint32(0xa0f) << uint32(0x0); // 7
7714 data << uint32(0xa10) << uint32(0x0); // 8
7715 data << uint32(0xa11) << uint32(0x0); // 9 show
7717 break;
7718 case 3702: // Blade's Edge Arena
7719 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7720 bg->FillInitialWorldStates(data);
7721 else
7723 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7724 data << uint32(0x9f1) << uint32(0x0); // 8 green
7725 data << uint32(0x9f3) << uint32(0x0); // 9 show
7727 break;
7728 case 3968: // Ruins of Lordaeron
7729 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7730 bg->FillInitialWorldStates(data);
7731 else
7733 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7734 data << uint32(0xbb9) << uint32(0x0); // 8 green
7735 data << uint32(0xbba) << uint32(0x0); // 9 show
7737 break;
7738 case 3703: // Shattrath City
7739 break;
7740 default:
7741 data << uint32(0x914) << uint32(0x0); // 7
7742 data << uint32(0x913) << uint32(0x0); // 8
7743 data << uint32(0x912) << uint32(0x0); // 9
7744 data << uint32(0x915) << uint32(0x0); // 10
7745 break;
7747 GetSession()->SendPacket(&data);
7750 uint32 Player::GetXPRestBonus(uint32 xp)
7752 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7754 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7755 rested_bonus = xp;
7757 SetRestBonus( GetRestBonus() - rested_bonus);
7759 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7760 return rested_bonus;
7763 void Player::SetBindPoint(uint64 guid)
7765 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7766 data << uint64(guid);
7767 GetSession()->SendPacket( &data );
7770 void Player::SendTalentWipeConfirm(uint64 guid)
7772 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7773 data << uint64(guid);
7774 data << uint32(resetTalentsCost());
7775 GetSession()->SendPacket( &data );
7778 void Player::SendPetSkillWipeConfirm()
7780 Pet* pet = GetPet();
7781 if(!pet)
7782 return;
7783 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7784 data << pet->GetGUID();
7785 data << uint32(pet->resetTalentsCost());
7786 GetSession()->SendPacket( &data );
7789 /*********************************************************/
7790 /*** STORAGE SYSTEM ***/
7791 /*********************************************************/
7793 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7795 assert(i < 3);
7796 if(i < 2 && item)
7798 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7799 return;
7800 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7801 if(charges == 0)
7802 return;
7803 if(charges > 1)
7804 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7805 else if(charges <= 1)
7807 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7808 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7813 void Player::SetSheath( uint32 sheathed )
7815 switch (sheathed)
7817 case SHEATH_STATE_UNARMED: // no prepared weapon
7818 SetVirtualItemSlot(0,NULL);
7819 SetVirtualItemSlot(1,NULL);
7820 SetVirtualItemSlot(2,NULL);
7821 break;
7822 case SHEATH_STATE_MELEE: // prepared melee weapon
7824 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7825 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7826 SetVirtualItemSlot(2,NULL);
7827 }; break;
7828 case SHEATH_STATE_RANGED: // prepared ranged weapon
7829 SetVirtualItemSlot(0,NULL);
7830 SetVirtualItemSlot(1,NULL);
7831 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7832 break;
7833 default:
7834 SetVirtualItemSlot(0,NULL);
7835 SetVirtualItemSlot(1,NULL);
7836 SetVirtualItemSlot(2,NULL);
7837 break;
7839 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7842 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7844 uint8 pClass = getClass();
7846 uint8 slots[4];
7847 slots[0] = NULL_SLOT;
7848 slots[1] = NULL_SLOT;
7849 slots[2] = NULL_SLOT;
7850 slots[3] = NULL_SLOT;
7851 switch( proto->InventoryType )
7853 case INVTYPE_HEAD:
7854 slots[0] = EQUIPMENT_SLOT_HEAD;
7855 break;
7856 case INVTYPE_NECK:
7857 slots[0] = EQUIPMENT_SLOT_NECK;
7858 break;
7859 case INVTYPE_SHOULDERS:
7860 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7861 break;
7862 case INVTYPE_BODY:
7863 slots[0] = EQUIPMENT_SLOT_BODY;
7864 break;
7865 case INVTYPE_CHEST:
7866 slots[0] = EQUIPMENT_SLOT_CHEST;
7867 break;
7868 case INVTYPE_ROBE:
7869 slots[0] = EQUIPMENT_SLOT_CHEST;
7870 break;
7871 case INVTYPE_WAIST:
7872 slots[0] = EQUIPMENT_SLOT_WAIST;
7873 break;
7874 case INVTYPE_LEGS:
7875 slots[0] = EQUIPMENT_SLOT_LEGS;
7876 break;
7877 case INVTYPE_FEET:
7878 slots[0] = EQUIPMENT_SLOT_FEET;
7879 break;
7880 case INVTYPE_WRISTS:
7881 slots[0] = EQUIPMENT_SLOT_WRISTS;
7882 break;
7883 case INVTYPE_HANDS:
7884 slots[0] = EQUIPMENT_SLOT_HANDS;
7885 break;
7886 case INVTYPE_FINGER:
7887 slots[0] = EQUIPMENT_SLOT_FINGER1;
7888 slots[1] = EQUIPMENT_SLOT_FINGER2;
7889 break;
7890 case INVTYPE_TRINKET:
7891 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7892 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7893 break;
7894 case INVTYPE_CLOAK:
7895 slots[0] = EQUIPMENT_SLOT_BACK;
7896 break;
7897 case INVTYPE_WEAPON:
7899 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7901 // suggest offhand slot only if know dual wielding
7902 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7903 if(CanDualWield())
7904 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7905 break;
7907 case INVTYPE_SHIELD:
7908 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7909 break;
7910 case INVTYPE_RANGED:
7911 slots[0] = EQUIPMENT_SLOT_RANGED;
7912 break;
7913 case INVTYPE_2HWEAPON:
7914 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7915 if (CanDualWield() && CanTitanGrip())
7916 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7917 break;
7918 case INVTYPE_TABARD:
7919 slots[0] = EQUIPMENT_SLOT_TABARD;
7920 break;
7921 case INVTYPE_WEAPONMAINHAND:
7922 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7923 break;
7924 case INVTYPE_WEAPONOFFHAND:
7925 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7926 break;
7927 case INVTYPE_HOLDABLE:
7928 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7929 break;
7930 case INVTYPE_THROWN:
7931 slots[0] = EQUIPMENT_SLOT_RANGED;
7932 break;
7933 case INVTYPE_RANGEDRIGHT:
7934 slots[0] = EQUIPMENT_SLOT_RANGED;
7935 break;
7936 case INVTYPE_BAG:
7937 slots[0] = INVENTORY_SLOT_BAG_START + 0;
7938 slots[1] = INVENTORY_SLOT_BAG_START + 1;
7939 slots[2] = INVENTORY_SLOT_BAG_START + 2;
7940 slots[3] = INVENTORY_SLOT_BAG_START + 3;
7941 break;
7942 case INVTYPE_RELIC:
7944 switch(proto->SubClass)
7946 case ITEM_SUBCLASS_ARMOR_LIBRAM:
7947 if (pClass == CLASS_PALADIN)
7948 slots[0] = EQUIPMENT_SLOT_RANGED;
7949 break;
7950 case ITEM_SUBCLASS_ARMOR_IDOL:
7951 if (pClass == CLASS_DRUID)
7952 slots[0] = EQUIPMENT_SLOT_RANGED;
7953 break;
7954 case ITEM_SUBCLASS_ARMOR_TOTEM:
7955 if (pClass == CLASS_SHAMAN)
7956 slots[0] = EQUIPMENT_SLOT_RANGED;
7957 break;
7958 case ITEM_SUBCLASS_ARMOR_MISC:
7959 if (pClass == CLASS_WARLOCK)
7960 slots[0] = EQUIPMENT_SLOT_RANGED;
7961 break;
7962 case ITEM_SUBCLASS_ARMOR_SIGIL:
7963 if (pClass == CLASS_DEATH_KNIGHT)
7964 slots[0] = EQUIPMENT_SLOT_RANGED;
7965 break;
7967 break;
7969 default :
7970 return NULL_SLOT;
7973 if( slot != NULL_SLOT )
7975 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
7977 for (int i = 0; i < 4; ++i)
7979 if ( slots[i] == slot )
7980 return slot;
7984 else
7986 // search free slot at first
7987 for (int i = 0; i < 4; ++i)
7989 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
7991 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
7992 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
7993 return slots[i];
7997 // if not found free and can swap return first appropriate from used
7998 for (int i = 0; i < 4; ++i)
8000 if ( slots[i] != NULL_SLOT && swap )
8001 return slots[i];
8005 // no free position
8006 return NULL_SLOT;
8009 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8011 Item *pItem;
8012 uint32 tempcount = 0;
8014 uint8 res = EQUIP_ERR_OK;
8016 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8018 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8019 if( pItem && pItem->GetEntry() == item )
8021 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8022 if(ires==EQUIP_ERR_OK)
8024 tempcount += pItem->GetCount();
8025 if( tempcount >= count )
8026 return EQUIP_ERR_OK;
8028 else
8029 res = ires;
8032 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8034 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8035 if( pItem && pItem->GetEntry() == item )
8037 tempcount += pItem->GetCount();
8038 if( tempcount >= count )
8039 return EQUIP_ERR_OK;
8042 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8044 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8045 if( pItem && pItem->GetEntry() == item )
8047 tempcount += pItem->GetCount();
8048 if( tempcount >= count )
8049 return EQUIP_ERR_OK;
8052 Bag *pBag;
8053 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8055 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8056 if( pBag )
8058 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8060 pItem = GetItemByPos( i, j );
8061 if( pItem && pItem->GetEntry() == item )
8063 tempcount += pItem->GetCount();
8064 if( tempcount >= count )
8065 return EQUIP_ERR_OK;
8071 // not found req. item count and have unequippable items
8072 return res;
8075 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8077 uint32 count = 0;
8078 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8080 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8081 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8082 count += pItem->GetCount();
8084 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8086 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8087 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8088 count += pItem->GetCount();
8090 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8092 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8093 if( pBag )
8094 count += pBag->GetItemCount(item,skipItem);
8097 if(skipItem && skipItem->GetProto()->GemProperties)
8099 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8101 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8102 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8103 count += pItem->GetGemCountWithID(item);
8107 if(inBankAlso)
8109 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8111 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8112 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8113 count += pItem->GetCount();
8115 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8117 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8118 if( pBag )
8119 count += pBag->GetItemCount(item,skipItem);
8122 if(skipItem && skipItem->GetProto()->GemProperties)
8124 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8126 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8127 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8128 count += pItem->GetGemCountWithID(item);
8133 return count;
8136 Item* Player::GetItemByGuid( uint64 guid ) const
8138 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8140 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8141 if( pItem && pItem->GetGUID() == guid )
8142 return pItem;
8144 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8146 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8147 if( pItem && pItem->GetGUID() == guid )
8148 return pItem;
8151 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8153 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8154 if( pBag )
8156 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8158 Item* pItem = pBag->GetItemByPos( j );
8159 if( pItem && pItem->GetGUID() == guid )
8160 return pItem;
8164 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8166 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8167 if( pBag )
8169 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8171 Item* pItem = pBag->GetItemByPos( j );
8172 if( pItem && pItem->GetGUID() == guid )
8173 return pItem;
8178 return NULL;
8181 Item* Player::GetItemByPos( uint16 pos ) const
8183 uint8 bag = pos >> 8;
8184 uint8 slot = pos & 255;
8185 return GetItemByPos( bag, slot );
8188 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8190 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8191 return m_items[slot];
8192 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8193 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8195 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8196 if ( pBag )
8197 return pBag->GetItemByPos(slot);
8199 return NULL;
8202 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8204 uint16 slot;
8205 switch (attackType)
8207 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8208 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8209 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8210 default: return NULL;
8213 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8214 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8215 return NULL;
8217 if(!useable)
8218 return item;
8220 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8221 return NULL;
8223 return item;
8226 Item* Player::GetShield(bool useable) const
8228 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8229 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8230 return NULL;
8232 if(!useable)
8233 return item;
8235 if( item->IsBroken())
8236 return NULL;
8238 return item;
8241 uint32 Player::GetAttackBySlot( uint8 slot )
8243 switch(slot)
8245 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8246 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8247 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8248 default: return MAX_ATTACK;
8252 bool Player::HasBankBagSlot( uint8 slot ) const
8254 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8255 if( slot < maxslot )
8256 return true;
8257 return false;
8260 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8262 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8263 return true;
8264 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8265 return true;
8266 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8267 return true;
8268 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8269 return true;
8270 return false;
8273 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8275 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8276 return true;
8277 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8278 return true;
8279 return false;
8282 bool Player::IsBankPos( uint8 bag, uint8 slot )
8284 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8285 return true;
8286 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8287 return true;
8288 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8289 return true;
8290 return false;
8293 bool Player::IsBagPos( uint16 pos )
8295 uint8 bag = pos >> 8;
8296 uint8 slot = pos & 255;
8297 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8298 return true;
8299 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8300 return true;
8301 return false;
8304 bool Player::IsValidPos( uint8 bag, uint8 slot )
8306 // post selected
8307 if(bag == NULL_BAG)
8308 return true;
8310 if (bag == INVENTORY_SLOT_BAG_0)
8312 // any post selected
8313 if (slot == NULL_SLOT)
8314 return true;
8316 // equipment
8317 if (slot < EQUIPMENT_SLOT_END)
8318 return true;
8320 // bag equip slots
8321 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8322 return true;
8324 // backpack slots
8325 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8326 return true;
8328 // keyring slots
8329 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8330 return true;
8332 // bank main slots
8333 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8334 return true;
8336 // bank bag slots
8337 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8338 return true;
8340 return false;
8343 // bag content slots
8344 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8346 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8347 if(!pBag)
8348 return false;
8350 // any post selected
8351 if (slot == NULL_SLOT)
8352 return true;
8354 return slot < pBag->GetBagSize();
8357 // bank bag content slots
8358 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8360 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8361 if(!pBag)
8362 return false;
8364 // any post selected
8365 if (slot == NULL_SLOT)
8366 return true;
8368 return slot < pBag->GetBagSize();
8371 // where this?
8372 return false;
8376 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8378 uint32 tempcount = 0;
8379 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8381 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8382 if( pItem && pItem->GetEntry() == item )
8384 tempcount += pItem->GetCount();
8385 if( tempcount >= count )
8386 return true;
8389 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8391 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8392 if( pItem && pItem->GetEntry() == item )
8394 tempcount += pItem->GetCount();
8395 if( tempcount >= count )
8396 return true;
8399 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8401 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8403 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8405 Item* pItem = GetItemByPos( i, j );
8406 if( pItem && pItem->GetEntry() == item )
8408 tempcount += pItem->GetCount();
8409 if( tempcount >= count )
8410 return true;
8416 if(inBankAlso)
8418 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8420 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8421 if( pItem && pItem->GetEntry() == item )
8423 tempcount += pItem->GetCount();
8424 if( tempcount >= count )
8425 return true;
8428 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8430 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8432 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8434 Item* pItem = GetItemByPos( i, j );
8435 if( pItem && pItem->GetEntry() == item )
8437 tempcount += pItem->GetCount();
8438 if( tempcount >= count )
8439 return true;
8446 return false;
8449 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8451 uint32 tempcount = 0;
8452 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8454 if(i==int(except_slot))
8455 continue;
8457 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8458 if( pItem && pItem->GetEntry() == item)
8460 tempcount += pItem->GetCount();
8461 if( tempcount >= count )
8462 return true;
8466 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8467 if (pProto && pProto->GemProperties)
8469 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8471 if(i==int(except_slot))
8472 continue;
8474 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8475 if( pItem && pItem->GetProto()->Socket[0].Color)
8477 tempcount += pItem->GetGemCountWithID(item);
8478 if( tempcount >= count )
8479 return true;
8484 return false;
8487 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8489 uint32 tempcount = 0;
8490 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8492 if(i==int(except_slot))
8493 continue;
8495 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8496 if (!pItem)
8497 continue;
8499 ItemPrototype const *pProto = pItem->GetProto();
8500 if (!pProto)
8501 continue;
8503 if (pProto->ItemLimitCategory == limitCategory)
8505 tempcount += pItem->GetCount();
8506 if( tempcount >= count )
8507 return true;
8510 if( pProto->Socket[0].Color)
8512 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8513 if( tempcount >= count )
8514 return true;
8518 return false;
8521 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8523 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8524 if( !pProto )
8526 if(no_space_count)
8527 *no_space_count = count;
8528 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8531 // no maximum
8532 if(pProto->MaxCount <= 0)
8533 return EQUIP_ERR_OK;
8535 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8537 if (curcount + count > uint32(pProto->MaxCount))
8539 if(no_space_count)
8540 *no_space_count = count +curcount - pProto->MaxCount;
8541 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8544 return EQUIP_ERR_OK;
8547 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8549 Item *pItem;
8550 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8552 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8553 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8554 return true;
8556 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8558 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8559 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8560 return true;
8562 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8564 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8566 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8568 pItem = GetItemByPos( i, j );
8569 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8570 return true;
8574 return false;
8577 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8579 Item* pItem2 = GetItemByPos( bag, slot );
8581 // ignore move item (this slot will be empty at move)
8582 if(pItem2==pSrcItem)
8583 pItem2 = NULL;
8585 uint32 need_space;
8587 // empty specific slot - check item fit to slot
8588 if( !pItem2 || swap )
8590 if( bag == INVENTORY_SLOT_BAG_0 )
8592 // keyring case
8593 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8594 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8596 // vanitypet case (not use, vanity pets stored as spells)
8597 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END)
8598 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8600 // currencytoken case (disabled until proper implement)
8601 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8602 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8604 // guestbag case (not use)
8605 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END)
8606 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8608 // prevent cheating
8609 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8610 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8612 else
8614 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8615 if( !pBag )
8616 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8618 ItemPrototype const* pBagProto = pBag->GetProto();
8619 if( !pBagProto )
8620 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8622 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8623 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8626 // non empty stack with space
8627 need_space = pProto->GetMaxStackSize();
8629 // non empty slot, check item type
8630 else
8632 // check item type
8633 if(pItem2->GetEntry() != pProto->ItemId)
8634 return EQUIP_ERR_ITEM_CANT_STACK;
8636 // check free space
8637 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8638 return EQUIP_ERR_ITEM_CANT_STACK;
8640 // free stack space or infinity
8641 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8644 if(need_space > count)
8645 need_space = count;
8647 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8648 if(!newPosition.isContainedIn(dest))
8650 dest.push_back(newPosition);
8651 count -= need_space;
8653 return EQUIP_ERR_OK;
8656 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
8658 // skip specific bag already processed in first called _CanStoreItem_InBag
8659 if(bag==skip_bag)
8660 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8662 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8663 if( !pBag )
8664 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8666 ItemPrototype const* pBagProto = pBag->GetProto();
8667 if( !pBagProto )
8668 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8670 // specialized bag mode or non-specilized
8671 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8672 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8674 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8675 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8677 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8679 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8680 if(j==skip_slot)
8681 continue;
8683 Item* pItem2 = GetItemByPos( bag, j );
8685 // ignore move item (this slot will be empty at move)
8686 if(pItem2==pSrcItem)
8687 pItem2 = NULL;
8689 // if merge skip empty, if !merge skip non-empty
8690 if((pItem2!=NULL)!=merge)
8691 continue;
8693 if( pItem2 )
8695 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8697 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8698 if(need_space > count)
8699 need_space = count;
8701 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8702 if(!newPosition.isContainedIn(dest))
8704 dest.push_back(newPosition);
8705 count -= need_space;
8707 if(count==0)
8708 return EQUIP_ERR_OK;
8712 else
8714 uint32 need_space = pProto->GetMaxStackSize();
8715 if(need_space > count)
8716 need_space = count;
8718 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8719 if(!newPosition.isContainedIn(dest))
8721 dest.push_back(newPosition);
8722 count -= need_space;
8724 if(count==0)
8725 return EQUIP_ERR_OK;
8729 return EQUIP_ERR_OK;
8732 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
8734 for(uint32 j = slot_begin; j < slot_end; ++j)
8736 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8737 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8738 continue;
8740 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8742 // ignore move item (this slot will be empty at move)
8743 if(pItem2==pSrcItem)
8744 pItem2 = NULL;
8746 // if merge skip empty, if !merge skip non-empty
8747 if((pItem2!=NULL)!=merge)
8748 continue;
8750 if( pItem2 )
8752 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8754 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8755 if(need_space > count)
8756 need_space = count;
8757 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8758 if(!newPosition.isContainedIn(dest))
8760 dest.push_back(newPosition);
8761 count -= need_space;
8763 if(count==0)
8764 return EQUIP_ERR_OK;
8768 else
8770 uint32 need_space = pProto->GetMaxStackSize();
8771 if(need_space > count)
8772 need_space = count;
8774 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8775 if(!newPosition.isContainedIn(dest))
8777 dest.push_back(newPosition);
8778 count -= need_space;
8780 if(count==0)
8781 return EQUIP_ERR_OK;
8785 return EQUIP_ERR_OK;
8788 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8790 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8792 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8793 if( !pProto )
8795 if(no_space_count)
8796 *no_space_count = count;
8797 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8800 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8802 if(no_space_count)
8803 *no_space_count = count;
8804 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8807 // check count of items (skip for auto move for same player from bank)
8808 uint32 no_similar_count = 0; // can't store this amount similar items
8809 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8810 if(res!=EQUIP_ERR_OK)
8812 if(count==no_similar_count)
8814 if(no_space_count)
8815 *no_space_count = no_similar_count;
8816 return res;
8818 count -= no_similar_count;
8821 // in specific slot
8822 if( bag != NULL_BAG && slot != NULL_SLOT )
8824 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8825 if(res!=EQUIP_ERR_OK)
8827 if(no_space_count)
8828 *no_space_count = count + no_similar_count;
8829 return res;
8832 if(count==0)
8834 if(no_similar_count==0)
8835 return EQUIP_ERR_OK;
8837 if(no_space_count)
8838 *no_space_count = count + no_similar_count;
8839 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8843 // not specific slot or have space for partly store only in specific slot
8845 // in specific bag
8846 if( bag != NULL_BAG )
8848 // search stack in bag for merge to
8849 if( pProto->Stackable != 1 )
8851 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8853 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8854 if(res!=EQUIP_ERR_OK)
8856 if(no_space_count)
8857 *no_space_count = count + no_similar_count;
8858 return res;
8861 if(count==0)
8863 if(no_similar_count==0)
8864 return EQUIP_ERR_OK;
8866 if(no_space_count)
8867 *no_space_count = count + no_similar_count;
8868 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8871 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8872 if(res!=EQUIP_ERR_OK)
8874 if(no_space_count)
8875 *no_space_count = count + no_similar_count;
8876 return res;
8879 if(count==0)
8881 if(no_similar_count==0)
8882 return EQUIP_ERR_OK;
8884 if(no_space_count)
8885 *no_space_count = count + no_similar_count;
8886 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8889 else // equipped bag
8891 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8892 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8893 if(res!=EQUIP_ERR_OK)
8894 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8896 if(res!=EQUIP_ERR_OK)
8898 if(no_space_count)
8899 *no_space_count = count + no_similar_count;
8900 return res;
8903 if(count==0)
8905 if(no_similar_count==0)
8906 return EQUIP_ERR_OK;
8908 if(no_space_count)
8909 *no_space_count = count + no_similar_count;
8910 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8915 // search free slot in bag for place to
8916 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8918 // search free slot - keyring case
8919 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8921 uint32 keyringSize = GetMaxKeyringSize();
8922 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8923 if(res!=EQUIP_ERR_OK)
8925 if(no_space_count)
8926 *no_space_count = count + no_similar_count;
8927 return res;
8930 if(count==0)
8932 if(no_similar_count==0)
8933 return EQUIP_ERR_OK;
8935 if(no_space_count)
8936 *no_space_count = count + no_similar_count;
8937 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8940 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8941 if(res!=EQUIP_ERR_OK)
8943 if(no_space_count)
8944 *no_space_count = count + no_similar_count;
8945 return res;
8948 if(count==0)
8950 if(no_similar_count==0)
8951 return EQUIP_ERR_OK;
8953 if(no_space_count)
8954 *no_space_count = count + no_similar_count;
8955 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8958 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
8960 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8961 if(res!=EQUIP_ERR_OK)
8963 if(no_space_count)
8964 *no_space_count = count + no_similar_count;
8965 return res;
8968 if(count==0)
8970 if(no_similar_count==0)
8971 return EQUIP_ERR_OK;
8973 if(no_space_count)
8974 *no_space_count = count + no_similar_count;
8975 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8979 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8980 if(res!=EQUIP_ERR_OK)
8982 if(no_space_count)
8983 *no_space_count = count + no_similar_count;
8984 return res;
8987 if(count==0)
8989 if(no_similar_count==0)
8990 return EQUIP_ERR_OK;
8992 if(no_space_count)
8993 *no_space_count = count + no_similar_count;
8994 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8997 else // equipped bag
8999 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9000 if(res!=EQUIP_ERR_OK)
9001 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9003 if(res!=EQUIP_ERR_OK)
9005 if(no_space_count)
9006 *no_space_count = count + no_similar_count;
9007 return res;
9010 if(count==0)
9012 if(no_similar_count==0)
9013 return EQUIP_ERR_OK;
9015 if(no_space_count)
9016 *no_space_count = count + no_similar_count;
9017 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9022 // not specific bag or have space for partly store only in specific bag
9024 // search stack for merge to
9025 if( pProto->Stackable != 1 )
9027 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9028 if(res!=EQUIP_ERR_OK)
9030 if(no_space_count)
9031 *no_space_count = count + no_similar_count;
9032 return res;
9035 if(count==0)
9037 if(no_similar_count==0)
9038 return EQUIP_ERR_OK;
9040 if(no_space_count)
9041 *no_space_count = count + no_similar_count;
9042 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9045 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9046 if(res!=EQUIP_ERR_OK)
9048 if(no_space_count)
9049 *no_space_count = count + no_similar_count;
9050 return res;
9053 if(count==0)
9055 if(no_similar_count==0)
9056 return EQUIP_ERR_OK;
9058 if(no_space_count)
9059 *no_space_count = count + no_similar_count;
9060 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9063 if( pProto->BagFamily )
9065 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9067 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9068 if(res!=EQUIP_ERR_OK)
9069 continue;
9071 if(count==0)
9073 if(no_similar_count==0)
9074 return EQUIP_ERR_OK;
9076 if(no_space_count)
9077 *no_space_count = count + no_similar_count;
9078 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9083 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9085 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9086 if(res!=EQUIP_ERR_OK)
9087 continue;
9089 if(count==0)
9091 if(no_similar_count==0)
9092 return EQUIP_ERR_OK;
9094 if(no_space_count)
9095 *no_space_count = count + no_similar_count;
9096 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9101 // search free slot - special bag case
9102 if( pProto->BagFamily )
9104 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9106 uint32 keyringSize = GetMaxKeyringSize();
9107 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9108 if(res!=EQUIP_ERR_OK)
9110 if(no_space_count)
9111 *no_space_count = count + no_similar_count;
9112 return res;
9115 if(count==0)
9117 if(no_similar_count==0)
9118 return EQUIP_ERR_OK;
9120 if(no_space_count)
9121 *no_space_count = count + no_similar_count;
9122 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9125 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9127 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9128 if(res!=EQUIP_ERR_OK)
9130 if(no_space_count)
9131 *no_space_count = count + no_similar_count;
9132 return res;
9135 if(count==0)
9137 if(no_similar_count==0)
9138 return EQUIP_ERR_OK;
9140 if(no_space_count)
9141 *no_space_count = count + no_similar_count;
9142 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9146 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9148 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9149 if(res!=EQUIP_ERR_OK)
9150 continue;
9152 if(count==0)
9154 if(no_similar_count==0)
9155 return EQUIP_ERR_OK;
9157 if(no_space_count)
9158 *no_space_count = count + no_similar_count;
9159 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9164 // search free slot
9165 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9166 if(res!=EQUIP_ERR_OK)
9168 if(no_space_count)
9169 *no_space_count = count + no_similar_count;
9170 return res;
9173 if(count==0)
9175 if(no_similar_count==0)
9176 return EQUIP_ERR_OK;
9178 if(no_space_count)
9179 *no_space_count = count + no_similar_count;
9180 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9183 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9185 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9186 if(res!=EQUIP_ERR_OK)
9187 continue;
9189 if(count==0)
9191 if(no_similar_count==0)
9192 return EQUIP_ERR_OK;
9194 if(no_space_count)
9195 *no_space_count = count + no_similar_count;
9196 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9200 if(no_space_count)
9201 *no_space_count = count + no_similar_count;
9203 return EQUIP_ERR_INVENTORY_FULL;
9206 //////////////////////////////////////////////////////////////////////////
9207 uint8 Player::CanStoreItems( Item **pItems,int count) const
9209 Item *pItem2;
9211 // fill space table
9212 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9213 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9214 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9215 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9217 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9218 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9219 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9220 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9222 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9224 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9226 if (pItem2 && !pItem2->IsInTrade())
9228 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9232 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9234 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9236 if (pItem2 && !pItem2->IsInTrade())
9238 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9242 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9244 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9246 if (pItem2 && !pItem2->IsInTrade())
9248 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9252 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9254 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9256 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9258 pItem2 = GetItemByPos( i, j );
9259 if (pItem2 && !pItem2->IsInTrade())
9261 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9267 // check free space for all items
9268 for (int k=0;k<count;k++)
9270 Item *pItem = pItems[k];
9272 // no item
9273 if (!pItem) continue;
9275 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9276 ItemPrototype const *pProto = pItem->GetProto();
9278 // strange item
9279 if( !pProto )
9280 return EQUIP_ERR_ITEM_NOT_FOUND;
9282 // item it 'bind'
9283 if(pItem->IsBindedNotWith(GetGUID()))
9284 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9286 Bag *pBag;
9287 ItemPrototype const *pBagProto;
9289 // item is 'one item only'
9290 uint8 res = CanTakeMoreSimilarItems(pItem);
9291 if(res != EQUIP_ERR_OK)
9292 return res;
9294 // search stack for merge to
9295 if( pProto->Stackable != 1 )
9297 bool b_found = false;
9299 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9301 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9302 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9304 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9305 b_found = true;
9306 break;
9309 if (b_found) continue;
9311 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9313 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9314 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9316 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9317 b_found = true;
9318 break;
9321 if (b_found) continue;
9323 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9325 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9326 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9328 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9329 b_found = true;
9330 break;
9333 if (b_found) continue;
9335 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9337 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9338 if( pBag )
9340 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9342 pItem2 = GetItemByPos( t, j );
9343 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9345 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9346 b_found = true;
9347 break;
9352 if (b_found) continue;
9355 // special bag case
9356 if( pProto->BagFamily )
9358 bool b_found = false;
9359 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9361 uint32 keyringSize = GetMaxKeyringSize();
9362 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9364 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9366 inv_keys[t-KEYRING_SLOT_START] = 1;
9367 b_found = true;
9368 break;
9373 if (b_found) continue;
9375 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9377 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9379 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9381 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9382 b_found = true;
9383 break;
9388 if (b_found) continue;
9390 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9392 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9393 if( pBag )
9395 pBagProto = pBag->GetProto();
9397 // not plain container check
9398 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9399 ItemCanGoIntoBag(pProto,pBagProto) )
9401 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9403 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9405 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9406 b_found = true;
9407 break;
9413 if (b_found) continue;
9416 // search free slot
9417 bool b_found = false;
9418 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9420 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9422 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9423 b_found = true;
9424 break;
9427 if (b_found) continue;
9429 // search free slot in bags
9430 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9432 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9433 if( pBag )
9435 pBagProto = pBag->GetProto();
9437 // special bag already checked
9438 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9439 continue;
9441 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9443 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9445 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9446 b_found = true;
9447 break;
9453 // no free slot found?
9454 if (!b_found)
9455 return EQUIP_ERR_INVENTORY_FULL;
9458 return EQUIP_ERR_OK;
9461 //////////////////////////////////////////////////////////////////////////
9462 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9464 dest = 0;
9465 Item *pItem = Item::CreateItem( item, 1, this );
9466 if( pItem )
9468 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9469 delete pItem;
9470 return result;
9473 return EQUIP_ERR_ITEM_NOT_FOUND;
9476 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9478 dest = 0;
9479 if( pItem )
9481 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9482 ItemPrototype const *pProto = pItem->GetProto();
9483 if( pProto )
9485 if(pItem->IsBindedNotWith(GetGUID()))
9486 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9488 // check count of items (skip for auto move for same player from bank)
9489 uint8 res = CanTakeMoreSimilarItems(pItem);
9490 if(res != EQUIP_ERR_OK)
9491 return res;
9493 // check this only in game
9494 if(not_loading)
9496 // May be here should be more stronger checks; STUNNED checked
9497 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9498 if (hasUnitState(UNIT_STAT_STUNNED))
9499 return EQUIP_ERR_YOU_ARE_STUNNED;
9501 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9502 // - combat
9503 // - in-progress arenas
9504 if( !pProto->CanChangeEquipStateInCombat() )
9506 if( isInCombat() )
9507 return EQUIP_ERR_NOT_IN_COMBAT;
9509 if(BattleGround* bg = GetBattleGround())
9510 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9511 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9514 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9515 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9517 if(IsNonMeleeSpellCasted(false))
9518 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9521 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9522 if( eslot == NULL_SLOT )
9523 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9525 uint8 msg = CanUseItem( pItem , not_loading );
9526 if( msg != EQUIP_ERR_OK )
9527 return msg;
9528 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9529 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9531 // if swap ignore item (equipped also)
9532 if(uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9533 return res2;
9535 // check unique-equipped special item classes
9536 if (pProto->Class == ITEM_CLASS_QUIVER)
9538 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9540 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9542 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9544 if( pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot ) )
9546 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9547 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9548 else
9549 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9556 uint32 type = pProto->InventoryType;
9558 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9560 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9562 if(!CanDualWield())
9563 return EQUIP_ERR_CANT_DUAL_WIELD;
9565 else if (type == INVTYPE_2HWEAPON)
9567 if(!CanDualWield() || !CanTitanGrip())
9568 return EQUIP_ERR_CANT_DUAL_WIELD;
9571 if(IsTwoHandUsed())
9572 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9575 // equip two-hand weapon case (with possible unequip 2 items)
9576 if( type == INVTYPE_2HWEAPON )
9578 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9580 if (!CanTitanGrip())
9581 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9583 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9584 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9586 if (!CanTitanGrip())
9588 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9589 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9590 ItemPosCountVec off_dest;
9591 if( offItem && (!not_loading ||
9592 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9593 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9594 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9597 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9598 return EQUIP_ERR_OK;
9601 if( !swap )
9602 return EQUIP_ERR_ITEM_NOT_FOUND;
9603 else
9604 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9607 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9609 // Applied only to equipped items and bank bags
9610 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9611 return EQUIP_ERR_OK;
9613 Item* pItem = GetItemByPos(pos);
9615 // Applied only to existed equipped item
9616 if( !pItem )
9617 return EQUIP_ERR_OK;
9619 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9621 ItemPrototype const *pProto = pItem->GetProto();
9622 if( !pProto )
9623 return EQUIP_ERR_ITEM_NOT_FOUND;
9625 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9626 // - combat
9627 // - in-progress arenas
9628 if( !pProto->CanChangeEquipStateInCombat() )
9630 if( isInCombat() )
9631 return EQUIP_ERR_NOT_IN_COMBAT;
9633 if(BattleGround* bg = GetBattleGround())
9634 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9635 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9638 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9639 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9641 return EQUIP_ERR_OK;
9644 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9646 if( !pItem )
9647 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9649 uint32 count = pItem->GetCount();
9651 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9652 ItemPrototype const *pProto = pItem->GetProto();
9653 if( !pProto )
9654 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9656 if( pItem->IsBindedNotWith(GetGUID()) )
9657 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9659 // check count of items (skip for auto move for same player from bank)
9660 uint8 res = CanTakeMoreSimilarItems(pItem);
9661 if(res != EQUIP_ERR_OK)
9662 return res;
9664 // in specific slot
9665 if( bag != NULL_BAG && slot != NULL_SLOT )
9667 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9669 if (!pItem->IsBag())
9670 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9672 Bag *pBag = (Bag*)pItem;
9673 if( !HasBankBagSlot( slot ) )
9674 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9676 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9677 return cantuse;
9680 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9681 if(res!=EQUIP_ERR_OK)
9682 return res;
9684 if(count==0)
9685 return EQUIP_ERR_OK;
9688 // not specific slot or have space for partly store only in specific slot
9690 // in specific bag
9691 if( bag != NULL_BAG )
9693 if( pProto->InventoryType == INVTYPE_BAG )
9695 Bag *pBag = (Bag*)pItem;
9696 if( pBag && !pBag->IsEmpty() )
9697 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9700 // search stack in bag for merge to
9701 if( pProto->Stackable != 1 )
9703 if( bag == INVENTORY_SLOT_BAG_0 )
9705 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9706 if(res!=EQUIP_ERR_OK)
9707 return res;
9709 if(count==0)
9710 return EQUIP_ERR_OK;
9712 else
9714 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9715 if(res!=EQUIP_ERR_OK)
9716 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9718 if(res!=EQUIP_ERR_OK)
9719 return res;
9721 if(count==0)
9722 return EQUIP_ERR_OK;
9726 // search free slot in bag
9727 if( bag == INVENTORY_SLOT_BAG_0 )
9729 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9730 if(res!=EQUIP_ERR_OK)
9731 return res;
9733 if(count==0)
9734 return EQUIP_ERR_OK;
9736 else
9738 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9739 if(res!=EQUIP_ERR_OK)
9740 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9742 if(res!=EQUIP_ERR_OK)
9743 return res;
9745 if(count==0)
9746 return EQUIP_ERR_OK;
9750 // not specific bag or have space for partly store only in specific bag
9752 // search stack for merge to
9753 if( pProto->Stackable != 1 )
9755 // in slots
9756 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9757 if(res!=EQUIP_ERR_OK)
9758 return res;
9760 if(count==0)
9761 return EQUIP_ERR_OK;
9763 // in special bags
9764 if( pProto->BagFamily )
9766 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9768 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9769 if(res!=EQUIP_ERR_OK)
9770 continue;
9772 if(count==0)
9773 return EQUIP_ERR_OK;
9777 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9779 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9780 if(res!=EQUIP_ERR_OK)
9781 continue;
9783 if(count==0)
9784 return EQUIP_ERR_OK;
9788 // search free place in special bag
9789 if( pProto->BagFamily )
9791 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9793 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9794 if(res!=EQUIP_ERR_OK)
9795 continue;
9797 if(count==0)
9798 return EQUIP_ERR_OK;
9802 // search free space
9803 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9804 if(res!=EQUIP_ERR_OK)
9805 return res;
9807 if(count==0)
9808 return EQUIP_ERR_OK;
9810 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9812 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9813 if(res!=EQUIP_ERR_OK)
9814 continue;
9816 if(count==0)
9817 return EQUIP_ERR_OK;
9819 return EQUIP_ERR_BANK_FULL;
9822 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9824 if( pItem )
9826 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9827 if( !isAlive() && not_loading )
9828 return EQUIP_ERR_YOU_ARE_DEAD;
9829 //if( isStunned() )
9830 // return EQUIP_ERR_YOU_ARE_STUNNED;
9831 ItemPrototype const *pProto = pItem->GetProto();
9832 if( pProto )
9834 if( pItem->IsBindedNotWith(GetGUID()) )
9835 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9836 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9837 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9838 if( pItem->GetSkill() != 0 )
9840 if( GetSkillValue( pItem->GetSkill() ) == 0 )
9841 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9843 if( pProto->RequiredSkill != 0 )
9845 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9846 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9847 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9848 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9850 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9851 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9852 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
9853 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9854 if( getLevel() < pProto->RequiredLevel )
9855 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9856 return EQUIP_ERR_OK;
9859 return EQUIP_ERR_ITEM_NOT_FOUND;
9862 bool Player::CanUseItem( ItemPrototype const *pProto )
9864 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9866 if( pProto )
9868 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9869 return false;
9870 if( pProto->RequiredSkill != 0 )
9872 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9873 return false;
9874 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9875 return false;
9877 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9878 return false;
9879 if( getLevel() < pProto->RequiredLevel )
9880 return false;
9881 return true;
9883 return false;
9886 uint8 Player::CanUseAmmo( uint32 item ) const
9888 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
9889 if( !isAlive() )
9890 return EQUIP_ERR_YOU_ARE_DEAD;
9891 //if( isStunned() )
9892 // return EQUIP_ERR_YOU_ARE_STUNNED;
9893 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
9894 if( pProto )
9896 if( pProto->InventoryType!= INVTYPE_AMMO )
9897 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
9898 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9899 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9900 if( pProto->RequiredSkill != 0 )
9902 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9903 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9904 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9905 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9907 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9908 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9909 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
9910 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9912 if( getLevel() < pProto->RequiredLevel )
9913 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9915 // Requires No Ammo
9916 if(GetDummyAura(46699))
9917 return EQUIP_ERR_BAG_FULL6;
9919 return EQUIP_ERR_OK;
9921 return EQUIP_ERR_ITEM_NOT_FOUND;
9924 void Player::SetAmmo( uint32 item )
9926 if(!item)
9927 return;
9929 // already set
9930 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
9931 return;
9933 // check ammo
9934 if(item)
9936 uint8 msg = CanUseAmmo( item );
9937 if( msg != EQUIP_ERR_OK )
9939 SendEquipError( msg, NULL, NULL );
9940 return;
9944 SetUInt32Value(PLAYER_AMMO_ID, item);
9946 _ApplyAmmoBonuses();
9949 void Player::RemoveAmmo()
9951 SetUInt32Value(PLAYER_AMMO_ID, 0);
9953 m_ammoDPS = 0.0f;
9955 if(CanModifyStats())
9956 UpdateDamagePhysical(RANGED_ATTACK);
9959 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9960 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
9962 uint32 count = 0;
9963 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
9964 count += itr->count;
9966 Item *pItem = Item::CreateItem( item, count, this );
9967 if( pItem )
9969 ItemAddedQuestCheck( item, count );
9970 if(randomPropertyId)
9971 pItem->SetItemRandomProperties(randomPropertyId);
9972 pItem = StoreItem( dest, pItem, update );
9974 return pItem;
9977 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
9979 if( !pItem )
9980 return NULL;
9982 Item* lastItem = pItem;
9983 uint32 entry = pItem->GetEntry();
9984 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
9986 uint16 pos = itr->pos;
9987 uint32 count = itr->count;
9989 ++itr;
9991 if(itr == dest.end())
9993 lastItem = _StoreItem(pos,pItem,count,false,update);
9994 break;
9997 lastItem = _StoreItem(pos,pItem,count,true,update);
9999 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10000 return lastItem;
10003 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10004 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10006 if( !pItem )
10007 return NULL;
10009 uint8 bag = pos >> 8;
10010 uint8 slot = pos & 255;
10012 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10014 Item *pItem2 = GetItemByPos( bag, slot );
10016 if (!pItem2)
10018 if (clone)
10019 pItem = pItem->CloneItem(count,this);
10020 else
10021 pItem->SetCount(count);
10023 if (!pItem)
10024 return NULL;
10026 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10027 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10028 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10029 pItem->SetBinding( true );
10031 if (bag == INVENTORY_SLOT_BAG_0)
10033 m_items[slot] = pItem;
10034 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10035 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10036 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10038 pItem->SetSlot( slot );
10039 pItem->SetContainer( NULL );
10041 // need update known currency
10042 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10043 UpdateKnownCurrencies(pItem->GetEntry(),true);
10045 if (IsInWorld() && update)
10047 pItem->AddToWorld();
10048 pItem->SendUpdateToPlayer( this );
10051 pItem->SetState(ITEM_CHANGED, this);
10053 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10055 pBag->StoreItem( slot, pItem, update );
10056 if( IsInWorld() && update )
10058 pItem->AddToWorld();
10059 pItem->SendUpdateToPlayer( this );
10061 pItem->SetState(ITEM_CHANGED, this);
10062 pBag->SetState(ITEM_CHANGED, this);
10065 AddEnchantmentDurations(pItem);
10066 AddItemDurations(pItem);
10068 return pItem;
10070 else
10072 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10073 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10074 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10075 pItem2->SetBinding( true );
10077 pItem2->SetCount( pItem2->GetCount() + count );
10078 if (IsInWorld() && update)
10079 pItem2->SendUpdateToPlayer( this );
10081 if (!clone)
10083 // delete item (it not in any slot currently)
10084 if (IsInWorld() && update)
10086 pItem->RemoveFromWorld();
10087 pItem->DestroyForPlayer( this );
10090 RemoveEnchantmentDurations(pItem);
10091 RemoveItemDurations(pItem);
10093 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10094 pItem->SetState(ITEM_REMOVED, this);
10097 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10098 AddEnchantmentDurations(pItem2);
10100 pItem2->SetState(ITEM_CHANGED, this);
10102 return pItem2;
10106 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10108 if (Item *pItem = Item::CreateItem( item, 1, this ))
10110 ItemAddedQuestCheck( item, 1 );
10111 return EquipItem( pos, pItem, update );
10114 return NULL;
10117 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10120 AddEnchantmentDurations(pItem);
10121 AddItemDurations(pItem);
10123 uint8 bag = pos >> 8;
10124 uint8 slot = pos & 255;
10126 Item *pItem2 = GetItemByPos( bag, slot );
10128 if( !pItem2 )
10130 VisualizeItem( slot, pItem);
10132 if(isAlive())
10134 ItemPrototype const *pProto = pItem->GetProto();
10136 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10137 if(pProto && pProto->ItemSet)
10138 AddItemsSetItem(this,pItem);
10140 _ApplyItemMods(pItem, slot, true);
10142 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10144 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10146 if (getClass() == CLASS_ROGUE)
10147 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10149 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10151 if (!spellProto)
10152 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10153 else
10155 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10157 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10158 data << uint64(GetGUID());
10159 data << uint8(1);
10160 data << uint32(cooldownSpell);
10161 data << uint32(0);
10162 GetSession()->SendPacket(&data);
10167 if( IsInWorld() && update )
10169 pItem->AddToWorld();
10170 pItem->SendUpdateToPlayer( this );
10173 ApplyEquipCooldown(pItem);
10175 if( slot == EQUIPMENT_SLOT_MAINHAND )
10176 UpdateExpertise(BASE_ATTACK);
10177 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10178 UpdateExpertise(OFF_ATTACK);
10180 else
10182 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10183 if( IsInWorld() && update )
10184 pItem2->SendUpdateToPlayer( this );
10186 // delete item (it not in any slot currently)
10187 //pItem->DeleteFromDB();
10188 if( IsInWorld() && update )
10190 pItem->RemoveFromWorld();
10191 pItem->DestroyForPlayer( this );
10194 RemoveEnchantmentDurations(pItem);
10195 RemoveItemDurations(pItem);
10197 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10198 pItem->SetState(ITEM_REMOVED, this);
10199 pItem2->SetState(ITEM_CHANGED, this);
10201 ApplyEquipCooldown(pItem2);
10203 return pItem2;
10206 // only for full equip instead adding to stack
10207 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10209 return pItem;
10212 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10214 if( pItem )
10216 AddEnchantmentDurations(pItem);
10217 AddItemDurations(pItem);
10219 uint8 slot = pos & 255;
10220 VisualizeItem( slot, pItem);
10222 if( IsInWorld() )
10224 pItem->AddToWorld();
10225 pItem->SendUpdateToPlayer( this );
10230 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10232 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10233 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10234 // entry // Size: 1
10235 // inspected enchantments // Size: 6
10236 // ? // Size: 5
10237 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10238 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10239 // // = 16
10241 if(pItem)
10243 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10245 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10246 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10248 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10249 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10251 // Use SetInt16Value to prevent set high part to FFFF for negative value
10252 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10253 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10255 else
10257 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10259 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10260 SetUInt32Value(VisibleBase + 0, 0);
10262 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10263 SetUInt32Value(VisibleBase + 1 + i, 0);
10265 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10266 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10270 void Player::VisualizeItem( uint8 slot, Item *pItem)
10272 if(!pItem)
10273 return;
10275 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10276 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10277 pItem->SetBinding( true );
10279 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10281 m_items[slot] = pItem;
10282 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10283 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10284 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10285 pItem->SetSlot( slot );
10286 pItem->SetContainer( NULL );
10288 if( slot < EQUIPMENT_SLOT_END )
10289 SetVisibleItemSlot(slot,pItem);
10291 pItem->SetState(ITEM_CHANGED, this);
10294 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10296 // note: removeitem does not actually change the item
10297 // it only takes the item out of storage temporarily
10298 // note2: if removeitem is to be used for delinking
10299 // the item must be removed from the player's updatequeue
10301 Item *pItem = GetItemByPos( bag, slot );
10302 if( pItem )
10304 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10306 RemoveEnchantmentDurations(pItem);
10307 RemoveItemDurations(pItem);
10309 if( bag == INVENTORY_SLOT_BAG_0 )
10311 if ( slot < INVENTORY_SLOT_BAG_END )
10313 ItemPrototype const *pProto = pItem->GetProto();
10314 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10316 if(pProto && pProto->ItemSet)
10317 RemoveItemsSetItem(this,pProto);
10319 _ApplyItemMods(pItem, slot, false);
10321 // remove item dependent auras and casts (only weapon and armor slots)
10322 if(slot < EQUIPMENT_SLOT_END)
10324 RemoveItemDependentAurasAndCasts(pItem);
10326 // remove held enchantments, update expertise
10327 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10329 if (pItem->GetItemSuffixFactor())
10331 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10332 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10334 else
10336 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10337 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10340 UpdateExpertise(BASE_ATTACK);
10342 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10343 UpdateExpertise(OFF_ATTACK);
10346 // need update known currency
10347 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10348 UpdateKnownCurrencies(pItem->GetEntry(),false);
10350 m_items[slot] = NULL;
10351 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10353 if ( slot < EQUIPMENT_SLOT_END )
10354 SetVisibleItemSlot(slot,NULL);
10356 else
10358 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10359 if( pBag )
10360 pBag->RemoveItem(slot, update);
10362 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10363 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10364 pItem->SetSlot( NULL_SLOT );
10365 if( IsInWorld() && update )
10366 pItem->SendUpdateToPlayer( this );
10370 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10371 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10373 if(Item* it = GetItemByPos(bag,slot))
10375 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10376 RemoveItem( bag,slot,update);
10377 it->RemoveFromUpdateQueueOf(this);
10378 if(it->IsInWorld())
10380 it->RemoveFromWorld();
10381 it->DestroyForPlayer( this );
10386 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10387 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10389 // update quest counters
10390 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10392 // store item
10393 Item* pLastItem = StoreItem( dest, pItem, update);
10395 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10396 if(pLastItem==pItem)
10398 // update owner for last item (this can be original item with wrong owner
10399 if(pLastItem->GetOwnerGUID() != GetGUID())
10400 pLastItem->SetOwnerGUID(GetGUID());
10402 // if this original item then it need create record in inventory
10403 // in case trade we already have item in other player inventory
10404 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10408 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10410 Item *pItem = GetItemByPos( bag, slot );
10411 if( pItem )
10413 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10415 // start from destroy contained items (only equipped bag can have its)
10416 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10418 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10419 DestroyItem(slot,i,update);
10422 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10423 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10425 RemoveEnchantmentDurations(pItem);
10426 RemoveItemDurations(pItem);
10428 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10430 if( bag == INVENTORY_SLOT_BAG_0 )
10432 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10434 // equipment and equipped bags can have applied bonuses
10435 if ( slot < INVENTORY_SLOT_BAG_END )
10437 ItemPrototype const *pProto = pItem->GetProto();
10439 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10440 if(pProto && pProto->ItemSet)
10441 RemoveItemsSetItem(this,pProto);
10443 _ApplyItemMods(pItem, slot, false);
10446 if ( slot < EQUIPMENT_SLOT_END )
10448 // remove item dependent auras and casts (only weapon and armor slots)
10449 RemoveItemDependentAurasAndCasts(pItem);
10451 // update expertise
10452 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10453 UpdateExpertise(BASE_ATTACK);
10454 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10455 UpdateExpertise(OFF_ATTACK);
10457 // equipment visual show
10458 SetVisibleItemSlot(slot,NULL);
10460 // need update known currency
10461 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10462 UpdateKnownCurrencies(pItem->GetEntry(),false);
10464 m_items[slot] = NULL;
10466 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10467 pBag->RemoveItem(slot, update);
10469 if( IsInWorld() && update )
10471 pItem->RemoveFromWorld();
10472 pItem->DestroyForPlayer(this);
10475 //pItem->SetOwnerGUID(0);
10476 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10477 pItem->SetSlot( NULL_SLOT );
10478 pItem->SetState(ITEM_REMOVED, this);
10482 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10484 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10485 uint32 remcount = 0;
10487 // in inventory
10488 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10490 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10492 if (pItem->GetEntry() == item)
10494 if (pItem->GetCount() + remcount <= count)
10496 // all items in inventory can unequipped
10497 remcount += pItem->GetCount();
10498 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10500 if (remcount >=count)
10501 return;
10503 else
10505 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10506 pItem->SetCount( pItem->GetCount() - count + remcount );
10507 if (IsInWorld() & update)
10508 pItem->SendUpdateToPlayer( this );
10509 pItem->SetState(ITEM_CHANGED, this);
10510 return;
10516 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
10518 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10520 if (pItem->GetEntry() == item)
10522 if (pItem->GetCount() + remcount <= count)
10524 // all keys can be unequipped
10525 remcount += pItem->GetCount();
10526 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10528 if (remcount >=count)
10529 return;
10531 else
10533 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10534 pItem->SetCount( pItem->GetCount() - count + remcount );
10535 if (IsInWorld() & update)
10536 pItem->SendUpdateToPlayer( this );
10537 pItem->SetState(ITEM_CHANGED, this);
10538 return;
10544 // in inventory bags
10545 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10547 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10549 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10551 if(Item* pItem = pBag->GetItemByPos(j))
10553 if (pItem->GetEntry() == item)
10555 // all items in bags can be unequipped
10556 if (pItem->GetCount() + remcount <= count)
10558 remcount += pItem->GetCount();
10559 DestroyItem( i, j, update );
10561 if (remcount >=count)
10562 return;
10564 else
10566 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10567 pItem->SetCount( pItem->GetCount() - count + remcount );
10568 if (IsInWorld() && update)
10569 pItem->SendUpdateToPlayer( this );
10570 pItem->SetState(ITEM_CHANGED, this);
10571 return;
10579 // in equipment and bag list
10580 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10582 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10584 if (pItem && pItem->GetEntry() == item)
10586 if (pItem->GetCount() + remcount <= count)
10588 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10590 remcount += pItem->GetCount();
10591 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10593 if (remcount >=count)
10594 return;
10597 else
10599 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10600 pItem->SetCount( pItem->GetCount() - count + remcount );
10601 if (IsInWorld() & update)
10602 pItem->SendUpdateToPlayer( this );
10603 pItem->SetState(ITEM_CHANGED, this);
10604 return;
10611 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10613 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10615 // in inventory
10616 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10617 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10618 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10619 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10621 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
10622 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10623 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10624 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10626 // in inventory bags
10627 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10628 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10629 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10630 if (Item* pItem = pBag->GetItemByPos(j))
10631 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10632 DestroyItem( i, j, update);
10634 // in equipment and bag list
10635 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10636 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10637 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10638 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10641 void Player::DestroyConjuredItems( bool update )
10643 // used when entering arena
10644 // destroys all conjured items
10645 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10647 // in inventory
10648 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10649 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10650 if (pItem->IsConjuredConsumable())
10651 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10653 // in inventory bags
10654 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10655 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10656 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10657 if (Item* pItem = pBag->GetItemByPos(j))
10658 if (pItem->IsConjuredConsumable())
10659 DestroyItem( i, j, update);
10661 // in equipment and bag list
10662 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10663 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10664 if (pItem->IsConjuredConsumable())
10665 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10668 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10670 if(!pItem)
10671 return;
10673 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10675 if( pItem->GetCount() <= count )
10677 count-= pItem->GetCount();
10679 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10681 else
10683 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10684 pItem->SetCount( pItem->GetCount() - count );
10685 count = 0;
10686 if( IsInWorld() & update )
10687 pItem->SendUpdateToPlayer( this );
10688 pItem->SetState(ITEM_CHANGED, this);
10692 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10694 uint8 srcbag = src >> 8;
10695 uint8 srcslot = src & 255;
10697 uint8 dstbag = dst >> 8;
10698 uint8 dstslot = dst & 255;
10700 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10701 if( !pSrcItem )
10703 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10704 return;
10707 // not let split all items (can be only at cheating)
10708 if(pSrcItem->GetCount() == count)
10710 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10711 return;
10714 // not let split more existed items (can be only at cheating)
10715 if(pSrcItem->GetCount() < count)
10717 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10718 return;
10721 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10723 //best error message found for attempting to split while looting
10724 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10725 return;
10728 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10729 Item *pNewItem = pSrcItem->CloneItem( count, this );
10730 if( !pNewItem )
10732 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10733 return;
10736 if( IsInventoryPos( dst ) )
10738 // change item amount before check (for unique max count check)
10739 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10741 ItemPosCountVec dest;
10742 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10743 if( msg != EQUIP_ERR_OK )
10745 delete pNewItem;
10746 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10747 SendEquipError( msg, pSrcItem, NULL );
10748 return;
10751 if( IsInWorld() )
10752 pSrcItem->SendUpdateToPlayer( this );
10753 pSrcItem->SetState(ITEM_CHANGED, this);
10754 StoreItem( dest, pNewItem, true);
10756 else if( IsBankPos ( dst ) )
10758 // change item amount before check (for unique max count check)
10759 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10761 ItemPosCountVec dest;
10762 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10763 if( msg != EQUIP_ERR_OK )
10765 delete pNewItem;
10766 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10767 SendEquipError( msg, pSrcItem, NULL );
10768 return;
10771 if( IsInWorld() )
10772 pSrcItem->SendUpdateToPlayer( this );
10773 pSrcItem->SetState(ITEM_CHANGED, this);
10774 BankItem( dest, pNewItem, true);
10776 else if( IsEquipmentPos ( dst ) )
10778 // change item amount before check (for unique max count check), provide space for splitted items
10779 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10781 uint16 dest;
10782 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10783 if( msg != EQUIP_ERR_OK )
10785 delete pNewItem;
10786 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10787 SendEquipError( msg, pSrcItem, NULL );
10788 return;
10791 if( IsInWorld() )
10792 pSrcItem->SendUpdateToPlayer( this );
10793 pSrcItem->SetState(ITEM_CHANGED, this);
10794 EquipItem( dest, pNewItem, true);
10795 AutoUnequipOffhandIfNeed();
10799 void Player::SwapItem( uint16 src, uint16 dst )
10801 uint8 srcbag = src >> 8;
10802 uint8 srcslot = src & 255;
10804 uint8 dstbag = dst >> 8;
10805 uint8 dstslot = dst & 255;
10807 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10808 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10810 if( !pSrcItem )
10811 return;
10813 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10815 if(!isAlive() )
10817 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10818 return;
10821 // SRC checks
10823 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10825 //best error message found for attempting to swap while looting
10826 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10827 return;
10830 // check unequip potability for equipped items and bank bags
10831 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10833 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10834 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
10835 if(msg != EQUIP_ERR_OK)
10837 SendEquipError( msg, pSrcItem, pDstItem );
10838 return;
10842 // prevent put equipped/bank bag in self
10843 if( IsBagPos ( src ) && srcslot == dstbag)
10845 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10846 return;
10849 // DST checks
10851 if (pDstItem)
10853 if(pDstItem->m_lootGenerated) // prevent swap looting item
10855 //best error message found for attempting to swap while looting
10856 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10857 return;
10860 // check unequip potability for equipped items and bank bags
10861 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10863 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10864 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
10865 if(msg != EQUIP_ERR_OK)
10867 SendEquipError( msg, pSrcItem, pDstItem );
10868 return;
10873 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10874 // or swap empty bag with another empty or not empty bag (with items exchange)
10876 // Move case
10877 if( !pDstItem )
10879 if( IsInventoryPos( dst ) )
10881 ItemPosCountVec dest;
10882 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10883 if( msg != EQUIP_ERR_OK )
10885 SendEquipError( msg, pSrcItem, NULL );
10886 return;
10889 RemoveItem(srcbag, srcslot, true);
10890 StoreItem( dest, pSrcItem, true);
10892 else if( IsBankPos ( dst ) )
10894 ItemPosCountVec dest;
10895 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10896 if( msg != EQUIP_ERR_OK )
10898 SendEquipError( msg, pSrcItem, NULL );
10899 return;
10902 RemoveItem(srcbag, srcslot, true);
10903 BankItem( dest, pSrcItem, true);
10905 else if( IsEquipmentPos ( dst ) )
10907 uint16 dest;
10908 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10909 if( msg != EQUIP_ERR_OK )
10911 SendEquipError( msg, pSrcItem, NULL );
10912 return;
10915 RemoveItem(srcbag, srcslot, true);
10916 EquipItem( dest, pSrcItem, true);
10917 AutoUnequipOffhandIfNeed();
10920 return;
10923 // attempt merge to / fill target item
10924 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
10926 uint8 msg;
10927 ItemPosCountVec sDest;
10928 uint16 eDest;
10929 if( IsInventoryPos( dst ) )
10930 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
10931 else if( IsBankPos ( dst ) )
10932 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
10933 else if( IsEquipmentPos ( dst ) )
10934 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
10935 else
10936 return;
10938 // can be merge/fill
10939 if(msg == EQUIP_ERR_OK)
10941 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
10943 RemoveItem(srcbag, srcslot, true);
10945 if( IsInventoryPos( dst ) )
10946 StoreItem( sDest, pSrcItem, true);
10947 else if( IsBankPos ( dst ) )
10948 BankItem( sDest, pSrcItem, true);
10949 else if( IsEquipmentPos ( dst ) )
10951 EquipItem( eDest, pSrcItem, true);
10952 AutoUnequipOffhandIfNeed();
10955 else
10957 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
10958 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
10959 pSrcItem->SetState(ITEM_CHANGED, this);
10960 pDstItem->SetState(ITEM_CHANGED, this);
10961 if( IsInWorld() )
10963 pSrcItem->SendUpdateToPlayer( this );
10964 pDstItem->SendUpdateToPlayer( this );
10967 return;
10971 // impossible merge/fill, do real swap
10972 uint8 msg;
10974 // check src->dest move possibility
10975 ItemPosCountVec sDest;
10976 uint16 eDest = 0;
10977 if( IsInventoryPos( dst ) )
10978 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
10979 else if( IsBankPos( dst ) )
10980 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
10981 else if( IsEquipmentPos( dst ) )
10983 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
10984 if( msg == EQUIP_ERR_OK )
10985 msg = CanUnequipItem( eDest, true );
10988 if( msg != EQUIP_ERR_OK )
10990 SendEquipError( msg, pSrcItem, pDstItem );
10991 return;
10994 // check dest->src move possibility
10995 ItemPosCountVec sDest2;
10996 uint16 eDest2 = 0;
10997 if( IsInventoryPos( src ) )
10998 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
10999 else if( IsBankPos( src ) )
11000 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11001 else if( IsEquipmentPos( src ) )
11003 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11004 if( msg == EQUIP_ERR_OK )
11005 msg = CanUnequipItem( eDest2, true);
11008 if( msg != EQUIP_ERR_OK )
11010 SendEquipError( msg, pDstItem, pSrcItem );
11011 return;
11014 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11015 if(pSrcItem->IsBag() && pDstItem->IsBag())
11017 Bag* emptyBag = NULL;
11018 Bag* fullBag = NULL;
11019 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11021 emptyBag = (Bag*)pSrcItem;
11022 fullBag = (Bag*)pDstItem;
11024 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11026 emptyBag = (Bag*)pDstItem;
11027 fullBag = (Bag*)pSrcItem;
11030 // bag swap (with items exchange) case
11031 if(emptyBag && fullBag)
11033 ItemPrototype const* emotyProto = emptyBag->GetProto();
11035 uint32 count = 0;
11037 for(int i=0; i < fullBag->GetBagSize(); ++i)
11039 Item *bagItem = fullBag->GetItemByPos(i);
11040 if (!bagItem)
11041 continue;
11043 ItemPrototype const* bagItemProto = bagItem->GetProto();
11044 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11046 // one from items not go to empry target bag
11047 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11048 return;
11051 ++count;
11055 if (count > emptyBag->GetBagSize())
11057 // too small targeted bag
11058 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11059 return;
11062 // Items swap
11063 count = 0; // will pos in new bag
11064 for(int i=0; i< fullBag->GetBagSize(); ++i)
11066 Item *bagItem = fullBag->GetItemByPos(i);
11067 if (!bagItem)
11068 continue;
11070 fullBag->RemoveItem(i, true);
11071 emptyBag->StoreItem(count, bagItem, true);
11072 bagItem->SetState(ITEM_CHANGED, this);
11074 ++count;
11079 // now do moves, remove...
11080 RemoveItem(dstbag, dstslot, false);
11081 RemoveItem(srcbag, srcslot, false);
11083 // add to dest
11084 if( IsInventoryPos( dst ) )
11085 StoreItem(sDest, pSrcItem, true);
11086 else if( IsBankPos( dst ) )
11087 BankItem(sDest, pSrcItem, true);
11088 else if( IsEquipmentPos( dst ) )
11089 EquipItem(eDest, pSrcItem, true);
11091 // add to src
11092 if( IsInventoryPos( src ) )
11093 StoreItem(sDest2, pDstItem, true);
11094 else if( IsBankPos( src ) )
11095 BankItem(sDest2, pDstItem, true);
11096 else if( IsEquipmentPos( src ) )
11097 EquipItem(eDest2, pDstItem, true);
11099 AutoUnequipOffhandIfNeed();
11102 void Player::AddItemToBuyBackSlot( Item *pItem )
11104 if( pItem )
11106 uint32 slot = m_currentBuybackSlot;
11107 // if current back slot non-empty search oldest or free
11108 if(m_items[slot])
11110 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11111 uint32 oldest_slot = BUYBACK_SLOT_START;
11113 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11115 // found empty
11116 if(!m_items[i])
11118 slot = i;
11119 break;
11122 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11124 if(oldest_time > i_time)
11126 oldest_time = i_time;
11127 oldest_slot = i;
11131 // find oldest
11132 slot = oldest_slot;
11135 RemoveItemFromBuyBackSlot( slot, true );
11136 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11138 m_items[slot] = pItem;
11139 time_t base = time(NULL);
11140 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11141 uint32 eslot = slot - BUYBACK_SLOT_START;
11143 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11144 ItemPrototype const *pProto = pItem->GetProto();
11145 if( pProto )
11146 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11147 else
11148 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11149 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11151 // move to next (for non filled list is move most optimized choice)
11152 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11153 ++m_currentBuybackSlot;
11157 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11159 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11160 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11161 return m_items[slot];
11162 return NULL;
11165 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11167 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11168 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11170 Item *pItem = m_items[slot];
11171 if( pItem )
11173 pItem->RemoveFromWorld();
11174 if(del) pItem->SetState(ITEM_REMOVED, this);
11177 m_items[slot] = NULL;
11179 uint32 eslot = slot - BUYBACK_SLOT_START;
11180 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11181 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11182 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11184 // if current backslot is filled set to now free slot
11185 if(m_items[m_currentBuybackSlot])
11186 m_currentBuybackSlot = slot;
11190 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11192 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11193 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11194 data << uint8(msg);
11196 if(msg)
11198 data << uint64(pItem ? pItem->GetGUID() : 0);
11199 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11200 data << uint8(0); // not 0 there...
11202 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11204 uint32 level = 0;
11206 if(pItem)
11207 if(ItemPrototype const* proto = pItem->GetProto())
11208 level = proto->RequiredLevel;
11210 data << uint32(level); // new 2.4.0
11213 GetSession()->SendPacket(&data);
11216 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11218 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11219 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11220 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11221 data << uint32(item);
11222 if( param > 0 )
11223 data << uint32(param);
11224 data << uint8(msg);
11225 GetSession()->SendPacket(&data);
11228 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11230 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11231 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11232 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11233 data << uint64(guid);
11234 if( param > 0 )
11235 data << uint32(param);
11236 data << uint8(msg);
11237 GetSession()->SendPacket(&data);
11240 void Player::ClearTrade()
11242 tradeGold = 0;
11243 acceptTrade = false;
11244 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11245 tradeItems[i] = NULL_SLOT;
11248 void Player::TradeCancel(bool sendback)
11250 if(pTrader)
11252 // send yellow "Trade canceled" message to both traders
11253 WorldSession* ws;
11254 ws = GetSession();
11255 if(sendback)
11256 ws->SendCancelTrade();
11257 ws = pTrader->GetSession();
11258 if(!ws->PlayerLogout())
11259 ws->SendCancelTrade();
11261 // cleanup
11262 ClearTrade();
11263 pTrader->ClearTrade();
11264 // prevent loss of reference
11265 pTrader->pTrader = NULL;
11266 pTrader = NULL;
11270 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11272 if(m_itemDuration.empty())
11273 return;
11275 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11277 for(ItemDurationList::const_iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11279 Item* item = *itr;
11280 ++itr; // current element can be erased in UpdateDuration
11282 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11283 item->UpdateDuration(this,time);
11287 void Player::UpdateEnchantTime(uint32 time)
11289 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11291 assert(itr->item);
11292 next=itr;
11293 if(!itr->item->GetEnchantmentId(itr->slot))
11295 next = m_enchantDuration.erase(itr);
11297 else if(itr->leftduration <= time)
11299 ApplyEnchantment(itr->item,itr->slot,false,false);
11300 itr->item->ClearEnchantment(itr->slot);
11301 next = m_enchantDuration.erase(itr);
11303 else if(itr->leftduration > time)
11305 itr->leftduration -= time;
11306 ++next;
11311 void Player::AddEnchantmentDurations(Item *item)
11313 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11315 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11316 continue;
11318 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11319 if( duration > 0 )
11320 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11324 void Player::RemoveEnchantmentDurations(Item *item)
11326 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11328 if(itr->item == item)
11330 // save duration in item
11331 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11332 itr = m_enchantDuration.erase(itr);
11334 else
11335 ++itr;
11339 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11341 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11342 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11344 next = itr;
11345 if(itr->slot==slot)
11347 if(itr->item && itr->item->GetEnchantmentId(slot))
11349 // remove from stats
11350 ApplyEnchantment(itr->item,slot,false,false);
11351 // remove visual
11352 itr->item->ClearEnchantment(slot);
11354 // remove from update list
11355 next = m_enchantDuration.erase(itr);
11357 else
11358 ++next;
11361 // remove enchants from inventory items
11362 // NOTE: no need to remove these from stats, since these aren't equipped
11363 // in inventory
11364 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11366 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11367 if( pItem && pItem->GetEnchantmentId(slot) )
11368 pItem->ClearEnchantment(slot);
11371 // in inventory bags
11372 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11374 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11375 if( pBag )
11377 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11379 Item* pItem = pBag->GetItemByPos(j);
11380 if( pItem && pItem->GetEnchantmentId(slot) )
11381 pItem->ClearEnchantment(slot);
11387 // duration == 0 will remove item enchant
11388 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11390 if(!item)
11391 return;
11393 if(slot >= MAX_ENCHANTMENT_SLOT)
11394 return;
11396 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11398 if(itr->item == item && itr->slot == slot)
11400 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11401 m_enchantDuration.erase(itr);
11402 break;
11405 if(item && duration > 0 )
11407 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11408 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11412 void Player::ApplyEnchantment(Item *item,bool apply)
11414 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11415 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11418 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11420 if(!item)
11421 return;
11423 if(!item->IsEquipped())
11424 return;
11426 if(slot >= MAX_ENCHANTMENT_SLOT)
11427 return;
11429 uint32 enchant_id = item->GetEnchantmentId(slot);
11430 if(!enchant_id)
11431 return;
11433 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11434 if(!pEnchant)
11435 return;
11437 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11438 return;
11440 for (int s=0; s<3; s++)
11442 uint32 enchant_display_type = pEnchant->type[s];
11443 uint32 enchant_amount = pEnchant->amount[s];
11444 uint32 enchant_spell_id = pEnchant->spellid[s];
11446 switch(enchant_display_type)
11448 case ITEM_ENCHANTMENT_TYPE_NONE:
11449 break;
11450 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11451 // processed in Player::CastItemCombatSpell
11452 break;
11453 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11454 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11455 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11456 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11457 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11458 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11459 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11460 break;
11461 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11462 if(enchant_spell_id)
11464 if(apply)
11466 int32 basepoints = 0;
11467 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11468 if (item->GetItemRandomPropertyId())
11470 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11471 if (item_rand)
11473 // Search enchant_amount
11474 for (int k=0; k<3; k++)
11476 if(item_rand->enchant_id[k] == enchant_id)
11478 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11479 break;
11484 // Cast custom spell vs all equal basepoints getted from enchant_amount
11485 if (basepoints)
11486 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11487 else
11488 CastSpell(this,enchant_spell_id,true,item);
11490 else
11491 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11493 break;
11494 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11495 if (!enchant_amount)
11497 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11498 if(item_rand)
11500 for (int k=0; k<3; k++)
11502 if(item_rand->enchant_id[k] == enchant_id)
11504 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11505 break;
11511 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11512 break;
11513 case ITEM_ENCHANTMENT_TYPE_STAT:
11515 if (!enchant_amount)
11517 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11518 if(item_rand_suffix)
11520 for (int k=0; k<3; k++)
11522 if(item_rand_suffix->enchant_id[k] == enchant_id)
11524 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11525 break;
11531 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11532 switch (enchant_spell_id)
11534 case ITEM_MOD_AGILITY:
11535 sLog.outDebug("+ %u AGILITY",enchant_amount);
11536 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11537 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11538 break;
11539 case ITEM_MOD_STRENGTH:
11540 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11541 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11542 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11543 break;
11544 case ITEM_MOD_INTELLECT:
11545 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11546 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11547 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11548 break;
11549 case ITEM_MOD_SPIRIT:
11550 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11551 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11552 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11553 break;
11554 case ITEM_MOD_STAMINA:
11555 sLog.outDebug("+ %u STAMINA",enchant_amount);
11556 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11557 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11558 break;
11559 case ITEM_MOD_DEFENSE_SKILL_RATING:
11560 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11561 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11562 break;
11563 case ITEM_MOD_DODGE_RATING:
11564 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11565 sLog.outDebug("+ %u DODGE", enchant_amount);
11566 break;
11567 case ITEM_MOD_PARRY_RATING:
11568 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11569 sLog.outDebug("+ %u PARRY", enchant_amount);
11570 break;
11571 case ITEM_MOD_BLOCK_RATING:
11572 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11573 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11574 break;
11575 case ITEM_MOD_HIT_MELEE_RATING:
11576 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11577 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11578 break;
11579 case ITEM_MOD_HIT_RANGED_RATING:
11580 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11581 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11582 break;
11583 case ITEM_MOD_HIT_SPELL_RATING:
11584 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11585 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11586 break;
11587 case ITEM_MOD_CRIT_MELEE_RATING:
11588 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11589 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11590 break;
11591 case ITEM_MOD_CRIT_RANGED_RATING:
11592 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11593 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11594 break;
11595 case ITEM_MOD_CRIT_SPELL_RATING:
11596 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11597 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11598 break;
11599 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11600 // in Enchantments
11601 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11602 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11603 // break;
11604 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11605 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11606 // break;
11607 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11608 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11609 // break;
11610 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11611 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11612 // break;
11613 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11614 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11615 // break;
11616 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11617 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11618 // break;
11619 // case ITEM_MOD_HASTE_MELEE_RATING:
11620 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11621 // break;
11622 // case ITEM_MOD_HASTE_RANGED_RATING:
11623 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11624 // break;
11625 case ITEM_MOD_HASTE_SPELL_RATING:
11626 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11627 break;
11628 case ITEM_MOD_HIT_RATING:
11629 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11630 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11631 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11632 sLog.outDebug("+ %u HIT", enchant_amount);
11633 break;
11634 case ITEM_MOD_CRIT_RATING:
11635 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11636 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11637 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11638 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11639 break;
11640 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11641 // case ITEM_MOD_HIT_TAKEN_RATING:
11642 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11643 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11644 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11645 // break;
11646 // case ITEM_MOD_CRIT_TAKEN_RATING:
11647 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11648 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11649 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11650 // break;
11651 case ITEM_MOD_RESILIENCE_RATING:
11652 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11653 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11654 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11655 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11656 break;
11657 case ITEM_MOD_HASTE_RATING:
11658 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11659 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11660 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11661 sLog.outDebug("+ %u HASTE", enchant_amount);
11662 break;
11663 case ITEM_MOD_EXPERTISE_RATING:
11664 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11665 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11666 break;
11667 case ITEM_MOD_ATTACK_POWER:
11668 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11669 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11670 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11671 break;
11672 case ITEM_MOD_RANGED_ATTACK_POWER:
11673 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11674 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11675 break;
11676 case ITEM_MOD_FERAL_ATTACK_POWER:
11677 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11678 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11679 break;
11680 case ITEM_MOD_SPELL_HEALING_DONE:
11681 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11682 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
11683 break;
11684 case ITEM_MOD_SPELL_DAMAGE_DONE:
11685 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11686 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
11687 break;
11688 case ITEM_MOD_MANA_REGENERATION:
11689 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
11690 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
11691 break;
11692 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11693 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11694 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11695 break;
11696 case ITEM_MOD_SPELL_POWER:
11697 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11698 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11699 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
11700 break;
11701 default:
11702 break;
11704 break;
11706 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11708 if(getClass() == CLASS_SHAMAN)
11710 float addValue = 0.0f;
11711 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11713 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11714 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11716 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11718 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11719 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11722 break;
11724 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
11725 // processed in Player::CastItemUseSpell
11726 break;
11727 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
11728 // nothing do..
11729 break;
11730 default:
11731 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
11732 break;
11733 } /*switch(enchant_display_type)*/
11734 } /*for*/
11736 // visualize enchantment at player and equipped items
11737 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11739 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11740 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11743 if(apply_dur)
11745 if(apply)
11747 // set duration
11748 uint32 duration = item->GetEnchantmentDuration(slot);
11749 if(duration > 0)
11750 AddEnchantmentDuration(item,slot,duration);
11752 else
11754 // duration == 0 will remove EnchantDuration
11755 AddEnchantmentDuration(item,slot,0);
11760 void Player::SendEnchantmentDurations()
11762 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11764 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11768 void Player::SendItemDurations()
11770 for(ItemDurationList::const_iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11772 (*itr)->SendTimeUpdate(this);
11776 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11778 if(!item) // prevent crash
11779 return;
11781 // last check 2.0.10
11782 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11783 data << GetGUID(); // player GUID
11784 data << uint32(received); // 0=looted, 1=from npc
11785 data << uint32(created); // 0=received, 1=created
11786 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11787 data << (uint8)item->GetBagSlot(); // bagslot
11788 // item slot, but when added to stack: 0xFFFFFFFF
11789 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11790 data << uint32(item->GetEntry()); // item id
11791 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11792 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11793 data << uint32(count); // count of items
11794 data << GetItemCount(item->GetEntry()); // count of items in inventory
11796 if (broadcast && GetGroup())
11797 GetGroup()->BroadcastPacket(&data, true);
11798 else
11799 GetSession()->SendPacket(&data);
11802 /*********************************************************/
11803 /*** QUEST SYSTEM ***/
11804 /*********************************************************/
11806 void Player::PrepareQuestMenu( uint64 guid )
11808 Object *pObject;
11809 QuestRelations* pObjectQR;
11810 QuestRelations* pObjectQIR;
11811 Creature *pCreature = GetMap()->GetCreature(guid);
11812 if( pCreature )
11814 pObject = (Object*)pCreature;
11815 pObjectQR = &objmgr.mCreatureQuestRelations;
11816 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11818 else
11820 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11821 if( pGameObject )
11823 pObject = (Object*)pGameObject;
11824 pObjectQR = &objmgr.mGOQuestRelations;
11825 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11827 else
11828 return;
11831 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11832 qm.ClearMenu();
11834 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11836 uint32 quest_id = i->second;
11837 QuestStatus status = GetQuestStatus( quest_id );
11838 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11839 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11840 else if ( status == QUEST_STATUS_INCOMPLETE )
11841 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11842 else if (status == QUEST_STATUS_AVAILABLE )
11843 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11846 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11848 uint32 quest_id = i->second;
11849 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11850 if(!pQuest) continue;
11852 QuestStatus status = GetQuestStatus( quest_id );
11854 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11855 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11856 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11857 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
11861 void Player::SendPreparedQuest( uint64 guid )
11863 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11864 if( questMenu.Empty() )
11865 return;
11867 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11869 uint32 status = qmi0.m_qIcon;
11871 // single element case
11872 if ( questMenu.MenuItemCount() == 1 )
11874 // Auto open -- maybe also should verify there is no greeting
11875 uint32 quest_id = qmi0.m_qId;
11876 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11877 if ( pQuest )
11879 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
11880 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
11881 else if( status == DIALOG_STATUS_INCOMPLETE )
11882 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
11883 // Send completable on repeatable quest if player don't have quest
11884 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
11885 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11886 else
11887 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11890 // multiply entries
11891 else
11893 QEmote qe;
11894 qe._Delay = 0;
11895 qe._Emote = 0;
11896 std::string title = "";
11897 Creature *pCreature = GetMap()->GetCreature(guid);
11898 if( pCreature )
11900 uint32 textid = pCreature->GetNpcTextId();
11901 GossipText const* gossiptext = objmgr.GetGossipText(textid);
11902 if( !gossiptext )
11904 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11905 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11906 title = "";
11908 else
11910 qe = gossiptext->Options[0].Emotes[0];
11912 if(!gossiptext->Options[0].Text_0.empty())
11914 title = gossiptext->Options[0].Text_0;
11916 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11917 if (loc_idx >= 0)
11919 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11920 if (nl)
11922 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
11923 title = nl->Text_0[0][loc_idx];
11927 else
11929 title = gossiptext->Options[0].Text_1;
11931 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11932 if (loc_idx >= 0)
11934 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11935 if (nl)
11937 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
11938 title = nl->Text_1[0][loc_idx];
11944 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
11948 bool Player::IsActiveQuest( uint32 quest_id ) const
11950 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
11952 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
11955 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
11957 Object *pObject;
11958 QuestRelations* pObjectQR;
11959 QuestRelations* pObjectQIR;
11961 Creature *pCreature = GetMap()->GetCreature(guid);
11962 if( pCreature )
11964 pObject = (Object*)pCreature;
11965 pObjectQR = &objmgr.mCreatureQuestRelations;
11966 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11968 else
11970 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11971 if( pGameObject )
11973 pObject = (Object*)pGameObject;
11974 pObjectQR = &objmgr.mGOQuestRelations;
11975 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11977 else
11978 return NULL;
11981 uint32 nextQuestID = pQuest->GetNextQuestInChain();
11982 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
11984 if (itr->second == nextQuestID)
11985 return objmgr.GetQuestTemplate(nextQuestID);
11988 return NULL;
11991 bool Player::CanSeeStartQuest( Quest const *pQuest )
11993 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
11994 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
11995 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
11996 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
11998 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12001 return false;
12004 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12006 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12007 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12008 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12009 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12010 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12011 && SatisfyQuestDay( pQuest, msg );
12014 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12016 if( !SatisfyQuestLog( msg ) )
12017 return false;
12019 uint32 srcitem = pQuest->GetSrcItemId();
12020 if( srcitem > 0 )
12022 uint32 count = pQuest->GetSrcItemCount();
12023 ItemPosCountVec dest;
12024 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12026 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12027 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12028 return true;
12029 else if( msg2 != EQUIP_ERR_OK )
12031 SendEquipError( msg2, NULL, NULL );
12032 return false;
12035 return true;
12038 bool Player::CanCompleteQuest( uint32 quest_id )
12040 if( quest_id )
12042 QuestStatusData& q_status = mQuestStatus[quest_id];
12043 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12044 return false; // not allow re-complete quest
12046 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12048 if(!qInfo)
12049 return false;
12051 // auto complete quest
12052 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12053 return true;
12055 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12058 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12060 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12062 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12063 return false;
12067 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12069 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12071 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12072 continue;
12074 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12075 return false;
12079 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12080 return false;
12082 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12083 return false;
12085 if ( qInfo->GetRewOrReqMoney() < 0 )
12087 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12088 return false;
12091 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12092 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12093 return false;
12095 return true;
12098 return false;
12101 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12103 // Solve problem that player don't have the quest and try complete it.
12104 // if repeatable she must be able to complete event if player don't have it.
12105 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12106 if( !CanTakeQuest(pQuest, false) )
12107 return false;
12109 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12110 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12111 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12112 return false;
12114 if( !CanRewardQuest(pQuest, false) )
12115 return false;
12117 return true;
12120 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12122 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12123 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12124 return false;
12126 // daily quest can't be rewarded (25 daily quest already completed)
12127 if(!SatisfyQuestDay(pQuest,true))
12128 return false;
12130 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12131 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12132 return false;
12134 // prevent receive reward with quest items in bank
12135 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12137 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12139 if( pQuest->ReqItemCount[i]!= 0 &&
12140 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12142 if(msg)
12143 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12144 return false;
12149 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12150 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12151 return false;
12153 return true;
12156 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12158 // prevent receive reward with quest items in bank or for not completed quest
12159 if(!CanRewardQuest(pQuest,msg))
12160 return false;
12162 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12164 if( pQuest->RewChoiceItemId[reward] )
12166 ItemPosCountVec dest;
12167 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12168 if( res != EQUIP_ERR_OK )
12170 SendEquipError( res, NULL, NULL );
12171 return false;
12176 if ( pQuest->GetRewItemsCount() > 0 )
12178 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12180 if( pQuest->RewItemId[i] )
12182 ItemPosCountVec dest;
12183 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12184 if( res != EQUIP_ERR_OK )
12186 SendEquipError( res, NULL, NULL );
12187 return false;
12193 return true;
12196 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12198 uint16 log_slot = FindQuestSlot( 0 );
12199 assert(log_slot < MAX_QUEST_LOG_SIZE);
12201 uint32 quest_id = pQuest->GetQuestId();
12203 // if not exist then created with set uState==NEW and rewarded=false
12204 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12206 // check for repeatable quests status reset
12207 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12208 questStatusData.m_explored = false;
12210 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12212 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12213 questStatusData.m_itemcount[i] = 0;
12216 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12218 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12219 questStatusData.m_creatureOrGOcount[i] = 0;
12222 GiveQuestSourceItem( pQuest );
12223 AdjustQuestReqItemCount( pQuest, questStatusData );
12225 if( pQuest->GetRepObjectiveFaction() )
12226 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12227 GetReputationMgr().SetVisible(factionEntry);
12229 uint32 qtime = 0;
12230 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12232 uint32 limittime = pQuest->GetLimitTime();
12234 // shared timed quest
12235 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12236 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12238 AddTimedQuest( quest_id );
12239 questStatusData.m_timer = limittime * IN_MILISECONDS;
12240 qtime = static_cast<uint32>(time(NULL)) + limittime;
12242 else
12243 questStatusData.m_timer = 0;
12245 SetQuestSlot(log_slot, quest_id, qtime);
12247 if (questStatusData.uState != QUEST_NEW)
12248 questStatusData.uState = QUEST_CHANGED;
12250 //starting initial quest script
12251 if(questGiver && pQuest->GetQuestStartScript()!=0)
12252 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12254 // Some spells applied at quest activation
12255 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12256 if(saBounds.first != saBounds.second)
12258 uint32 zone, area;
12259 GetZoneAndAreaId(zone,area);
12261 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12262 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12263 if( !HasAura(itr->second->spellId,0) )
12264 CastSpell(this,itr->second->spellId,true);
12267 UpdateForQuestsGO();
12270 void Player::CompleteQuest( uint32 quest_id )
12272 if( quest_id )
12274 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12276 uint16 log_slot = FindQuestSlot( quest_id );
12277 if( log_slot < MAX_QUEST_LOG_SIZE)
12278 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12280 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12282 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12283 RewardQuest(qInfo,0,this,false);
12284 else
12285 SendQuestComplete( quest_id );
12290 void Player::IncompleteQuest( uint32 quest_id )
12292 if( quest_id )
12294 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12296 uint16 log_slot = FindQuestSlot( quest_id );
12297 if( log_slot < MAX_QUEST_LOG_SIZE)
12298 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12302 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12304 uint32 quest_id = pQuest->GetQuestId();
12306 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i )
12308 if ( pQuest->ReqItemId[i] )
12309 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12312 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12313 // SetTimedQuest( 0 );
12314 m_timedquests.erase(pQuest->GetQuestId());
12316 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12318 if( pQuest->RewChoiceItemId[reward] )
12320 ItemPosCountVec dest;
12321 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12323 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12324 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12329 if ( pQuest->GetRewItemsCount() > 0 )
12331 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12333 if( pQuest->RewItemId[i] )
12335 ItemPosCountVec dest;
12336 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12338 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12339 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12345 RewardReputation( pQuest );
12347 if( pQuest->GetRewSpellCast() > 0 )
12348 CastSpell( this, pQuest->GetRewSpellCast(), true);
12349 else if( pQuest->GetRewSpell() > 0)
12350 CastSpell( this, pQuest->GetRewSpell(), true);
12352 uint16 log_slot = FindQuestSlot( quest_id );
12353 if( log_slot < MAX_QUEST_LOG_SIZE)
12354 SetQuestSlot(log_slot,0);
12356 QuestStatusData& q_status = mQuestStatus[quest_id];
12358 // Not give XP in case already completed once repeatable quest
12359 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12361 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12362 GiveXP( XP , NULL );
12363 else
12365 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12366 ModifyMoney( money );
12367 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12370 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12371 if(pQuest->GetRewOrReqMoney())
12373 ModifyMoney( pQuest->GetRewOrReqMoney() );
12375 if(pQuest->GetRewOrReqMoney() > 0)
12376 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12379 // honor reward
12380 if(pQuest->GetRewHonorableKills())
12381 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12383 // title reward
12384 if(pQuest->GetCharTitleId())
12386 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12387 SetTitle(titleEntry);
12390 if(pQuest->GetBonusTalents())
12392 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12393 InitTalentForLevel();
12396 // Send reward mail
12397 if(pQuest->GetRewMailTemplateId())
12399 MailMessageType mailType;
12400 uint32 senderGuidOrEntry;
12401 switch(questGiver->GetTypeId())
12403 case TYPEID_UNIT:
12404 mailType = MAIL_CREATURE;
12405 senderGuidOrEntry = questGiver->GetEntry();
12406 break;
12407 case TYPEID_GAMEOBJECT:
12408 mailType = MAIL_GAMEOBJECT;
12409 senderGuidOrEntry = questGiver->GetEntry();
12410 break;
12411 case TYPEID_ITEM:
12412 mailType = MAIL_ITEM;
12413 senderGuidOrEntry = questGiver->GetEntry();
12414 break;
12415 case TYPEID_PLAYER:
12416 mailType = MAIL_NORMAL;
12417 senderGuidOrEntry = questGiver->GetGUIDLow();
12418 break;
12419 default:
12420 mailType = MAIL_NORMAL;
12421 senderGuidOrEntry = GetGUIDLow();
12422 break;
12425 Loot questMailLoot;
12427 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12429 // fill mail
12430 MailItemsInfo mi; // item list preparing
12432 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12433 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12435 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12437 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12439 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12440 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12445 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12448 if(pQuest->IsDaily())
12450 SetDailyQuestStatus(quest_id);
12451 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12454 if ( !pQuest->IsRepeatable() )
12455 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12456 else
12457 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12459 q_status.m_rewarded = true;
12461 if(announce)
12462 SendQuestReward( pQuest, XP, questGiver );
12464 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12465 if (pQuest->GetZoneOrSort() > 0)
12466 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12467 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12468 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
12470 uint32 zone = 0;
12471 uint32 area = 0;
12473 // remove auras from spells with quest reward state limitations
12474 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12475 if(saEndBounds.first != saEndBounds.second)
12477 GetZoneAndAreaId(zone,area);
12479 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12480 if(!itr->second->IsFitToRequirements(this,zone,area))
12481 RemoveAurasDueToSpell(itr->second->spellId);
12484 // Some spells applied at quest reward
12485 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12486 if(saBounds.first != saBounds.second)
12488 if(!zone || !area)
12489 GetZoneAndAreaId(zone,area);
12491 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12492 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12493 if( !HasAura(itr->second->spellId,0) )
12494 CastSpell(this,itr->second->spellId,true);
12498 void Player::FailQuest( uint32 quest_id )
12500 if( quest_id )
12502 IncompleteQuest( quest_id );
12504 uint16 log_slot = FindQuestSlot( quest_id );
12505 if( log_slot < MAX_QUEST_LOG_SIZE)
12507 SetQuestSlotTimer(log_slot, 1 );
12508 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12510 SendQuestFailed( quest_id );
12514 void Player::FailTimedQuest( uint32 quest_id )
12516 if( quest_id )
12518 QuestStatusData& q_status = mQuestStatus[quest_id];
12520 q_status.m_timer = 0;
12521 if (q_status.uState != QUEST_NEW)
12522 q_status.uState = QUEST_CHANGED;
12524 IncompleteQuest( quest_id );
12526 uint16 log_slot = FindQuestSlot( quest_id );
12527 if( log_slot < MAX_QUEST_LOG_SIZE)
12529 SetQuestSlotTimer(log_slot, 1 );
12530 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12532 SendQuestTimerFailed( quest_id );
12536 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12538 int32 zoneOrSort = qInfo->GetZoneOrSort();
12539 int32 skillOrClass = qInfo->GetSkillOrClass();
12541 // skip zone zoneOrSort and 0 case skillOrClass
12542 if( zoneOrSort >= 0 && skillOrClass == 0 )
12543 return true;
12545 int32 questSort = -zoneOrSort;
12546 uint8 reqSortClass = ClassByQuestSort(questSort);
12548 // check class sort cases in zoneOrSort
12549 if( reqSortClass != 0 && getClass() != reqSortClass)
12551 if( msg )
12552 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12553 return false;
12556 // check class
12557 if( skillOrClass < 0 )
12559 uint8 reqClass = -int32(skillOrClass);
12560 if(getClass() != reqClass)
12562 if( msg )
12563 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12564 return false;
12567 // check skill
12568 else if( skillOrClass > 0 )
12570 uint32 reqSkill = skillOrClass;
12571 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12573 if( msg )
12574 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12575 return false;
12579 return true;
12582 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12584 if( getLevel() < qInfo->GetMinLevel() )
12586 if( msg )
12587 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12588 return false;
12590 return true;
12593 bool Player::SatisfyQuestLog( bool msg )
12595 // exist free slot
12596 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12597 return true;
12599 if( msg )
12601 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12602 GetSession()->SendPacket( &data );
12603 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12605 return false;
12608 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12610 // No previous quest (might be first quest in a series)
12611 if( qInfo->prevQuests.empty())
12612 return true;
12614 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12616 uint32 prevId = abs(*iter);
12618 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12619 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12621 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12623 // If any of the positive previous quests completed, return true
12624 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12626 // skip one-from-all exclusive group
12627 if(qPrevInfo->GetExclusiveGroup() >= 0)
12628 return true;
12630 // each-from-all exclusive group ( < 0)
12631 // can be start if only all quests in prev quest exclusive group completed and rewarded
12632 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12633 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12635 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12637 for(; iter2 != end; ++iter2)
12639 uint32 exclude_Id = iter2->second;
12641 // skip checked quest id, only state of other quests in group is interesting
12642 if(exclude_Id == prevId)
12643 continue;
12645 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12647 // alternative quest from group also must be completed and rewarded(reported)
12648 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12650 if( msg )
12651 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12652 return false;
12655 return true;
12657 // If any of the negative previous quests active, return true
12658 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12659 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12661 // skip one-from-all exclusive group
12662 if(qPrevInfo->GetExclusiveGroup() >= 0)
12663 return true;
12665 // each-from-all exclusive group ( < 0)
12666 // can be start if only all quests in prev quest exclusive group active
12667 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12668 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12670 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12672 for(; iter2 != end; ++iter2)
12674 uint32 exclude_Id = iter2->second;
12676 // skip checked quest id, only state of other quests in group is interesting
12677 if(exclude_Id == prevId)
12678 continue;
12680 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12682 // alternative quest from group also must be active
12683 if( i_exstatus == mQuestStatus.end() ||
12684 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12685 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12687 if( msg )
12688 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12689 return false;
12692 return true;
12697 // Has only positive prev. quests in non-rewarded state
12698 // and negative prev. quests in non-active state
12699 if( msg )
12700 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12702 return false;
12705 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12707 uint32 reqraces = qInfo->GetRequiredRaces();
12708 if ( reqraces == 0 )
12709 return true;
12710 if( (reqraces & getRaceMask()) == 0 )
12712 if( msg )
12713 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12714 return false;
12716 return true;
12719 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12721 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12722 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12724 if( msg )
12725 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12726 return false;
12729 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12730 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12732 if( msg )
12733 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12734 return false;
12737 return true;
12740 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12742 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12743 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12745 if( msg )
12746 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12747 return false;
12749 return true;
12752 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12754 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12756 if( msg )
12757 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12758 return false;
12760 return true;
12763 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12765 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12766 if(qInfo->GetExclusiveGroup() <= 0)
12767 return true;
12769 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12770 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12772 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12774 for(; iter != end; ++iter)
12776 uint32 exclude_Id = iter->second;
12778 // skip checked quest id, only state of other quests in group is interesting
12779 if(exclude_Id == qInfo->GetQuestId())
12780 continue;
12782 // not allow have daily quest if daily quest from exclusive group already recently completed
12783 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12784 if( !SatisfyQuestDay(Nquest, false) )
12786 if( msg )
12787 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12788 return false;
12791 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12793 // alternative quest already started or completed
12794 if( i_exstatus != mQuestStatus.end()
12795 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12797 if( msg )
12798 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12799 return false;
12802 return true;
12805 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12807 if(!qInfo->GetNextQuestInChain())
12808 return true;
12810 // next quest in chain already started or completed
12811 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12812 if( itr != mQuestStatus.end()
12813 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12815 if( msg )
12816 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12817 return false;
12820 // check for all quests further up the chain
12821 // only necessary if there are quest chains with more than one quest that can be skipped
12822 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12823 return true;
12826 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12828 // No previous quest in chain
12829 if( qInfo->prevChainQuests.empty())
12830 return true;
12832 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12834 uint32 prevId = *iter;
12836 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12838 if( i_prevstatus != mQuestStatus.end() )
12840 // If any of the previous quests in chain active, return false
12841 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12842 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12844 if( msg )
12845 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12846 return false;
12850 // check for all quests further down the chain
12851 // only necessary if there are quest chains with more than one quest that can be skipped
12852 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12853 // return false;
12856 // No previous quest in chain active
12857 return true;
12860 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12862 if(!qInfo->IsDaily())
12863 return true;
12865 bool have_slot = false;
12866 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12868 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12869 if(qInfo->GetQuestId()==id)
12870 return false;
12872 if(!id)
12873 have_slot = true;
12876 if(!have_slot)
12878 if( msg )
12879 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12880 return false;
12883 return true;
12886 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12888 uint32 srcitem = pQuest->GetSrcItemId();
12889 if( srcitem > 0 )
12891 uint32 count = pQuest->GetSrcItemCount();
12892 if( count <= 0 )
12893 count = 1;
12895 ItemPosCountVec dest;
12896 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12897 if( msg == EQUIP_ERR_OK )
12899 Item * item = StoreNewItem(dest, srcitem, true);
12900 SendNewItem(item, count, true, false);
12901 return true;
12903 // player already have max amount required item, just report success
12904 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12905 return true;
12906 else
12907 SendEquipError( msg, NULL, NULL );
12908 return false;
12911 return true;
12914 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12916 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12917 if( qInfo )
12919 uint32 srcitem = qInfo->GetSrcItemId();
12920 if( srcitem > 0 )
12922 uint32 count = qInfo->GetSrcItemCount();
12923 if( count <= 0 )
12924 count = 1;
12926 // exist one case when destroy source quest item not possible:
12927 // non un-equippable item (equipped non-empty bag, for example)
12928 uint8 res = CanUnequipItems(srcitem,count);
12929 if(res != EQUIP_ERR_OK)
12931 if(msg)
12932 SendEquipError( res, NULL, NULL );
12933 return false;
12936 DestroyItemCount(srcitem, count, true, true);
12939 return true;
12942 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12944 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12945 if( qInfo )
12947 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12948 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12949 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12950 && !qInfo->IsRepeatable() )
12951 return itr->second.m_rewarded;
12953 return false;
12955 return false;
12958 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
12960 if( quest_id )
12962 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12963 if( itr != mQuestStatus.end() )
12964 return itr->second.m_status;
12966 return QUEST_STATUS_NONE;
12969 bool Player::CanShareQuest(uint32 quest_id) const
12971 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12972 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
12974 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12975 if( itr != mQuestStatus.end() )
12976 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
12978 return false;
12981 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
12983 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12984 if( qInfo )
12986 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
12988 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12989 m_timedquests.erase(qInfo->GetQuestId());
12992 QuestStatusData& q_status = mQuestStatus[quest_id];
12994 q_status.m_status = status;
12995 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12998 UpdateForQuestsGO();
13001 // not used in MaNGOS, but used in scripting code
13002 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13004 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13005 if( !qInfo )
13006 return 0;
13008 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13009 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13010 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13012 return 0;
13015 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13017 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13019 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13021 uint32 reqitemcount = pQuest->ReqItemCount[i];
13022 if( reqitemcount != 0 )
13024 uint32 quest_id = pQuest->GetQuestId();
13025 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13027 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13028 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13034 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13036 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13037 if ( GetQuestSlotQuestId(i) == quest_id )
13038 return i;
13040 return MAX_QUEST_LOG_SIZE;
13043 void Player::AreaExploredOrEventHappens( uint32 questId )
13045 if( questId )
13047 uint16 log_slot = FindQuestSlot( questId );
13048 if( log_slot < MAX_QUEST_LOG_SIZE)
13050 QuestStatusData& q_status = mQuestStatus[questId];
13052 if(!q_status.m_explored)
13054 q_status.m_explored = true;
13055 if (q_status.uState != QUEST_NEW)
13056 q_status.uState = QUEST_CHANGED;
13059 if( CanCompleteQuest( questId ) )
13060 CompleteQuest( questId );
13064 //not used in mangosd, function for external script library
13065 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13067 if( Group *pGroup = GetGroup() )
13069 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13071 Player *pGroupGuy = itr->getSource();
13073 // for any leave or dead (with not released body) group member at appropriate distance
13074 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13075 pGroupGuy->AreaExploredOrEventHappens(questId);
13078 else
13079 AreaExploredOrEventHappens(questId);
13082 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13084 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13086 uint32 questid = GetQuestSlotQuestId(i);
13087 if ( questid == 0 )
13088 continue;
13090 QuestStatusData& q_status = mQuestStatus[questid];
13092 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13093 continue;
13095 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13096 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13097 continue;
13099 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13101 uint32 reqitem = qInfo->ReqItemId[j];
13102 if ( reqitem == entry )
13104 uint32 reqitemcount = qInfo->ReqItemCount[j];
13105 uint32 curitemcount = q_status.m_itemcount[j];
13106 if ( curitemcount < reqitemcount )
13108 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13109 q_status.m_itemcount[j] += additemcount;
13110 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13112 SendQuestUpdateAddItem( qInfo, j, additemcount );
13114 if ( CanCompleteQuest( questid ) )
13115 CompleteQuest( questid );
13116 return;
13120 UpdateForQuestsGO();
13123 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13125 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13127 uint32 questid = GetQuestSlotQuestId(i);
13128 if(!questid)
13129 continue;
13130 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13131 if ( !qInfo )
13132 continue;
13133 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13134 continue;
13136 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13138 uint32 reqitem = qInfo->ReqItemId[j];
13139 if ( reqitem == entry )
13141 QuestStatusData& q_status = mQuestStatus[questid];
13143 uint32 reqitemcount = qInfo->ReqItemCount[j];
13144 uint32 curitemcount;
13145 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13146 curitemcount = q_status.m_itemcount[j];
13147 else
13148 curitemcount = GetItemCount(entry,true);
13149 if ( curitemcount < reqitemcount + count )
13151 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13152 q_status.m_itemcount[j] = curitemcount - remitemcount;
13153 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13155 IncompleteQuest( questid );
13157 return;
13161 UpdateForQuestsGO();
13164 void Player::KilledMonster( uint32 entry, uint64 guid )
13166 uint32 addkillcount = 1;
13167 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13168 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13170 uint32 questid = GetQuestSlotQuestId(i);
13171 if(!questid)
13172 continue;
13174 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13175 if( !qInfo )
13176 continue;
13177 // just if !ingroup || !noraidgroup || raidgroup
13178 QuestStatusData& q_status = mQuestStatus[questid];
13179 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13181 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13183 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13185 // skip GO activate objective or none
13186 if(qInfo->ReqCreatureOrGOId[j] <=0)
13187 continue;
13189 // skip Cast at creature objective
13190 if(qInfo->ReqSpell[j] !=0 )
13191 continue;
13193 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13195 if ( reqkill == entry )
13197 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13198 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13199 if ( curkillcount < reqkillcount )
13201 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13202 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13204 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13206 if ( CanCompleteQuest( questid ) )
13207 CompleteQuest( questid );
13209 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13210 continue;
13218 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13220 bool isCreature = IS_CREATURE_GUID(guid);
13222 uint32 addCastCount = 1;
13223 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13225 uint32 questid = GetQuestSlotQuestId(i);
13226 if(!questid)
13227 continue;
13229 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13230 if ( !qInfo )
13231 continue;
13233 QuestStatusData& q_status = mQuestStatus[questid];
13235 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13237 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13239 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13241 // skip kill creature objective (0) or wrong spell casts
13242 if(qInfo->ReqSpell[j] != spell_id )
13243 continue;
13245 uint32 reqTarget = 0;
13247 if(isCreature)
13249 // creature activate objectives
13250 if(qInfo->ReqCreatureOrGOId[j] > 0)
13251 // checked at quest_template loading
13252 reqTarget = qInfo->ReqCreatureOrGOId[j];
13254 else
13256 // GO activate objective
13257 if(qInfo->ReqCreatureOrGOId[j] < 0)
13258 // checked at quest_template loading
13259 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13262 // other not this creature/GO related objectives
13263 if( reqTarget != entry )
13264 continue;
13266 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13267 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13268 if ( curCastCount < reqCastCount )
13270 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13271 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13273 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13276 if ( CanCompleteQuest( questid ) )
13277 CompleteQuest( questid );
13279 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13280 break;
13287 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13289 uint32 addTalkCount = 1;
13290 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13292 uint32 questid = GetQuestSlotQuestId(i);
13293 if(!questid)
13294 continue;
13296 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13297 if ( !qInfo )
13298 continue;
13300 QuestStatusData& q_status = mQuestStatus[questid];
13302 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13304 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13306 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13308 // skip spell casts and Gameobject objectives
13309 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13310 continue;
13312 uint32 reqTarget = 0;
13314 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13315 // checked at quest_template loading
13316 reqTarget = qInfo->ReqCreatureOrGOId[j];
13317 else
13318 continue;
13320 if ( reqTarget == entry )
13322 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13323 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13324 if ( curTalkCount < reqTalkCount )
13326 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13327 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13329 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13331 if ( CanCompleteQuest( questid ) )
13332 CompleteQuest( questid );
13334 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13335 continue;
13343 void Player::MoneyChanged( uint32 count )
13345 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13347 uint32 questid = GetQuestSlotQuestId(i);
13348 if (!questid)
13349 continue;
13351 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13352 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13354 QuestStatusData& q_status = mQuestStatus[questid];
13356 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13358 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13360 if ( CanCompleteQuest( questid ) )
13361 CompleteQuest( questid );
13364 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13366 if(int32(count) < -qInfo->GetRewOrReqMoney())
13367 IncompleteQuest( questid );
13373 void Player::ReputationChanged(FactionEntry const* factionEntry )
13375 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13377 if(uint32 questid = GetQuestSlotQuestId(i))
13379 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13381 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13383 QuestStatusData& q_status = mQuestStatus[questid];
13384 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13386 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13387 if ( CanCompleteQuest( questid ) )
13388 CompleteQuest( questid );
13390 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13392 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13393 IncompleteQuest( questid );
13401 bool Player::HasQuestForItem( uint32 itemid ) const
13403 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13405 uint32 questid = GetQuestSlotQuestId(i);
13406 if ( questid == 0 )
13407 continue;
13409 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13410 if(qs_itr == mQuestStatus.end())
13411 continue;
13413 QuestStatusData const& q_status = qs_itr->second;
13415 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13417 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13418 if(!qinfo)
13419 continue;
13421 // hide quest if player is in raid-group and quest is no raid quest
13422 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13423 continue;
13425 // There should be no mixed ReqItem/ReqSource drop
13426 // This part for ReqItem drop
13427 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13429 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13430 return true;
13432 // This part - for ReqSource
13433 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
13435 // examined item is a source item
13436 if (qinfo->ReqSourceId[j] == itemid)
13438 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13440 // 'unique' item
13441 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13442 return true;
13444 // allows custom amount drop when not 0
13445 if (qinfo->ReqSourceCount[j])
13447 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13448 return true;
13449 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13450 return true;
13455 return false;
13458 void Player::SendQuestComplete( uint32 quest_id )
13460 if( quest_id )
13462 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13463 data << uint32(quest_id);
13464 GetSession()->SendPacket( &data );
13465 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13469 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13471 uint32 questid = pQuest->GetQuestId();
13472 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13473 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13474 data << uint32(questid);
13476 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13478 data << uint32(XP);
13479 data << uint32(pQuest->GetRewOrReqMoney());
13481 else
13483 data << uint32(0);
13484 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13487 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13488 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13489 GetSession()->SendPacket( &data );
13491 if (pQuest->GetQuestCompleteScript() != 0)
13492 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13495 void Player::SendQuestFailed( uint32 quest_id )
13497 if( quest_id )
13499 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13500 data << quest_id;
13501 data << uint32(0); // failed reason (4 for inventory is full)
13502 GetSession()->SendPacket( &data );
13503 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13507 void Player::SendQuestTimerFailed( uint32 quest_id )
13509 if( quest_id )
13511 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13512 data << quest_id;
13513 GetSession()->SendPacket( &data );
13514 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13518 void Player::SendCanTakeQuestResponse( uint32 msg )
13520 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13521 data << uint32(msg);
13522 GetSession()->SendPacket( &data );
13523 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13526 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13528 if( pPlayer )
13530 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13531 data << uint64(pPlayer->GetGUID());
13532 data << uint8(msg); // valid values: 0-8
13533 GetSession()->SendPacket( &data );
13534 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13538 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13540 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13541 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13542 //data << pQuest->ReqItemId[item_idx];
13543 //data << count;
13544 GetSession()->SendPacket( &data );
13547 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13549 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13551 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13552 if (entry < 0)
13553 // client expected gameobject template id in form (id|0x80000000)
13554 entry = (-entry) | 0x80000000;
13556 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13557 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13558 data << uint32(pQuest->GetQuestId());
13559 data << uint32(entry);
13560 data << uint32(old_count + add_count);
13561 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13562 data << uint64(guid);
13563 GetSession()->SendPacket(&data);
13565 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13566 if( log_slot < MAX_QUEST_LOG_SIZE)
13567 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13570 /*********************************************************/
13571 /*** LOAD SYSTEM ***/
13572 /*********************************************************/
13574 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13576 bool delete_result = true;
13577 if(!result)
13579 // 0 1 2 3 4 5 6 7 8 9
13580 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13581 if(!result) return false;
13583 else delete_result = false;
13585 Field *fields = result->Fetch();
13587 if(!LoadValues( fields[1].GetString()))
13589 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13590 if(delete_result) delete result;
13591 return false;
13594 // overwrite possible wrong/corrupted guid
13595 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13597 m_name = fields[2].GetCppString();
13599 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13600 SetMapId(fields[6].GetUInt32());
13601 // the instance id is not needed at character enum
13603 m_Played_time[0] = fields[7].GetUInt32();
13604 m_Played_time[1] = fields[8].GetUInt32();
13606 m_atLoginFlags = fields[9].GetUInt32();
13608 // I don't see these used anywhere ..
13609 /*_LoadGroup();
13611 _LoadBoundInstances();*/
13613 if (delete_result) delete result;
13615 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
13616 m_items[i] = NULL;
13618 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13619 m_deathState = DEAD;
13621 return true;
13624 void Player::_LoadDeclinedNames(QueryResult* result)
13626 if(!result)
13627 return;
13629 if(m_declinedname)
13630 delete m_declinedname;
13632 m_declinedname = new DeclinedName;
13633 Field *fields = result->Fetch();
13634 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13635 m_declinedname->name[i] = fields[i].GetCppString();
13637 delete result;
13640 void Player::_LoadArenaTeamInfo(QueryResult *result)
13642 // arenateamid, played_week, played_season, personal_rating
13643 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13644 if (!result)
13645 return;
13649 Field *fields = result->Fetch();
13651 uint32 arenateamid = fields[0].GetUInt32();
13652 uint32 played_week = fields[1].GetUInt32();
13653 uint32 played_season = fields[2].GetUInt32();
13654 uint32 personal_rating = fields[3].GetUInt32();
13656 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13657 if(!aTeam)
13659 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13660 continue;
13662 uint8 arenaSlot = aTeam->GetSlot();
13664 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13665 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13666 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13667 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13668 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13669 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13671 }while (result->NextRow());
13672 delete result;
13675 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13677 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13678 if(!result)
13679 return false;
13681 Field *fields = result->Fetch();
13683 x = fields[0].GetFloat();
13684 y = fields[1].GetFloat();
13685 z = fields[2].GetFloat();
13686 o = fields[3].GetFloat();
13687 mapid = fields[4].GetUInt32();
13688 in_flight = !fields[5].GetCppString().empty();
13690 delete result;
13691 return true;
13694 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13696 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13697 if( !result )
13698 return false;
13700 Field *fields = result->Fetch();
13702 data = StrSplit(fields[0].GetCppString(), " ");
13704 delete result;
13706 return true;
13709 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13711 if(index >= data.size())
13712 return 0;
13714 return (uint32)atoi(data[index].c_str());
13717 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13719 float result;
13720 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13721 memcpy(&result, &temp, sizeof(result));
13723 return result;
13726 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13728 Tokens data;
13729 if(!LoadValuesArrayFromDB(data,guid))
13730 return 0;
13732 return GetUInt32ValueFromArray(data,index);
13735 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13737 float result;
13738 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13739 memcpy(&result, &temp, sizeof(result));
13741 return result;
13744 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13746 //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [28] [29] 30 31 32 33 34 35 36 37 38 39 40
13747 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points,bgid,bgteam,bgmap,bgx,bgy,bgz,bgo FROM characters WHERE guid = '%u'", guid);
13748 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13750 if(!result)
13752 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13753 return false;
13756 Field *fields = result->Fetch();
13758 uint32 dbAccountId = fields[1].GetUInt32();
13760 // check if the character's account in the db and the logged in account match.
13761 // player should be able to load/delete character only with correct account!
13762 if( dbAccountId != GetSession()->GetAccountId() )
13764 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13765 delete result;
13766 return false;
13769 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13771 m_name = fields[3].GetCppString();
13773 // check name limitations
13774 if(!ObjectMgr::IsValidName(m_name) || (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name)))
13776 delete result;
13777 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13778 return false;
13781 if(!LoadValues( fields[2].GetString()))
13783 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13784 delete result;
13785 return false;
13788 // overwrite possible wrong/corrupted guid
13789 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13791 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13792 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13794 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13795 SetVisibleItemSlot(slot,NULL);
13797 if (m_items[slot])
13799 delete m_items[slot];
13800 m_items[slot] = NULL;
13804 // update money limits
13805 if(GetMoney() > MAX_MONEY_AMOUNT)
13806 SetMoney(MAX_MONEY_AMOUNT);
13808 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13809 outDebugValues();
13811 m_race = fields[4].GetUInt8();
13812 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13813 //Other way is to saves m_team into characters table.
13814 setFactionForRace(m_race);
13815 SetCharm(NULL);
13817 m_class = fields[5].GetUInt8();
13819 // load home bind and check in same time class/race pair, it used later for restore broken positions
13820 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13821 return false;
13823 InitPrimaryProffesions(); // to max set before any spell loaded
13825 // init saved position, and fix it later if problematic
13826 uint32 transGUID = fields[24].GetUInt32();
13827 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13828 SetMapId(fields[9].GetUInt32());
13829 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13831 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13833 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
13835 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
13836 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
13837 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
13839 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
13841 // check arena teams integrity
13842 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13844 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13845 if(!arena_team_id)
13846 continue;
13848 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13849 if(at->HaveMember(GetGUID()))
13850 continue;
13852 // arena team not exist or not member, cleanup fields
13853 for(int j =0; j < 6; ++j)
13854 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13857 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13859 if(!IsPositionValid())
13861 sLog.outError("Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
13862 RelocateToHomebind();
13864 transGUID = 0;
13866 m_movementInfo.t_x = 0.0f;
13867 m_movementInfo.t_y = 0.0f;
13868 m_movementInfo.t_z = 0.0f;
13869 m_movementInfo.t_o = 0.0f;
13872 uint32 bgid = fields[34].GetUInt32();
13873 uint32 bgteam = fields[35].GetUInt32();
13875 if(bgid) //saved in BattleGround
13877 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
13879 // check entry point and fix to homebind if need
13880 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
13881 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
13882 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
13884 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid, BATTLEGROUND_TYPE_NONE);
13886 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
13888 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
13889 AddBattleGroundQueueId(bgQueueTypeId);
13891 SetBattleGroundId(currentBg->GetInstanceID(), currentBg->GetTypeID());
13892 SetBGTeam(bgteam);
13894 //join player to battleground group
13895 currentBg->EventPlayerLoggedIn(this, GetGUID());
13896 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
13898 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
13900 else
13902 Relocate(GetBattleGroundEntryPoint());
13903 //RemoveArenaAuras(true);
13906 else
13908 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
13909 // if server restart after player save in BG or area
13910 // player can have current coordinates in to BG/Arean map, fix this
13911 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
13913 // return to BG master
13914 SetMapId(fields[36].GetUInt32());
13915 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
13917 // check entry point and fix to homebind if need
13918 mapEntry = sMapStore.LookupEntry(GetMapId());
13919 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
13920 RelocateToHomebind();
13924 if (transGUID != 0)
13926 m_movementInfo.t_x = fields[20].GetFloat();
13927 m_movementInfo.t_y = fields[21].GetFloat();
13928 m_movementInfo.t_z = fields[22].GetFloat();
13929 m_movementInfo.t_o = fields[23].GetFloat();
13931 if( !MaNGOS::IsValidMapCoord(
13932 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13933 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13934 // transport size limited
13935 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13937 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13938 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13939 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13941 RelocateToHomebind();
13943 m_movementInfo.t_x = 0.0f;
13944 m_movementInfo.t_y = 0.0f;
13945 m_movementInfo.t_z = 0.0f;
13946 m_movementInfo.t_o = 0.0f;
13948 transGUID = 0;
13952 if (transGUID != 0)
13954 for (MapManager::TransportSet::const_iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13956 if( (*iter)->GetGUIDLow() == transGUID)
13958 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
13959 // client without expansion support
13960 if(GetSession()->Expansion() < transMapEntry->Expansion())
13962 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
13963 break;
13966 m_transport = *iter;
13967 m_transport->AddPassenger(this);
13968 SetMapId(m_transport->GetMapId());
13969 break;
13973 if(!m_transport)
13975 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
13976 guid,transGUID);
13978 RelocateToHomebind();
13980 m_movementInfo.t_x = 0.0f;
13981 m_movementInfo.t_y = 0.0f;
13982 m_movementInfo.t_z = 0.0f;
13983 m_movementInfo.t_o = 0.0f;
13985 transGUID = 0;
13988 else // not transport case
13990 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
13991 // client without expansion support
13992 if(GetSession()->Expansion() < mapEntry->Expansion())
13994 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
13995 RelocateToHomebind();
13999 // NOW player must have valid map
14000 // load the player's map here if it's not already loaded
14001 Map *map = GetMap();
14003 // since the player may not be bound to the map yet, make sure subsequent
14004 // getmap calls won't create new maps
14005 SetInstanceId(map->GetInstanceId());
14007 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14008 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14010 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14011 if(at)
14012 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14013 else
14014 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());
14017 SaveRecallPosition();
14019 time_t now = time(NULL);
14020 time_t logoutTime = time_t(fields[16].GetUInt64());
14022 // since last logout (in seconds)
14023 uint64 time_diff = uint64(now - logoutTime);
14025 // set value, including drunk invisibility detection
14026 // calculate sobering. after 15 minutes logged out, the player will be sober again
14027 float soberFactor;
14028 if(time_diff > 15*MINUTE)
14029 soberFactor = 0;
14030 else
14031 soberFactor = 1-time_diff/(15.0f*MINUTE);
14032 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14033 SetDrunkValue(newDrunkenValue);
14035 m_rest_bonus = fields[15].GetFloat();
14036 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14037 float bubble0 = 0.031;
14038 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14039 float bubble1 = 0.125;
14041 if((int32)fields[16].GetUInt32() > 0)
14043 float bubble = fields[17].GetUInt32() > 0
14044 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14045 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14047 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14050 m_cinematic = fields[12].GetUInt32();
14051 m_Played_time[0]= fields[13].GetUInt32();
14052 m_Played_time[1]= fields[14].GetUInt32();
14054 m_resetTalentsCost = fields[18].GetUInt32();
14055 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14057 // reserve some flags
14058 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14060 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14061 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14063 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14065 uint32 extraflags = fields[25].GetUInt32();
14067 m_stableSlots = fields[26].GetUInt32();
14068 if(m_stableSlots > MAX_PET_STABLES)
14070 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14071 m_stableSlots = MAX_PET_STABLES;
14074 m_atLoginFlags = fields[27].GetUInt32();
14076 // Honor system
14077 // Update Honor kills data
14078 m_lastHonorUpdateTime = logoutTime;
14079 UpdateHonorFields();
14081 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14082 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14083 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14085 std::string taxi_nodes = fields[31].GetCppString();
14087 delete result;
14089 // clear channel spell data (if saved at channel spell casting)
14090 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14091 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14093 // clear charm/summon related fields
14094 SetCharm(NULL);
14095 SetPet(NULL);
14096 SetCharmerGUID(0);
14097 SetOwnerGUID(0);
14098 SetCreatorGUID(0);
14100 // reset some aura modifiers before aura apply
14101 SetFarSightGUID(0);
14102 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14103 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14105 _LoadSkills();
14107 // make sure the unit is considered out of combat for proper loading
14108 ClearInCombat();
14110 // make sure the unit is considered not in duel for proper loading
14111 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14112 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14114 // remember loaded power/health values to restore after stats initialization and modifier applying
14115 uint32 savedHealth = GetHealth();
14116 uint32 savedPower[MAX_POWERS];
14117 for(uint32 i = 0; i < MAX_POWERS; ++i)
14118 savedPower[i] = GetPower(Powers(i));
14120 // reset stats before loading any modifiers
14121 InitStatsForLevel();
14122 InitTaxiNodesForLevel();
14123 InitGlyphsForLevel();
14124 InitRunes();
14126 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14128 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14129 //_LoadMail();
14131 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14132 _LoadGlyphAuras();
14134 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14135 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14136 m_deathState = DEAD;
14138 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14140 // after spell load, learn rewarded spell if need also
14141 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14142 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14144 // after spell and quest load
14145 InitTalentForLevel();
14146 learnDefaultSpells();
14148 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14150 // must be before inventory (some items required reputation check)
14151 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14153 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14155 // update items with duration and realtime
14156 UpdateItemDuration(time_diff, true);
14158 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14160 // unread mails and next delivery time, actual mails not loaded
14161 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14163 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14165 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14166 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14167 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14169 if(!HasTitle(curTitle))
14170 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14173 // Not finish taxi flight path
14174 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14176 // problems with taxi path loading
14177 TaxiNodesEntry const* nodeEntry = NULL;
14178 if(uint32 node_id = m_taxi.GetTaxiSource())
14179 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14181 if(!nodeEntry) // don't know taxi start node, to homebind
14183 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14184 RelocateToHomebind();
14185 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14187 else // have start node, to it
14189 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14190 SetMapId(nodeEntry->map_id);
14191 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14192 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14194 m_taxi.ClearTaxiDestinations();
14196 else if(uint32 node_id = m_taxi.GetTaxiSource())
14198 // save source node as recall coord to prevent recall and fall from sky
14199 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14200 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14201 m_recallMap = nodeEntry->map_id;
14202 m_recallX = nodeEntry->x;
14203 m_recallY = nodeEntry->y;
14204 m_recallZ = nodeEntry->z;
14206 // flight will started later
14209 // has to be called after last Relocate() in Player::LoadFromDB
14210 SetFallInformation(0, GetPositionZ());
14212 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14214 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14215 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14216 if(!isAlive())
14217 RemoveAllAurasOnDeath();
14219 //apply all stat bonuses from items and auras
14220 SetCanModifyStats(true);
14221 UpdateAllStats();
14223 // restore remembered power/health values (but not more max values)
14224 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14225 for(uint32 i = 0; i < MAX_POWERS; ++i)
14226 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14228 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14229 outDebugValues();
14231 // GM state
14232 if(GetSession()->GetSecurity() > SEC_PLAYER)
14234 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14236 default:
14237 case 0: break; // disable
14238 case 1: SetGameMaster(true); break; // enable
14239 case 2: // save state
14240 if(extraflags & PLAYER_EXTRA_GM_ON)
14241 SetGameMaster(true);
14242 break;
14245 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14247 default:
14248 case 0: SetGMVisible(false); break; // invisible
14249 case 1: break; // visible
14250 case 2: // save state
14251 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14252 SetGMVisible(false);
14253 break;
14256 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14258 default:
14259 case 0: break; // disable
14260 case 1: SetAcceptTicket(true); break; // enable
14261 case 2: // save state
14262 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14263 SetAcceptTicket(true);
14264 break;
14267 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14269 default:
14270 case 0: break; // disable
14271 case 1: SetGMChat(true); break; // enable
14272 case 2: // save state
14273 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14274 SetGMChat(true);
14275 break;
14278 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14280 default:
14281 case 0: break; // disable
14282 case 1: SetAcceptWhispers(true); break; // enable
14283 case 2: // save state
14284 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14285 SetAcceptWhispers(true);
14286 break;
14290 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14292 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14293 m_achievementMgr.CheckAllAchievementCriteria();
14294 return true;
14297 bool Player::isAllowedToLoot(Creature* creature)
14299 if(Player* recipient = creature->GetLootRecipient())
14301 if (recipient == this)
14302 return true;
14303 if( Group* otherGroup = recipient->GetGroup())
14305 Group* thisGroup = GetGroup();
14306 if(!thisGroup)
14307 return false;
14308 return thisGroup == otherGroup;
14310 return false;
14312 else
14313 // prevent other players from looting if the recipient got disconnected
14314 return !creature->hasLootRecipient();
14317 void Player::_LoadActions(QueryResult *result)
14319 m_actionButtons.clear();
14321 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14323 if(result)
14327 Field *fields = result->Fetch();
14329 uint8 button = fields[0].GetUInt8();
14331 if(addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8()))
14332 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14333 else
14335 sLog.outError( " ...at loading, and will deleted in DB also");
14337 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14338 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14341 while( result->NextRow() );
14343 delete result;
14347 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14349 m_Auras.clear();
14350 for (int i = 0; i < TOTAL_AURAS; ++i)
14351 m_modAuras[i].clear();
14353 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14355 if(result)
14359 Field *fields = result->Fetch();
14360 uint64 caster_guid = fields[0].GetUInt64();
14361 uint32 spellid = fields[1].GetUInt32();
14362 uint32 effindex = fields[2].GetUInt32();
14363 uint32 stackcount = fields[3].GetUInt32();
14364 int32 damage = (int32)fields[4].GetUInt32();
14365 int32 maxduration = (int32)fields[5].GetUInt32();
14366 int32 remaintime = (int32)fields[6].GetUInt32();
14367 int32 remaincharges = (int32)fields[7].GetUInt32();
14369 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14370 if(!spellproto)
14372 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14373 continue;
14376 if(effindex >= 3)
14378 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14379 continue;
14382 // negative effects should continue counting down after logout
14383 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14385 if(remaintime <= int32(timediff))
14386 continue;
14388 remaintime -= timediff;
14391 // prevent wrong values of remaincharges
14392 if(spellproto->procCharges)
14394 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14395 remaincharges = spellproto->procCharges;
14397 else
14398 remaincharges = 0;
14401 for(uint32 i=0; i<stackcount; ++i)
14403 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14404 if(!damage)
14405 damage = aura->GetModifier()->m_amount;
14407 // reset stolen single target auras
14408 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14409 aura->SetIsSingleTarget(false);
14411 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14412 AddAura(aura);
14413 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14416 while( result->NextRow() );
14418 delete result;
14421 if(m_class == CLASS_WARRIOR)
14422 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14425 void Player::_LoadGlyphAuras()
14427 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14429 if (uint32 glyph = GetGlyph(i))
14431 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14433 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14435 if(gp->TypeFlags == gs->TypeFlags)
14437 CastSpell(this, gp->SpellId, true);
14438 continue;
14440 else
14441 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14443 else
14444 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14446 else
14447 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14449 // On any error remove glyph
14450 SetGlyph(i, 0);
14455 void Player::LoadCorpse()
14457 if( isAlive() )
14459 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14461 else
14463 if(Corpse *corpse = GetCorpse())
14465 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14467 else
14469 //Prevent Dead Player login without corpse
14470 ResurrectPlayer(0.5f);
14475 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14477 //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());
14478 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14479 //NOTE: the "order by `bag`" is important because it makes sure
14480 //the bagMap is filled before items in the bags are loaded
14481 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14482 //expected to be equipped before offhand items (TODO: fixme)
14484 uint32 zone = GetZoneId();
14486 if (result)
14488 std::list<Item*> problematicItems;
14490 // prevent items from being added to the queue when stored
14491 m_itemUpdateQueueBlocked = true;
14494 Field *fields = result->Fetch();
14495 uint32 bag_guid = fields[1].GetUInt32();
14496 uint8 slot = fields[2].GetUInt8();
14497 uint32 item_guid = fields[3].GetUInt32();
14498 uint32 item_id = fields[4].GetUInt32();
14500 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14502 if(!proto)
14504 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14505 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14506 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14507 continue;
14510 Item *item = NewItemOrBag(proto);
14512 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14514 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14515 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14516 item->FSetState(ITEM_REMOVED);
14517 item->SaveToDB(); // it also deletes item object !
14518 continue;
14521 // not allow have in alive state item limited to another map/zone
14522 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14524 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14525 item->FSetState(ITEM_REMOVED);
14526 item->SaveToDB(); // it also deletes item object !
14527 continue;
14530 // "Conjured items disappear if you are logged out for more than 15 minutes"
14531 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14533 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14534 item->FSetState(ITEM_REMOVED);
14535 item->SaveToDB(); // it also deletes item object !
14536 continue;
14539 bool success = true;
14541 if (!bag_guid)
14543 // the item is not in a bag
14544 item->SetContainer( NULL );
14545 item->SetSlot(slot);
14547 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14549 ItemPosCountVec dest;
14550 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14551 item = StoreItem(dest, item, true);
14552 else
14553 success = false;
14555 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14557 uint16 dest;
14558 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14559 QuickEquipItem(dest, item);
14560 else
14561 success = false;
14563 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14565 ItemPosCountVec dest;
14566 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14567 item = BankItem(dest, item, true);
14568 else
14569 success = false;
14572 if(success)
14574 // store bags that may contain items in them
14575 if(item->IsBag() && IsBagPos(item->GetPos()))
14576 bagMap[item_guid] = (Bag*)item;
14579 else
14581 item->SetSlot(NULL_SLOT);
14582 // the item is in a bag, find the bag
14583 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
14584 if(itr != bagMap.end())
14585 itr->second->StoreItem(slot, item, true );
14586 else
14587 success = false;
14590 // item's state may have changed after stored
14591 if (success)
14592 item->SetState(ITEM_UNCHANGED, this);
14593 else
14595 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);
14596 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14597 problematicItems.push_back(item);
14599 } while (result->NextRow());
14601 delete result;
14602 m_itemUpdateQueueBlocked = false;
14604 // send by mail problematic items
14605 while(!problematicItems.empty())
14607 // fill mail
14608 MailItemsInfo mi; // item list preparing
14610 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14612 Item* item = problematicItems.front();
14613 problematicItems.pop_front();
14615 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14618 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14620 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14623 //if(isAlive())
14624 _ApplyAllItemMods();
14627 // load mailed item which should receive current player
14628 void Player::_LoadMailedItems(Mail *mail)
14630 // data needs to be at first place for Item::LoadFromDB
14631 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);
14632 if(!result)
14633 return;
14637 Field *fields = result->Fetch();
14638 uint32 item_guid_low = fields[1].GetUInt32();
14639 uint32 item_template = fields[2].GetUInt32();
14641 mail->AddItem(item_guid_low, item_template);
14643 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14645 if(!proto)
14647 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);
14648 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14649 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14650 continue;
14653 Item *item = NewItemOrBag(proto);
14655 if(!item->LoadFromDB(item_guid_low, 0, result))
14657 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14658 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14659 item->FSetState(ITEM_REMOVED);
14660 item->SaveToDB(); // it also deletes item object !
14661 continue;
14664 AddMItem(item);
14665 } while (result->NextRow());
14667 delete result;
14670 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14672 //set a count of unread mails
14673 //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);
14674 if (resultUnread)
14676 Field *fieldMail = resultUnread->Fetch();
14677 unReadMails = fieldMail[0].GetUInt8();
14678 delete resultUnread;
14681 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14682 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14683 if (resultDelivery)
14685 Field *fieldMail = resultDelivery->Fetch();
14686 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14687 delete resultDelivery;
14691 void Player::_LoadMail()
14693 m_mail.clear();
14694 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14695 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());
14696 if(result)
14700 Field *fields = result->Fetch();
14701 Mail *m = new Mail;
14702 m->messageID = fields[0].GetUInt32();
14703 m->messageType = fields[1].GetUInt8();
14704 m->sender = fields[2].GetUInt32();
14705 m->receiver = fields[3].GetUInt32();
14706 m->subject = fields[4].GetCppString();
14707 m->itemTextId = fields[5].GetUInt32();
14708 bool has_items = fields[6].GetBool();
14709 m->expire_time = (time_t)fields[7].GetUInt64();
14710 m->deliver_time = (time_t)fields[8].GetUInt64();
14711 m->money = fields[9].GetUInt32();
14712 m->COD = fields[10].GetUInt32();
14713 m->checked = fields[11].GetUInt32();
14714 m->stationery = fields[12].GetUInt8();
14715 m->mailTemplateId = fields[13].GetInt16();
14717 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14719 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14720 m->mailTemplateId = 0;
14723 m->state = MAIL_STATE_UNCHANGED;
14725 if (has_items)
14726 _LoadMailedItems(m);
14728 m_mail.push_back(m);
14729 } while( result->NextRow() );
14730 delete result;
14732 m_mailsLoaded = true;
14735 void Player::LoadPet()
14737 //fixme: the pet should still be loaded if the player is not in world
14738 // just not added to the map
14739 if(IsInWorld())
14741 Pet *pet = new Pet;
14742 if(!pet->LoadPetFromDB(this,0,0,true))
14743 delete pet;
14747 void Player::_LoadQuestStatus(QueryResult *result)
14749 mQuestStatus.clear();
14751 uint32 slot = 0;
14753 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14754 //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());
14756 if(result)
14760 Field *fields = result->Fetch();
14762 uint32 quest_id = fields[0].GetUInt32();
14763 // used to be new, no delete?
14764 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14765 if( pQuest )
14767 // find or create
14768 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14770 uint32 qstatus = fields[1].GetUInt32();
14771 if(qstatus < MAX_QUEST_STATUS)
14772 questStatusData.m_status = QuestStatus(qstatus);
14773 else
14775 questStatusData.m_status = QUEST_STATUS_NONE;
14776 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14779 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14780 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14782 time_t quest_time = time_t(fields[4].GetUInt64());
14784 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14786 AddTimedQuest( quest_id );
14788 if (quest_time <= sWorld.GetGameTime())
14789 questStatusData.m_timer = 1;
14790 else
14791 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
14793 else
14794 quest_time = 0;
14796 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14797 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14798 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14799 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14800 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14801 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14802 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14803 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14805 questStatusData.uState = QUEST_UNCHANGED;
14807 // add to quest log
14808 if( slot < MAX_QUEST_LOG_SIZE &&
14809 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14810 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
14811 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14813 SetQuestSlot(slot,quest_id,quest_time);
14815 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14816 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14818 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14819 if(questStatusData.m_creatureOrGOcount[idx])
14820 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14822 ++slot;
14825 if(questStatusData.m_rewarded)
14827 // learn rewarded spell if unknown
14828 learnQuestRewardedSpells(pQuest);
14830 // set rewarded title if any
14831 if(pQuest->GetCharTitleId())
14833 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14834 SetTitle(titleEntry);
14837 if(pQuest->GetBonusTalents())
14838 m_questRewardTalentCount+=pQuest->GetBonusTalents();
14841 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14844 while( result->NextRow() );
14846 delete result;
14849 // clear quest log tail
14850 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14851 SetQuestSlot(i,0);
14854 void Player::_LoadDailyQuestStatus(QueryResult *result)
14856 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14857 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14859 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14861 if(result)
14863 uint32 quest_daily_idx = 0;
14867 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14869 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14870 break;
14873 Field *fields = result->Fetch();
14875 uint32 quest_id = fields[0].GetUInt32();
14877 // save _any_ from daily quest times (it must be after last reset anyway)
14878 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14880 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14881 if( !pQuest )
14882 continue;
14884 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14885 ++quest_daily_idx;
14887 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14889 while( result->NextRow() );
14891 delete result;
14894 m_DailyQuestChanged = false;
14897 void Player::_LoadSpells(QueryResult *result)
14899 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14901 if(result)
14905 Field *fields = result->Fetch();
14907 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
14909 while( result->NextRow() );
14911 delete result;
14915 void Player::_LoadTutorials(QueryResult *result)
14917 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14919 if(result)
14923 Field *fields = result->Fetch();
14925 for (int iI=0; iI<8; ++iI)
14926 m_Tutorials[iI] = fields[iI].GetUInt32();
14928 while( result->NextRow() );
14930 delete result;
14933 m_TutorialsChanged = false;
14936 void Player::_LoadGroup(QueryResult *result)
14938 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14939 if(result)
14941 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14942 delete result;
14943 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14944 if(group)
14946 uint8 subgroup = group->GetMemberGroup(GetGUID());
14947 SetGroup(group, subgroup);
14948 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14950 // the group leader may change the instance difficulty while the player is offline
14951 SetDifficulty(group->GetDifficulty());
14957 void Player::_LoadBoundInstances(QueryResult *result)
14959 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
14960 m_boundInstances[i].clear();
14962 Group *group = GetGroup();
14964 //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));
14965 if(result)
14969 Field *fields = result->Fetch();
14970 bool perm = fields[1].GetBool();
14971 uint32 mapId = fields[2].GetUInt32();
14972 uint32 instanceId = fields[0].GetUInt32();
14973 uint8 difficulty = fields[3].GetUInt8();
14974 time_t resetTime = (time_t)fields[4].GetUInt64();
14975 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14976 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14977 // and in that case it is not used
14979 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
14980 if(!mapEntry || !mapEntry->IsDungeon())
14982 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
14983 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14984 continue;
14987 if(!perm && group)
14989 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);
14990 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14991 continue;
14994 // since non permanent binds are always solo bind, they can always be reset
14995 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
14996 if(save) BindToInstance(save, perm, true);
14997 } while(result->NextRow());
14998 delete result;
15002 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15004 // some instances only have one difficulty
15005 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15006 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15008 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15009 if(itr != m_boundInstances[difficulty].end())
15010 return &itr->second;
15011 else
15012 return NULL;
15015 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15017 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15018 UnbindInstance(itr, difficulty, unload);
15021 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15023 if(itr != m_boundInstances[difficulty].end())
15025 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15026 itr->second.save->RemovePlayer(this); // save can become invalid
15027 m_boundInstances[difficulty].erase(itr++);
15031 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15033 if(save)
15035 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15036 if(bind.save)
15038 // update the save when the group kills a boss
15039 if(permanent != bind.perm || save != bind.save)
15040 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());
15042 else
15043 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15045 if(bind.save != save)
15047 if(bind.save) bind.save->RemovePlayer(this);
15048 save->AddPlayer(this);
15051 if(permanent) save->SetCanReset(false);
15053 bind.save = save;
15054 bind.perm = permanent;
15055 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());
15056 return &bind;
15058 else
15059 return NULL;
15062 void Player::SendRaidInfo()
15064 uint32 counter = 0;
15066 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15068 size_t p_counter = data.wpos();
15069 data << uint32(counter); // placeholder
15071 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15073 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15075 if(itr->second.perm)
15077 InstanceSave *save = itr->second.save;
15078 data << uint32(save->GetMapId());
15079 data << uint32(save->GetResetTime() - time(NULL));
15080 data << uint32(save->GetInstanceId());
15081 data << uint32(save->GetDifficulty());
15082 ++counter;
15086 data.put<uint32>(p_counter,counter);
15087 GetSession()->SendPacket(&data);
15091 - called on every successful teleportation to a map
15093 void Player::SendSavedInstances()
15095 bool hasBeenSaved = false;
15096 WorldPacket data;
15098 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15100 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15102 if(itr->second.perm) // only permanent binds are sent
15104 hasBeenSaved = true;
15105 break;
15110 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15111 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15112 data << uint32(hasBeenSaved);
15113 GetSession()->SendPacket(&data);
15115 if(!hasBeenSaved)
15116 return;
15118 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15120 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15122 if(itr->second.perm)
15124 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15125 data << uint32(itr->second.save->GetMapId());
15126 GetSession()->SendPacket(&data);
15132 /// convert the player's binds to the group
15133 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15135 bool has_binds = false;
15136 bool has_solo = false;
15138 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15139 assert(player_guid);
15141 // copy all binds to the group, when changing leader it's assumed the character
15142 // will not have any solo binds
15144 if(player)
15146 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15148 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15150 has_binds = true;
15151 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15152 // permanent binds are not removed
15153 if(!itr->second.perm)
15155 player->UnbindInstance(itr, i, true); // increments itr
15156 has_solo = true;
15158 else
15159 ++itr;
15164 // if the player's not online we don't know what binds it has
15165 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));
15166 // the following should not get executed when changing leaders
15167 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15170 bool Player::_LoadHomeBind(QueryResult *result)
15172 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15173 if(!info)
15175 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15176 return false;
15179 bool ok = false;
15180 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15181 if (result)
15183 Field *fields = result->Fetch();
15184 m_homebindMapId = fields[0].GetUInt32();
15185 m_homebindZoneId = fields[1].GetUInt16();
15186 m_homebindX = fields[2].GetFloat();
15187 m_homebindY = fields[3].GetFloat();
15188 m_homebindZ = fields[4].GetFloat();
15189 delete result;
15191 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15193 // accept saved data only for valid position (and non instanceable), and accessable
15194 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15195 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15197 ok = true;
15199 else
15200 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15203 if(!ok)
15205 m_homebindMapId = info->mapId;
15206 m_homebindZoneId = info->zoneId;
15207 m_homebindX = info->positionX;
15208 m_homebindY = info->positionY;
15209 m_homebindZ = info->positionZ;
15211 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);
15214 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15215 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15217 return true;
15220 /*********************************************************/
15221 /*** SAVE SYSTEM ***/
15222 /*********************************************************/
15224 void Player::SaveToDB()
15226 // delay auto save at any saves (manual, in code, or autosave)
15227 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15229 // first save/honor gain after midnight will also update the player's honor fields
15230 UpdateHonorFields();
15232 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15233 //save, far from tavern/city
15234 //save, but in tavern/city
15235 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15236 outDebugValues();
15238 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15239 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15240 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15241 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15242 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15243 uint32 tmp_displayid = GetDisplayId();
15245 // Set player sit state to standing on save, also stealth and shifted form
15246 SetByteValue(UNIT_FIELD_BYTES_1, 0, UNIT_STAND_STATE_STAND);
15247 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15248 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15249 SetDisplayId(GetNativeDisplayId());
15251 bool inworld = IsInWorld();
15253 CharacterDatabase.BeginTransaction();
15255 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15257 std::string sql_name = m_name;
15258 CharacterDatabase.escape_string(sql_name);
15260 std::ostringstream ss;
15261 ss << "INSERT INTO characters (guid,account,name,race,class,"
15262 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15263 "taximask, online, cinematic, "
15264 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15265 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15266 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15267 << GetGUIDLow() << ", "
15268 << GetSession()->GetAccountId() << ", '"
15269 << sql_name << "', "
15270 << m_race << ", "
15271 << m_class << ", ";
15273 if(!IsBeingTeleported())
15275 ss << GetMapId() << ", "
15276 << (uint32)GetDifficulty() << ", "
15277 << finiteAlways(GetPositionX()) << ", "
15278 << finiteAlways(GetPositionY()) << ", "
15279 << finiteAlways(GetPositionZ()) << ", "
15280 << finiteAlways(GetOrientation()) << ", '";
15282 else
15284 ss << GetTeleportDest().mapid << ", "
15285 << (uint32)GetDifficulty() << ", "
15286 << finiteAlways(GetTeleportDest().x) << ", "
15287 << finiteAlways(GetTeleportDest().y) << ", "
15288 << finiteAlways(GetTeleportDest().z) << ", "
15289 << finiteAlways(GetTeleportDest().o) << ", '";
15292 uint16 i;
15293 for( i = 0; i < m_valuesCount; ++i )
15295 ss << GetUInt32Value(i) << " ";
15298 ss << "', ";
15300 ss << m_taxi; // string with TaxiMaskSize numbers
15302 ss << ", ";
15303 ss << (inworld ? 1 : 0);
15305 ss << ", ";
15306 ss << m_cinematic;
15308 ss << ", ";
15309 ss << m_Played_time[0];
15310 ss << ", ";
15311 ss << m_Played_time[1];
15313 ss << ", ";
15314 ss << finiteAlways(m_rest_bonus);
15315 ss << ", ";
15316 ss << (uint64)time(NULL);
15317 ss << ", ";
15318 ss << is_save_resting;
15319 ss << ", ";
15320 ss << m_resetTalentsCost;
15321 ss << ", ";
15322 ss << (uint64)m_resetTalentsTime;
15324 ss << ", ";
15325 ss << finiteAlways(m_movementInfo.t_x);
15326 ss << ", ";
15327 ss << finiteAlways(m_movementInfo.t_y);
15328 ss << ", ";
15329 ss << finiteAlways(m_movementInfo.t_z);
15330 ss << ", ";
15331 ss << finiteAlways(m_movementInfo.t_o);
15332 ss << ", ";
15333 if (m_transport)
15334 ss << m_transport->GetGUIDLow();
15335 else
15336 ss << "0";
15338 ss << ", ";
15339 ss << m_ExtraFlags;
15341 ss << ", ";
15342 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15344 ss << ", ";
15345 ss << uint32(m_atLoginFlags);
15347 ss << ", ";
15348 ss << GetZoneId();
15350 ss << ", ";
15351 ss << (uint64)m_deathExpireTime;
15353 ss << ", '";
15354 ss << m_taxi.SaveTaxiDestinationsToString();
15355 ss << "', '0', ";
15356 ss << GetBattleGroundId();
15357 ss << ", ";
15358 ss << GetBGTeam();
15359 ss << ", ";
15360 ss << m_bgEntryPoint.mapid << ", "
15361 << finiteAlways(m_bgEntryPoint.x) << ", "
15362 << finiteAlways(m_bgEntryPoint.y) << ", "
15363 << finiteAlways(m_bgEntryPoint.z) << ", "
15364 << finiteAlways(m_bgEntryPoint.o);
15365 ss << ")";
15367 CharacterDatabase.Execute( ss.str().c_str() );
15369 if(m_mailsUpdated) //save mails only when needed
15370 _SaveMail();
15372 _SaveInventory();
15373 _SaveQuestStatus();
15374 _SaveDailyQuestStatus();
15375 _SaveTutorials();
15376 _SaveSpells();
15377 _SaveSpellCooldowns();
15378 _SaveActions();
15379 _SaveAuras();
15380 m_achievementMgr.SaveToDB();
15381 m_reputationMgr.SaveToDB();
15383 CharacterDatabase.CommitTransaction();
15385 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15386 SetDisplayId(tmp_displayid);
15387 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15388 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15389 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15390 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15392 // save pet (hunter pet level and experience and all type pets health/mana).
15393 if(Pet* pet = GetPet())
15394 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15397 // fast save function for item/money cheating preventing - save only inventory and money state
15398 void Player::SaveInventoryAndGoldToDB()
15400 _SaveInventory();
15401 //money is in data field
15402 SaveDataFieldToDB();
15405 void Player::_SaveActions()
15407 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15409 switch (itr->second.uState)
15411 case ACTIONBUTTON_NEW:
15412 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15413 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15414 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15415 ++itr;
15416 break;
15417 case ACTIONBUTTON_CHANGED:
15418 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15419 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15420 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15421 ++itr;
15422 break;
15423 case ACTIONBUTTON_DELETED:
15424 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15425 m_actionButtons.erase(itr++);
15426 break;
15427 default:
15428 ++itr;
15429 break;
15434 void Player::_SaveAuras()
15436 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15438 AuraMap const& auras = GetAuras();
15440 if (auras.empty())
15441 return;
15443 spellEffectPair lastEffectPair = auras.begin()->first;
15444 uint32 stackCounter = 1;
15446 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15448 if(itr == auras.end() || lastEffectPair != itr->first)
15450 AuraMap::const_iterator itr2 = itr;
15451 // save previous spellEffectPair to db
15452 itr2--;
15454 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15456 //skip all auras from spells that are passive or need a shapeshift
15457 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15459 //do not save single target auras (unless they were cast by the player)
15460 if (!(itr2->second->GetCasterGUID() != GetGUID() && itr2->second->IsSingleTarget()))
15462 uint8 i;
15463 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15464 for (i = 0; i < 3; ++i)
15465 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15466 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15467 break;
15469 if (i == 3)
15471 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15472 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15473 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()));
15478 if(itr == auras.end())
15479 break;
15482 if (lastEffectPair == itr->first)
15483 stackCounter++;
15484 else
15486 lastEffectPair = itr->first;
15487 stackCounter = 1;
15492 void Player::_SaveInventory()
15494 // force items in buyback slots to new state
15495 // and remove those that aren't already
15496 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
15498 Item *item = m_items[i];
15499 if (!item || item->GetState() == ITEM_NEW) continue;
15500 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15501 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15502 m_items[i]->FSetState(ITEM_NEW);
15505 // update enchantment durations
15506 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15508 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15511 // if no changes
15512 if (m_itemUpdateQueue.empty()) return;
15514 // do not save if the update queue is corrupt
15515 bool error = false;
15516 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15518 Item *item = m_itemUpdateQueue[i];
15519 if(!item || item->GetState() == ITEM_REMOVED) continue;
15520 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15522 if (test == NULL)
15524 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());
15525 error = true;
15527 else if (test != item)
15529 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());
15530 error = true;
15534 if (error)
15536 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15537 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15538 return;
15541 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15543 Item *item = m_itemUpdateQueue[i];
15544 if(!item) continue;
15546 Bag *container = item->GetContainer();
15547 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15549 switch(item->GetState())
15551 case ITEM_NEW:
15552 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());
15553 break;
15554 case ITEM_CHANGED:
15555 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());
15556 break;
15557 case ITEM_REMOVED:
15558 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15559 break;
15560 case ITEM_UNCHANGED:
15561 break;
15564 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15566 m_itemUpdateQueue.clear();
15569 void Player::_SaveMail()
15571 if (!m_mailsLoaded)
15572 return;
15574 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15576 Mail *m = (*itr);
15577 if (m->state == MAIL_STATE_CHANGED)
15579 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'",
15580 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15581 if(m->removedItems.size())
15583 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15584 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15585 m->removedItems.clear();
15587 m->state = MAIL_STATE_UNCHANGED;
15589 else if (m->state == MAIL_STATE_DELETED)
15591 if (m->HasItems())
15592 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15593 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15594 if (m->itemTextId)
15595 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15596 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15597 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15601 //deallocate deleted mails...
15602 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15604 if ((*itr)->state == MAIL_STATE_DELETED)
15606 Mail* m = *itr;
15607 m_mail.erase(itr);
15608 delete m;
15609 itr = m_mail.begin();
15611 else
15612 ++itr;
15615 m_mailsUpdated = false;
15618 void Player::_SaveQuestStatus()
15620 // we don't need transactions here.
15621 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15623 switch (i->second.uState)
15625 case QUEST_NEW :
15626 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15627 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15628 GetGUIDLow(), i->first, i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILISECONDS+ sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3]);
15629 break;
15630 case QUEST_CHANGED :
15631 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' ",
15632 i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILISECONDS + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3], GetGUIDLow(), i->first );
15633 break;
15634 case QUEST_UNCHANGED:
15635 break;
15637 i->second.uState = QUEST_UNCHANGED;
15641 void Player::_SaveDailyQuestStatus()
15643 if(!m_DailyQuestChanged)
15644 return;
15646 m_DailyQuestChanged = false;
15648 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15650 // we don't need transactions here.
15651 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15652 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15653 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15654 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15655 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15658 void Player::_SaveSpells()
15660 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15662 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15663 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15665 // add only changed/new not dependent spells
15666 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15667 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);
15669 if (itr->second->state == PLAYERSPELL_REMOVED)
15671 delete itr->second;
15672 m_spells.erase(itr++);
15674 else
15676 itr->second->state = PLAYERSPELL_UNCHANGED;
15677 ++itr;
15683 void Player::_SaveTutorials()
15685 if(!m_TutorialsChanged)
15686 return;
15688 uint32 Rows=0;
15689 // it's better than rebuilding indexes multiple times
15690 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15691 if(result)
15693 Rows = result->Fetch()[0].GetUInt32();
15694 delete result;
15697 if (Rows)
15699 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'",
15700 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 );
15702 else
15704 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]);
15707 m_TutorialsChanged = false;
15710 void Player::outDebugValues() const
15712 if(!sLog.IsOutDebug()) // optimize disabled debug output
15713 return;
15715 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15716 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15717 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15718 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15719 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15720 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15721 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15722 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15723 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15724 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15725 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15726 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15729 /*********************************************************/
15730 /*** FLOOD FILTER SYSTEM ***/
15731 /*********************************************************/
15733 void Player::UpdateSpeakTime()
15735 // ignore chat spam protection for GMs in any mode
15736 if(GetSession()->GetSecurity() > SEC_PLAYER)
15737 return;
15739 time_t current = time (NULL);
15740 if(m_speakTime > current)
15742 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15743 if(!max_count)
15744 return;
15746 ++m_speakCount;
15747 if(m_speakCount >= max_count)
15749 // prevent overwrite mute time, if message send just before mutes set, for example.
15750 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15751 if(GetSession()->m_muteTime < new_mute)
15752 GetSession()->m_muteTime = new_mute;
15754 m_speakCount = 0;
15757 else
15758 m_speakCount = 0;
15760 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15763 bool Player::CanSpeak() const
15765 return GetSession()->m_muteTime <= time (NULL);
15768 /*********************************************************/
15769 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15770 /*********************************************************/
15772 void Player::SendAttackSwingNotInRange()
15774 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15775 GetSession()->SendPacket( &data );
15778 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15780 std::ostringstream ss;
15781 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15782 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15783 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15784 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15785 sLog.outDebug(ss.str().c_str());
15786 CharacterDatabase.Execute(ss.str().c_str());
15789 void Player::SaveDataFieldToDB()
15791 std::ostringstream ss;
15792 ss<<"UPDATE characters SET data='";
15794 for(uint16 i = 0; i < m_valuesCount; ++i )
15796 ss << GetUInt32Value(i) << " ";
15798 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15800 CharacterDatabase.Execute(ss.str().c_str());
15803 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15805 std::ostringstream ss2;
15806 ss2<<"UPDATE characters SET data='";
15807 int i=0;
15808 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15810 ss2<<tokens[i]<<" ";
15812 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15814 return CharacterDatabase.Execute(ss2.str().c_str());
15817 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15819 char buf[11];
15820 snprintf(buf,11,"%u",value);
15822 if(index >= tokens.size())
15823 return;
15825 tokens[index] = buf;
15828 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15830 Tokens tokens;
15831 if(!LoadValuesArrayFromDB(tokens,guid))
15832 return;
15834 if(index >= tokens.size())
15835 return;
15837 char buf[11];
15838 snprintf(buf,11,"%u",value);
15839 tokens[index] = buf;
15841 SaveValuesArrayInDB(tokens,guid);
15844 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15846 uint32 temp;
15847 memcpy(&temp, &value, sizeof(value));
15848 Player::SetUInt32ValueInDB(index, temp, guid);
15851 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15853 Tokens tokens;
15854 if(!LoadValuesArrayFromDB(tokens, guid))
15855 return;
15857 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15858 uint8 race = unit_bytes0 & 0xFF;
15859 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15861 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15862 if(!info)
15863 return;
15865 unit_bytes0 &= ~(0xFF << 16);
15866 unit_bytes0 |= (gender << 16);
15867 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15869 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
15870 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
15872 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
15874 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
15875 player_bytes2 &= ~0xFF;
15876 player_bytes2 |= facialHair;
15877 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
15879 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
15880 player_bytes3 &= ~0xFF;
15881 player_bytes3 |= gender;
15882 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
15884 SaveValuesArrayInDB(tokens, guid);
15887 void Player::SendAttackSwingNotStanding()
15889 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15890 GetSession()->SendPacket( &data );
15893 void Player::SendAttackSwingDeadTarget()
15895 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15896 GetSession()->SendPacket( &data );
15899 void Player::SendAttackSwingCantAttack()
15901 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15902 GetSession()->SendPacket( &data );
15905 void Player::SendAttackSwingCancelAttack()
15907 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15908 GetSession()->SendPacket( &data );
15911 void Player::SendAttackSwingBadFacingAttack()
15913 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15914 GetSession()->SendPacket( &data );
15917 void Player::SendAutoRepeatCancel()
15919 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
15920 data.append(GetPackGUID()); // may be it's target guid
15921 GetSession()->SendPacket( &data );
15924 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15926 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15927 data << Area;
15928 data << Experience;
15929 GetSession()->SendPacket(&data);
15932 void Player::SendDungeonDifficulty(bool IsInGroup)
15934 uint8 val = 0x00000001;
15935 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15936 data << (uint32)GetDifficulty();
15937 data << uint32(val);
15938 data << uint32(IsInGroup);
15939 GetSession()->SendPacket(&data);
15942 void Player::SendResetFailedNotify(uint32 mapid)
15944 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15945 data << uint32(mapid);
15946 GetSession()->SendPacket(&data);
15949 /// Reset all solo instances and optionally send a message on success for each
15950 void Player::ResetInstances(uint8 method)
15952 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15954 // we assume that when the difficulty changes, all instances that can be reset will be
15955 uint8 dif = GetDifficulty();
15957 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15959 InstanceSave *p = itr->second.save;
15960 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15961 if(!entry || !p->CanReset())
15963 ++itr;
15964 continue;
15967 if(method == INSTANCE_RESET_ALL)
15969 // the "reset all instances" method can only reset normal maps
15970 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15972 ++itr;
15973 continue;
15977 // if the map is loaded, reset it
15978 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
15979 if(map && map->IsDungeon())
15980 ((InstanceMap*)map)->Reset(method);
15982 // since this is a solo instance there should not be any players inside
15983 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
15984 SendResetInstanceSuccess(p->GetMapId());
15986 p->DeleteFromDB();
15987 m_boundInstances[dif].erase(itr++);
15989 // the following should remove the instance save from the manager and delete it as well
15990 p->RemovePlayer(this);
15994 void Player::SendResetInstanceSuccess(uint32 MapId)
15996 WorldPacket data(SMSG_INSTANCE_RESET, 4);
15997 data << MapId;
15998 GetSession()->SendPacket(&data);
16001 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16003 // TODO: find what other fail reasons there are besides players in the instance
16004 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16005 data << reason;
16006 data << MapId;
16007 GetSession()->SendPacket(&data);
16010 /*********************************************************/
16011 /*** Update timers ***/
16012 /*********************************************************/
16014 ///checks the 15 afk reports per 5 minutes limit
16015 void Player::UpdateAfkReport(time_t currTime)
16017 if(m_bgAfkReportedTimer <= currTime)
16019 m_bgAfkReportedCount = 0;
16020 m_bgAfkReportedTimer = currTime+5*MINUTE;
16024 void Player::UpdateContestedPvP(uint32 diff)
16026 if(!m_contestedPvPTimer||isInCombat())
16027 return;
16028 if(m_contestedPvPTimer <= diff)
16030 ResetContestedPvP();
16032 else
16033 m_contestedPvPTimer -= diff;
16036 void Player::UpdatePvPFlag(time_t currTime)
16038 if(!IsPvP())
16039 return;
16040 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16041 return;
16043 UpdatePvP(false);
16046 void Player::UpdateDuelFlag(time_t currTime)
16048 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16049 return;
16051 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16052 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16054 duel->startTimer = 0;
16055 duel->startTime = currTime;
16056 duel->opponent->duel->startTimer = 0;
16057 duel->opponent->duel->startTime = currTime;
16060 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16062 if(!pet)
16063 pet = GetPet();
16065 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16067 //returning of reagents only for players, so best done here
16068 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16069 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16071 if(spellInfo)
16073 for(uint32 i = 0; i < 7; ++i)
16075 if(spellInfo->Reagent[i] > 0)
16077 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16078 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16079 if( msg == EQUIP_ERR_OK )
16081 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16082 if(IsInWorld())
16083 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16088 m_temporaryUnsummonedPetNumber = 0;
16091 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16092 return;
16094 // only if current pet in slot
16095 switch(pet->getPetType())
16097 case MINI_PET:
16098 m_miniPet = 0;
16099 break;
16100 case GUARDIAN_PET:
16101 m_guardianPets.erase(pet->GetGUID());
16102 break;
16103 default:
16104 if(GetPetGUID() == pet->GetGUID())
16105 SetPet(NULL);
16106 break;
16109 pet->CombatStop();
16111 if(returnreagent)
16113 switch(pet->GetEntry())
16115 //warlock pets except imp are removed(?) when logging out
16116 case 1860:
16117 case 1863:
16118 case 417:
16119 case 17252:
16120 mode = PET_SAVE_NOT_IN_SLOT;
16121 break;
16125 pet->SavePetToDB(mode);
16127 pet->CleanupsBeforeDelete();
16128 pet->AddObjectToRemoveList();
16129 pet->m_removed = true;
16131 if(pet->isControlled())
16133 WorldPacket data(SMSG_PET_SPELLS, 8+4);
16134 data << uint64(0);
16135 data << uint32(0);
16136 GetSession()->SendPacket(&data);
16138 if(GetGroup())
16139 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16143 void Player::RemoveMiniPet()
16145 if(Pet* pet = GetMiniPet())
16147 pet->Remove(PET_SAVE_AS_DELETED);
16148 m_miniPet = 0;
16152 Pet* Player::GetMiniPet()
16154 if(!m_miniPet)
16155 return NULL;
16156 return ObjectAccessor::GetPet(m_miniPet);
16159 void Player::RemoveGuardians()
16161 while(!m_guardianPets.empty())
16163 uint64 guid = *m_guardianPets.begin();
16164 if(Pet* pet = ObjectAccessor::GetPet(guid))
16165 pet->Remove(PET_SAVE_AS_DELETED);
16167 m_guardianPets.erase(guid);
16171 bool Player::HasGuardianWithEntry(uint32 entry)
16173 // pet guid middle part is entry (and creature also)
16174 // and in guardian list must be guardians with same entry _always_
16175 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16176 if(GUID_ENPART(*itr)==entry)
16177 return true;
16179 return false;
16182 void Player::Uncharm()
16184 Unit* charm = GetCharm();
16185 if(!charm)
16186 return;
16188 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16189 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16192 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16194 *data << (uint8)msgtype;
16195 *data << (uint32)language;
16196 *data << (uint64)GetGUID();
16197 *data << (uint32)language; //language 2.1.0 ?
16198 *data << (uint64)GetGUID();
16199 *data << (uint32)(text.length()+1);
16200 *data << text;
16201 *data << (uint8)chatTag();
16204 void Player::Say(const std::string& text, const uint32 language)
16206 WorldPacket data(SMSG_MESSAGECHAT, 200);
16207 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16208 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16211 void Player::Yell(const std::string& text, const uint32 language)
16213 WorldPacket data(SMSG_MESSAGECHAT, 200);
16214 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16215 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16218 void Player::TextEmote(const std::string& text)
16220 WorldPacket data(SMSG_MESSAGECHAT, 200);
16221 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16222 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16225 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16227 if (language != LANG_ADDON) // if not addon data
16228 language = LANG_UNIVERSAL; // whispers should always be readable
16230 Player *rPlayer = objmgr.GetPlayer(receiver);
16232 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16233 if(!rPlayer->isDND() || isGameMaster())
16235 WorldPacket data(SMSG_MESSAGECHAT, 200);
16236 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16237 rPlayer->GetSession()->SendPacket(&data);
16239 data.Initialize(SMSG_MESSAGECHAT, 200);
16240 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16241 GetSession()->SendPacket(&data);
16243 else
16245 // announce to player that player he is whispering to is dnd and cannot receive his message
16246 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16249 if(!isAcceptWhispers())
16251 SetAcceptWhispers(true);
16252 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16255 // announce to player that player he is whispering to is afk
16256 if(rPlayer->isAFK())
16257 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16259 // if player whisper someone, auto turn of dnd to be able to receive an answer
16260 if(isDND() && !rPlayer->isGameMaster())
16261 ToggleDND();
16264 void Player::PetSpellInitialize()
16266 Pet* pet = GetPet();
16268 if(!pet)
16269 return;
16271 sLog.outDebug("Pet Spells Groups");
16273 CharmInfo *charmInfo = pet->GetCharmInfo();
16275 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16276 data << uint64(pet->GetGUID());
16277 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16278 data << uint32(0);
16279 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16281 // action bar loop
16282 for(uint32 i = 0; i < 10; ++i)
16284 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16287 size_t spellsCountPos = data.wpos();
16289 // spells count
16290 uint8 addlist = 0;
16291 data << uint8(addlist); // placeholder
16293 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16295 // spells loop
16296 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16298 if(itr->second->state == PETSPELL_REMOVED)
16299 continue;
16301 data << uint16(itr->first);
16302 data << uint16(itr->second->active); // pet spell active state isn't boolean
16303 ++addlist;
16307 data.put<uint8>(spellsCountPos, addlist);
16309 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16310 data << uint8(cooldownsCount);
16312 time_t curTime = time(NULL);
16314 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16316 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16318 data << uint16(itr->first); // spellid
16319 data << uint16(0); // spell category?
16320 data << uint32(cooldown); // cooldown
16321 data << uint32(0); // category cooldown
16324 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16326 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16328 data << uint16(itr->first); // spellid
16329 data << uint16(0); // spell category?
16330 data << uint32(0); // cooldown
16331 data << uint32(cooldown); // category cooldown
16334 GetSession()->SendPacket(&data);
16337 void Player::PossessSpellInitialize()
16339 Unit* charm = GetCharm();
16341 if(!charm)
16342 return;
16344 CharmInfo *charmInfo = charm->GetCharmInfo();
16346 if(!charmInfo)
16348 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16349 return;
16352 uint8 addlist = 0;
16353 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16355 //16
16356 data << uint64(charm->GetGUID());
16357 data << uint32(0x00000000);
16358 data << uint32(0);
16359 data << uint32(0);
16361 for(uint32 i = 0; i < 10; ++i) //40
16363 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16366 data << uint8(addlist); //1
16368 uint8 count = 0;
16369 data << uint8(count); // cooldowns count
16371 GetSession()->SendPacket(&data);
16374 void Player::CharmSpellInitialize()
16376 Unit* charm = GetCharm();
16378 if(!charm)
16379 return;
16381 CharmInfo *charmInfo = charm->GetCharmInfo();
16382 if(!charmInfo)
16384 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16385 return;
16388 uint8 addlist = 0;
16390 if(charm->GetTypeId() != TYPEID_PLAYER)
16392 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16394 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16396 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16398 if(charmInfo->GetCharmSpell(i)->spellId)
16399 ++addlist;
16404 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16406 data << uint64(charm->GetGUID());
16407 data << uint32(0x00000000);
16408 data << uint32(0);
16409 if(charm->GetTypeId() != TYPEID_PLAYER)
16410 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16411 else
16412 data << uint8(0) << uint8(0);
16413 data << uint16(0);
16415 for(uint32 i = 0; i < 10; ++i) //40
16417 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16420 data << uint8(addlist); //1
16422 if(addlist)
16424 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16426 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16427 if(cspell->spellId)
16429 data << uint16(cspell->spellId);
16430 data << uint16(cspell->active);
16435 uint8 count = 0;
16436 data << uint8(count); // cooldowns count
16438 GetSession()->SendPacket(&data);
16441 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16443 if (!mod || !spellInfo)
16444 return false;
16446 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16448 // prevent apply to any spell except spell that trigger expire
16449 if(spell)
16451 if(mod->lastAffected != spell)
16452 return false;
16454 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16455 return false;
16458 return spellmgr.IsAffectedByMod(spellInfo, mod);
16461 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16463 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16465 for(int eff=0;eff<96;++eff)
16467 uint64 _mask = 0;
16468 uint64 _mask2= 0;
16469 if (eff<64) _mask = uint64(1) << (eff- 0);
16470 else _mask2= uint64(1) << (eff-64);
16471 if ( mod->mask & _mask || mod->mask2 & _mask2)
16473 int32 val = 0;
16474 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16476 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16477 val += (*itr)->value;
16479 val += apply ? mod->value : -(mod->value);
16480 WorldPacket data(Opcode, (1+1+4));
16481 data << uint8(eff);
16482 data << uint8(mod->op);
16483 data << int32(val);
16484 SendDirectMessage(&data);
16488 if (apply)
16489 m_spellMods[mod->op].push_back(mod);
16490 else
16492 if (mod->charges == -1)
16493 --m_SpellModRemoveCount;
16494 m_spellMods[mod->op].remove(mod);
16495 delete mod;
16499 void Player::RemoveSpellMods(Spell const* spell)
16501 if(!spell || (m_SpellModRemoveCount == 0))
16502 return;
16504 for(int i=0;i<MAX_SPELLMOD;++i)
16506 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16508 SpellModifier *mod = *itr;
16509 ++itr;
16511 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16513 RemoveAurasDueToSpell(mod->spellId);
16514 if (m_spellMods[i].empty())
16515 break;
16516 else
16517 itr = m_spellMods[i].begin();
16523 // send Proficiency
16524 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16526 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16527 data << pr1 << pr2;
16528 GetSession()->SendPacket (&data);
16531 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16533 QueryResult *result = NULL;
16534 if(type==10)
16535 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16536 else
16537 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16538 if(result)
16540 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.
16541 { // and SendPetitionQueryOpcode reads data from the DB
16542 Field *fields = result->Fetch();
16543 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16544 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16546 // send update if charter owner in game
16547 Player* owner = objmgr.GetPlayer(ownerguid);
16548 if(owner)
16549 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16551 } while ( result->NextRow() );
16553 delete result;
16555 if(type==10)
16556 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16557 else
16558 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16561 CharacterDatabase.BeginTransaction();
16562 if(type == 10)
16564 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16565 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16567 else
16569 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16570 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16572 CharacterDatabase.CommitTransaction();
16575 void Player::LeaveAllArenaTeams(uint64 guid)
16577 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));
16578 if(!result)
16579 return;
16583 Field *fields = result->Fetch();
16584 uint32 at_id = fields[0].GetUInt32();
16585 if(at_id != 0)
16587 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16588 if(at)
16589 at->DelMember(guid);
16591 } while (result->NextRow());
16593 delete result;
16596 void Player::SetRestBonus (float rest_bonus_new)
16598 // Prevent resting on max level
16599 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16600 rest_bonus_new = 0;
16602 if(rest_bonus_new < 0)
16603 rest_bonus_new = 0;
16605 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16607 if(rest_bonus_new > rest_bonus_max)
16608 m_rest_bonus = rest_bonus_max;
16609 else
16610 m_rest_bonus = rest_bonus_new;
16612 // update data for client
16613 if(m_rest_bonus>10)
16614 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16615 else if(m_rest_bonus<=1)
16616 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16618 //RestTickUpdate
16619 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16622 void Player::HandleStealthedUnitsDetection()
16624 std::list<Unit*> stealthedUnits;
16626 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16627 Cell cell(p);
16628 cell.data.Part.reserved = ALL_DISTRICT;
16629 cell.SetNoCreate();
16631 MaNGOS::AnyStealthedCheck u_check;
16632 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16634 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16635 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16637 CellLock<GridReadGuard> cell_lock(cell, p);
16638 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16639 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16641 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16643 if((*i)==this)
16645 i = stealthedUnits.erase(i);
16646 continue;
16649 if ((*i)->isVisibleForOrDetect(this,true))
16652 (*i)->SendUpdateToPlayer(this);
16653 m_clientGUIDs.insert((*i)->GetGUID());
16655 #ifdef MANGOS_DEBUG
16656 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16657 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16658 #endif
16660 // target aura duration for caster show only if target exist at caster client
16661 // send data at target visibility change (adding to client)
16662 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16663 SendAurasForTarget(*i);
16665 i = stealthedUnits.erase(i);
16666 continue;
16669 ++i;
16673 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16675 if(nodes.size() < 2)
16676 return false;
16678 // not let cheating with start flight mounted
16679 if(IsMounted())
16681 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16682 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16683 GetSession()->SendPacket(&data);
16684 return false;
16687 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16689 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16690 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16691 GetSession()->SendPacket(&data);
16692 return false;
16695 // 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
16696 if(GetSession()->isLogingOut() ||
16697 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16698 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16699 IsNonMeleeSpellCasted(false) ||
16700 isInCombat())
16702 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16703 data << uint32(ERR_TAXIPLAYERBUSY);
16704 GetSession()->SendPacket(&data);
16705 return false;
16708 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16709 return false;
16711 uint32 sourcenode = nodes[0];
16713 // starting node too far away (cheat?)
16714 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16715 if( !node || node->map_id != GetMapId() ||
16716 (node->x - GetPositionX())*(node->x - GetPositionX())+
16717 (node->y - GetPositionY())*(node->y - GetPositionY())+
16718 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16719 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16721 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16722 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16723 GetSession()->SendPacket(&data);
16724 return false;
16727 // Prepare to flight start now
16729 // stop combat at start taxi flight if any
16730 CombatStop();
16732 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16733 TradeCancel(true);
16735 // clean not finished taxi path if any
16736 m_taxi.ClearTaxiDestinations();
16738 // 0 element current node
16739 m_taxi.AddTaxiDestination(sourcenode);
16741 // fill destinations path tail
16742 uint32 sourcepath = 0;
16743 uint32 totalcost = 0;
16745 uint32 prevnode = sourcenode;
16746 uint32 lastnode = 0;
16748 for(uint32 i = 1; i < nodes.size(); ++i)
16750 uint32 path, cost;
16752 lastnode = nodes[i];
16753 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16755 if(!path)
16757 m_taxi.ClearTaxiDestinations();
16758 return false;
16761 totalcost += cost;
16763 if(prevnode == sourcenode)
16764 sourcepath = path;
16766 m_taxi.AddTaxiDestination(lastnode);
16768 prevnode = lastnode;
16771 if(!mount_id) // if not provide then attempt use default.
16772 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16774 if (mount_id == 0 || sourcepath == 0)
16776 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16777 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16778 GetSession()->SendPacket(&data);
16779 m_taxi.ClearTaxiDestinations();
16780 return false;
16783 uint32 money = GetMoney();
16785 if(npc)
16787 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16790 if(money < totalcost)
16792 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16793 data << uint32(ERR_TAXINOTENOUGHMONEY);
16794 GetSession()->SendPacket(&data);
16795 m_taxi.ClearTaxiDestinations();
16796 return false;
16799 //Checks and preparations done, DO FLIGHT
16800 ModifyMoney(-(int32)totalcost);
16801 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
16803 // prevent stealth flight
16804 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16806 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16807 data << uint32(ERR_TAXIOK);
16808 GetSession()->SendPacket(&data);
16810 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16812 GetSession()->SendDoFlight(mount_id, sourcepath);
16814 return true;
16817 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16819 // last check 2.0.10
16820 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16821 data << GetGUID();
16822 data << uint8(0x0); // flags (0x1, 0x2)
16823 time_t curTime = time(NULL);
16824 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16826 if (itr->second->state == PLAYERSPELL_REMOVED)
16827 continue;
16828 uint32 unSpellId = itr->first;
16829 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16830 if (!spellInfo)
16832 ASSERT(spellInfo);
16833 continue;
16836 // Not send cooldown for this spells
16837 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16838 continue;
16840 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16842 data << unSpellId;
16843 data << unTimeMs; // in m.secs
16844 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
16847 GetSession()->SendPacket(&data);
16850 void Player::InitDataForForm(bool reapplyMods)
16852 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16853 if(ssEntry && ssEntry->attackSpeed)
16855 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16856 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16857 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16859 else
16860 SetRegularAttackTime();
16862 switch(m_form)
16864 case FORM_CAT:
16866 if(getPowerType()!=POWER_ENERGY)
16867 setPowerType(POWER_ENERGY);
16868 break;
16870 case FORM_BEAR:
16871 case FORM_DIREBEAR:
16873 if(getPowerType()!=POWER_RAGE)
16874 setPowerType(POWER_RAGE);
16875 break;
16877 default: // 0, for example
16879 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16880 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16881 setPowerType(Powers(cEntry->powerType));
16882 break;
16886 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16887 if (!reapplyMods)
16888 UpdateEquipSpellsAtFormChange();
16890 UpdateAttackPowerAndDamage();
16891 UpdateAttackPowerAndDamage(true);
16894 // Return true is the bought item has a max count to force refresh of window by caller
16895 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16897 // cheating attempt
16898 if(count < 1) count = 1;
16900 if(!isAlive())
16901 return false;
16903 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16904 if( !pProto )
16906 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16907 return false;
16910 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
16911 if (!pCreature)
16913 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16914 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16915 return false;
16918 VendorItemData const* vItems = pCreature->GetVendorItems();
16919 if(!vItems || vItems->Empty())
16921 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16922 return false;
16925 size_t vendor_slot = vItems->FindItemSlot(item);
16926 if(vendor_slot >= vItems->GetItemCount())
16928 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16929 return false;
16932 VendorItem const* crItem = vItems->m_items[vendor_slot];
16934 // check current item amount if it limited
16935 if( crItem->maxcount != 0 )
16937 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16939 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16940 return false;
16944 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16946 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16947 return false;
16950 if(crItem->ExtendedCost)
16952 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16953 if(!iece)
16955 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16956 return false;
16959 // honor points price
16960 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16962 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16963 return false;
16966 // arena points price
16967 if(GetArenaPoints() < (iece->reqarenapoints * count))
16969 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16970 return false;
16973 // item base price
16974 for (uint8 i = 0; i < 5; ++i)
16976 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
16978 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
16979 return false;
16983 // check for personal arena rating requirement
16984 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
16986 // probably not the proper equip err
16987 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
16988 return false;
16992 uint32 price = pProto->BuyPrice * count;
16994 // reputation discount
16995 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
16997 if( GetMoney() < price )
16999 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17000 return false;
17003 uint8 bag = 0; // init for case invalid bagGUID
17005 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17007 Bag *pBag;
17008 if( bagguid == GetGUID() )
17010 bag = INVENTORY_SLOT_BAG_0;
17012 else
17014 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;++i)
17016 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17017 if( pBag )
17019 if( bagguid == pBag->GetGUID() )
17021 bag = i;
17022 break;
17029 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17031 ItemPosCountVec dest;
17032 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17033 if( msg != EQUIP_ERR_OK )
17035 SendEquipError( msg, NULL, NULL );
17036 return false;
17039 ModifyMoney( -(int32)price );
17040 if(crItem->ExtendedCost) // case for new honor system
17042 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17043 if(iece->reqhonorpoints)
17044 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17045 if(iece->reqarenapoints)
17046 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17047 for (uint8 i = 0; i < 5; ++i)
17049 if(iece->reqitem[i])
17050 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17054 if(Item *it = StoreNewItem( dest, item, true ))
17056 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17058 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17059 data << pCreature->GetGUID();
17060 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17061 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17062 data << (uint32)count;
17063 GetSession()->SendPacket(&data);
17065 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17068 else if( IsEquipmentPos( bag, slot ) )
17070 if(pProto->BuyCount * count != 1)
17072 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17073 return false;
17076 uint16 dest;
17077 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17078 if( msg != EQUIP_ERR_OK )
17080 SendEquipError( msg, NULL, NULL );
17081 return false;
17084 ModifyMoney( -(int32)price );
17085 if(crItem->ExtendedCost) // case for new honor system
17087 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17088 if(iece->reqhonorpoints)
17089 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17090 if(iece->reqarenapoints)
17091 ModifyArenaPoints( - int32(iece->reqarenapoints));
17092 for (uint8 i = 0; i < 5; ++i)
17094 if(iece->reqitem[i])
17095 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17099 if(Item *it = EquipNewItem( dest, item, true ))
17101 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17103 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17104 data << pCreature->GetGUID();
17105 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17106 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17107 data << (uint32)count;
17108 GetSession()->SendPacket(&data);
17110 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17112 AutoUnequipOffhandIfNeed();
17115 else
17117 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17118 return false;
17121 return crItem->maxcount!=0;
17124 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17126 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17127 // the personal rating of the arena team must match the required limit as well
17128 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17129 uint32 max_personal_rating = 0;
17130 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17132 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17134 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17135 uint32 t_rating = at->GetRating();
17136 p_rating = p_rating<t_rating? p_rating : t_rating;
17137 if(max_personal_rating < p_rating)
17138 max_personal_rating = p_rating;
17141 return max_personal_rating;
17144 void Player::UpdateHomebindTime(uint32 time)
17146 // GMs never get homebind timer online
17147 if (m_InstanceValid || isGameMaster())
17149 if(m_HomebindTimer) // instance valid, but timer not reset
17151 // hide reminder
17152 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17153 data << uint32(0);
17154 data << uint32(0);
17155 GetSession()->SendPacket(&data);
17157 // instance is valid, reset homebind timer
17158 m_HomebindTimer = 0;
17160 else if (m_HomebindTimer > 0)
17162 if (time >= m_HomebindTimer)
17164 // teleport to homebind location
17165 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17167 else
17168 m_HomebindTimer -= time;
17170 else
17172 // instance is invalid, start homebind timer
17173 m_HomebindTimer = 60000;
17174 // send message to player
17175 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17176 data << m_HomebindTimer;
17177 data << uint32(1);
17178 GetSession()->SendPacket(&data);
17179 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17183 void Player::UpdatePvP(bool state, bool ovrride)
17185 if(!state || ovrride)
17187 SetPvP(state);
17188 if(Pet* pet = GetPet())
17189 pet->SetPvP(state);
17190 if(Unit* charmed = GetCharm())
17191 charmed->SetPvP(state);
17193 pvpInfo.endTimer = 0;
17195 else
17197 if(pvpInfo.endTimer != 0)
17198 pvpInfo.endTimer = time(NULL);
17199 else
17201 SetPvP(state);
17203 if(Pet* pet = GetPet())
17204 pet->SetPvP(state);
17205 if(Unit* charmed = GetCharm())
17206 charmed->SetPvP(state);
17211 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17213 // init cooldown values
17214 uint32 cat = 0;
17215 int32 rec = -1;
17216 int32 catrec = -1;
17218 // some special item spells without correct cooldown in SpellInfo
17219 // cooldown information stored in item prototype
17220 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17222 if(itemId)
17224 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17226 for(int idx = 0; idx < 5; ++idx)
17228 if(proto->Spells[idx].SpellId == spellInfo->Id)
17230 cat = proto->Spells[idx].SpellCategory;
17231 rec = proto->Spells[idx].SpellCooldown;
17232 catrec = proto->Spells[idx].SpellCategoryCooldown;
17233 break;
17239 // if no cooldown found above then base at DBC data
17240 if(rec < 0 && catrec < 0)
17242 cat = spellInfo->Category;
17243 rec = spellInfo->RecoveryTime;
17244 catrec = spellInfo->CategoryRecoveryTime;
17247 time_t curTime = time(NULL);
17249 time_t catrecTime;
17250 time_t recTime;
17252 // overwrite time for selected category
17253 if(infinityCooldown)
17255 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17256 // but not allow ignore until reset or re-login
17257 catrecTime = catrec > 0 ? curTime+MONTH : 0;
17258 recTime = rec > 0 ? curTime+MONTH : catrecTime;
17260 else
17262 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17263 // prevent 0 cooldowns set by another way
17264 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17265 rec = GetAttackTime(RANGED_ATTACK);
17267 // Now we have cooldown data (if found any), time to apply mods
17268 if(rec > 0)
17269 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17271 if(catrec > 0)
17272 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17274 // replace negative cooldowns by 0
17275 if (rec < 0) rec = 0;
17276 if (catrec < 0) catrec = 0;
17278 // no cooldown after applying spell mods
17279 if( rec == 0 && catrec == 0)
17280 return;
17282 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17283 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17286 // self spell cooldown
17287 if(recTime > 0)
17288 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17290 // category spells
17291 if (cat && catrec > 0)
17293 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17294 if(i_scstore != sSpellCategoryStore.end())
17296 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17298 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17299 continue;
17301 AddSpellCooldown(*i_scset, itemId, catrecTime);
17307 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17309 SpellCooldown sc;
17310 sc.end = end_time;
17311 sc.itemid = itemid;
17312 m_spellCooldowns[spellid] = sc;
17315 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17317 // start cooldowns at server side, if any
17318 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17320 // Send activate cooldown timer (possible 0) at client side
17321 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17322 data << spellInfo->Id;
17323 data << GetGUID();
17324 SendDirectMessage(&data);
17327 void Player::UpdatePotionCooldown(Spell* spell)
17329 // no potion used i combat or still in combat
17330 if(!m_lastPotionId || isInCombat())
17331 return;
17333 // Call not from spell cast, send cooldown event for item spells if no in combat
17334 if(!spell)
17336 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17337 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17338 for(int idx = 0; idx < 5; ++idx)
17339 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17340 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17341 SendCooldownEvent(spellInfo,m_lastPotionId);
17343 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17344 else
17345 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17347 m_lastPotionId = 0;
17350 //slot to be excluded while counting
17351 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17353 if(!enchantmentcondition)
17354 return true;
17356 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17358 if(!Condition)
17359 return true;
17361 uint8 curcount[4] = {0, 0, 0, 0};
17363 //counting current equipped gem colors
17364 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17366 if(i == slot)
17367 continue;
17368 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17369 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17371 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17373 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17374 if(!enchant_id)
17375 continue;
17377 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17378 if(!enchantEntry)
17379 continue;
17381 uint32 gemid = enchantEntry->GemID;
17382 if(!gemid)
17383 continue;
17385 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17386 if(!gemProto)
17387 continue;
17389 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17390 if(!gemProperty)
17391 continue;
17393 uint8 GemColor = gemProperty->color;
17395 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17397 if(tmpcolormask & GemColor)
17398 ++curcount[b];
17404 bool activate = true;
17406 for(int i = 0; i < 5; ++i)
17408 if(!Condition->Color[i])
17409 continue;
17411 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17413 // if have <CompareColor> use them as count, else use <value> from Condition
17414 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17416 switch(Condition->Comparator[i])
17418 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17419 activate &= (_cur_gem < _cmp_gem) ? true : false;
17420 break;
17421 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17422 activate &= (_cur_gem > _cmp_gem) ? true : false;
17423 break;
17424 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17425 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17426 break;
17430 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");
17432 return activate;
17435 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17437 //cycle all equipped items
17438 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17440 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17441 if(slot == exceptslot)
17442 continue;
17444 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17446 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17447 continue;
17449 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17451 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17452 if(!enchant_id)
17453 continue;
17455 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17456 if(!enchantEntry)
17457 continue;
17459 uint32 condition = enchantEntry->EnchantmentCondition;
17460 if(condition)
17462 //was enchant active with/without item?
17463 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17464 //should it now be?
17465 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17467 // ignore item gem conditions
17468 //if state changed, (dis)apply enchant
17469 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17476 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17477 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17479 //cycle all equipped items
17480 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17482 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17483 if(slot == exceptslot)
17484 continue;
17486 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17488 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17489 continue;
17491 //cycle all (gem)enchants
17492 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17494 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17495 if(!enchant_id) //if no enchant go to next enchant(slot)
17496 continue;
17498 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17499 if(!enchantEntry)
17500 continue;
17502 //only metagems to be (de)activated, so only enchants with condition
17503 uint32 condition = enchantEntry->EnchantmentCondition;
17504 if(condition)
17505 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17510 void Player::LeaveBattleground(bool teleportToEntryPoint)
17512 if(BattleGround *bg = GetBattleGround())
17514 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17516 // call after remove to be sure that player resurrected for correct cast
17517 if( bg->isBattleGround() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17519 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17520 CastSpell(this, 26013, true); // Deserter
17525 bool Player::CanJoinToBattleground() const
17527 // check Deserter debuff
17528 if(GetDummyAura(26013))
17529 return false;
17531 return true;
17534 bool Player::CanReportAfkDueToLimit()
17536 // a player can complain about 15 people per 5 minutes
17537 if(m_bgAfkReportedCount >= 15)
17538 return false;
17539 ++m_bgAfkReportedCount;
17540 return true;
17543 ///This player has been blamed to be inactive in a battleground
17544 void Player::ReportedAfkBy(Player* reporter)
17546 BattleGround *bg = GetBattleGround();
17547 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17548 return;
17550 // check if player has 'Idle' or 'Inactive' debuff
17551 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17553 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17554 // 3 players have to complain to apply debuff
17555 if(m_bgAfkReporter.size() >= 3)
17557 // cast 'Idle' spell
17558 CastSpell(this, 43680, true);
17559 m_bgAfkReporter.clear();
17564 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17566 // gamemaster in GM mode see all, including ghosts
17567 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17568 return true;
17570 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17571 if (InBattleGround())
17573 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17574 return false;
17575 return true;
17578 // Live player see live player or dead player with not realized corpse
17579 if(pl->isAlive() || pl->m_deathTimer > 0)
17581 return isAlive() || m_deathTimer > 0;
17584 // Ghost see other friendly ghosts, that's for sure
17585 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17586 return true;
17588 // Dead player see live players near own corpse
17589 if(isAlive())
17591 Corpse *corpse = pl->GetCorpse();
17592 if(corpse)
17594 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17595 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17596 return true;
17600 // and not see any other
17601 return false;
17604 bool Player::IsVisibleGloballyFor( Player* u ) const
17606 if(!u)
17607 return false;
17609 // Always can see self
17610 if (u==this)
17611 return true;
17613 // Visible units, always are visible for all players
17614 if (GetVisibility() == VISIBILITY_ON)
17615 return true;
17617 // GMs are visible for higher gms (or players are visible for gms)
17618 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17619 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17621 // non faction visibility non-breakable for non-GMs
17622 if (GetVisibility() == VISIBILITY_OFF)
17623 return false;
17625 // non-gm stealth/invisibility not hide from global player lists
17626 return true;
17629 void Player::UpdateVisibilityOf(WorldObject* target)
17631 if(HaveAtClient(target))
17633 if(!target->isVisibleForInState(this,true))
17635 target->DestroyForPlayer(this);
17636 m_clientGUIDs.erase(target->GetGUID());
17638 #ifdef MANGOS_DEBUG
17639 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17640 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17641 #endif
17644 else
17646 if(target->isVisibleForInState(this,false))
17648 target->SendUpdateToPlayer(this);
17649 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17650 m_clientGUIDs.insert(target->GetGUID());
17652 #ifdef MANGOS_DEBUG
17653 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17654 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17655 #endif
17657 // target aura duration for caster show only if target exist at caster client
17658 // send data at target visibility change (adding to client)
17659 if(target!=this && target->isType(TYPEMASK_UNIT))
17660 SendAurasForTarget((Unit*)target);
17662 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17663 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17668 template<class T>
17669 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17671 s64.insert(target->GetGUID());
17674 template<>
17675 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17677 if(!target->IsTransport())
17678 s64.insert(target->GetGUID());
17681 template<class T>
17682 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17684 if(HaveAtClient(target))
17686 if(!target->isVisibleForInState(this,true))
17688 target->BuildOutOfRangeUpdateBlock(&data);
17689 m_clientGUIDs.erase(target->GetGUID());
17691 #ifdef MANGOS_DEBUG
17692 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17693 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));
17694 #endif
17697 else
17699 if(target->isVisibleForInState(this,false))
17701 visibleNow.insert(target);
17702 target->BuildUpdate(data_updates);
17703 target->BuildCreateUpdateBlockForPlayer(&data, this);
17704 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17706 #ifdef MANGOS_DEBUG
17707 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17708 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));
17709 #endif
17714 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17715 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17716 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17717 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17718 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17720 void Player::InitPrimaryProffesions()
17722 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17725 void Player::SendComboPoints()
17727 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17728 if (combotarget)
17730 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17731 data.append(combotarget->GetPackGUID());
17732 data << uint8(m_comboPoints);
17733 GetSession()->SendPacket(&data);
17737 void Player::AddComboPoints(Unit* target, int8 count)
17739 if(!count)
17740 return;
17742 // without combo points lost (duration checked in aura)
17743 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17745 if(target->GetGUID() == m_comboTarget)
17747 m_comboPoints += count;
17749 else
17751 if(m_comboTarget)
17752 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
17753 target2->RemoveComboPointHolder(GetGUIDLow());
17755 m_comboTarget = target->GetGUID();
17756 m_comboPoints = count;
17758 target->AddComboPointHolder(GetGUIDLow());
17761 if (m_comboPoints > 5) m_comboPoints = 5;
17762 if (m_comboPoints < 0) m_comboPoints = 0;
17764 SendComboPoints();
17767 void Player::ClearComboPoints()
17769 if(!m_comboTarget)
17770 return;
17772 // without combopoints lost (duration checked in aura)
17773 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17775 m_comboPoints = 0;
17777 SendComboPoints();
17779 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17780 target->RemoveComboPointHolder(GetGUIDLow());
17782 m_comboTarget = 0;
17785 void Player::SetGroup(Group *group, int8 subgroup)
17787 if(group == NULL)
17788 m_group.unlink();
17789 else
17791 // never use SetGroup without a subgroup unless you specify NULL for group
17792 assert(subgroup >= 0);
17793 m_group.link(group, this);
17794 m_group.setSubGroup((uint8)subgroup);
17798 void Player::SendInitialPacketsBeforeAddToMap()
17800 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17801 data << uint32(0); // unknown, may be rest state time or experience
17802 GetSession()->SendPacket(&data);
17804 // Homebind
17805 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17806 data << m_homebindX << m_homebindY << m_homebindZ;
17807 data << (uint32) m_homebindMapId;
17808 data << (uint32) m_homebindZoneId;
17809 GetSession()->SendPacket(&data);
17811 // SMSG_SET_PROFICIENCY
17812 // SMSG_UPDATE_AURA_DURATION
17814 // tutorial stuff
17815 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17816 for (int i = 0; i < 8; ++i)
17817 data << uint32( GetTutorialInt(i) );
17818 GetSession()->SendPacket(&data);
17820 SendInitialSpells();
17822 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17823 data << uint32(0); // count, for(count) uint32;
17824 GetSession()->SendPacket(&data);
17826 SendInitialActionButtons();
17827 m_reputationMgr.SendInitialReputations();
17828 m_achievementMgr.SendAllAchievementData();
17830 // update zone
17831 uint32 newzone, newarea;
17832 GetZoneAndAreaId(newzone,newarea);
17833 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
17835 // SMSG_SET_AURA_SINGLE
17837 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17838 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17839 data << (float)0.01666667f; // game speed
17840 GetSession()->SendPacket( &data );
17842 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17843 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17844 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17846 m_mover = this;
17849 void Player::SendInitialPacketsAfterAddToMap()
17851 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17852 data << uint32(0x00000000); // on blizz it increments periodically
17853 GetSession()->SendPacket(&data);
17855 CastSpell(this, 836, true); // LOGINEFFECT
17857 // set some aura effects that send packet to player client after add player to map
17858 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17859 // same auras state lost at far teleport, send it one more time in this case also
17860 static const AuraType auratypes[] =
17862 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17863 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17864 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17866 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17868 Unit::AuraList const& auraList = GetAurasByType(*itr);
17869 if(!auraList.empty())
17870 auraList.front()->ApplyModifier(true,true);
17873 if(HasAuraType(SPELL_AURA_MOD_STUN))
17874 SetMovement(MOVE_ROOT);
17876 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17877 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17879 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
17880 data2.append(GetPackGUID());
17881 data2 << (uint32)2;
17882 SendMessageToSet(&data2,true);
17885 SendAurasForTarget(this);
17886 SendEnchantmentDurations(); // must be after add to map
17887 SendItemDurations(); // must be after add to map
17890 void Player::SendUpdateToOutOfRangeGroupMembers()
17892 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17893 return;
17894 if(Group* group = GetGroup())
17895 group->UpdatePlayerOutOfRange(this);
17897 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17898 m_auraUpdateMask = 0;
17899 if(Pet *pet = GetPet())
17900 pet->ResetAuraUpdateMask();
17903 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17905 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17906 data << uint32(mapid);
17907 data << uint8(reason); // transfer abort reason
17908 switch(reason)
17910 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17911 case TRANSFER_ABORT_DIFFICULTY:
17912 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17913 data << uint8(arg);
17914 break;
17916 GetSession()->SendPacket(&data);
17919 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17921 // type of warning, based on the time remaining until reset
17922 uint32 type;
17923 if(time > 3600)
17924 type = RAID_INSTANCE_WELCOME;
17925 else if(time > 900 && time <= 3600)
17926 type = RAID_INSTANCE_WARNING_HOURS;
17927 else if(time > 300 && time <= 900)
17928 type = RAID_INSTANCE_WARNING_MIN;
17929 else
17930 type = RAID_INSTANCE_WARNING_MIN_SOON;
17931 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17932 data << uint32(type);
17933 data << uint32(mapid);
17934 data << uint32(time);
17935 GetSession()->SendPacket(&data);
17938 void Player::ApplyEquipCooldown( Item * pItem )
17940 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
17942 _Spell const& spellData = pItem->GetProto()->Spells[i];
17944 // no spell
17945 if( !spellData.SpellId )
17946 continue;
17948 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17949 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17950 continue;
17952 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17954 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17955 data << pItem->GetGUID();
17956 data << uint32(spellData.SpellId);
17957 GetSession()->SendPacket(&data);
17961 void Player::resetSpells()
17963 // not need after this call
17964 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17966 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17967 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17970 // make full copy of map (spells removed and marked as deleted at another spell remove
17971 // and we can't use original map for safe iterative with visit each spell at loop end
17972 PlayerSpellMap smap = GetSpellMap();
17974 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17975 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17977 learnDefaultSpells();
17978 learnQuestRewardedSpells();
17981 void Player::learnDefaultSpells()
17983 // learn default race/class spells
17984 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17985 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
17987 uint32 tspell = *itr;
17988 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
17989 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
17990 addSpell(tspell,true,true,true,false);
17991 else // but send in normal spell in game learn case
17992 learnSpell(tspell,true);
17996 void Player::learnQuestRewardedSpells(Quest const* quest)
17998 uint32 spell_id = quest->GetRewSpellCast();
18000 // skip quests without rewarded spell
18001 if( !spell_id )
18002 return;
18004 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18005 if(!spellInfo)
18006 return;
18008 // check learned spells state
18009 bool found = false;
18010 for(int i=0; i < 3; ++i)
18012 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18014 found = true;
18015 break;
18019 // skip quests with not teaching spell or already known spell
18020 if(!found)
18021 return;
18023 // prevent learn non first rank unknown profession and second specialization for same profession)
18024 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18025 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18027 // not have first rank learned (unlearned prof?)
18028 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18029 if( !HasSpell(first_spell) )
18030 return;
18032 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18033 if(!learnedInfo)
18034 return;
18036 // specialization
18037 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18039 // search other specialization for same prof
18040 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18042 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18043 continue;
18045 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18046 if(!itrInfo)
18047 return;
18049 // compare only specializations
18050 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18051 continue;
18053 // compare same chain spells
18054 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18055 continue;
18057 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18058 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18059 return;
18064 CastSpell( this, spell_id, true);
18067 void Player::learnQuestRewardedSpells()
18069 // learn spells received from quest completing
18070 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18072 // skip no rewarded quests
18073 if(!itr->second.m_rewarded)
18074 continue;
18076 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18077 if( !quest )
18078 continue;
18080 learnQuestRewardedSpells(quest);
18084 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18086 uint32 raceMask = getRaceMask();
18087 uint32 classMask = getClassMask();
18088 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18090 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18091 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18092 continue;
18093 // Check race if set
18094 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18095 continue;
18096 // Check class if set
18097 if (pAbility->classmask && !(pAbility->classmask & classMask))
18098 continue;
18100 if (sSpellStore.LookupEntry(pAbility->spellId))
18102 // need unlearn spell
18103 if (skill_value < pAbility->req_skill_value)
18104 removeSpell(pAbility->spellId);
18105 // need learn
18106 else if (!IsInWorld())
18107 addSpell(pAbility->spellId,true,true,true,false);
18108 else
18109 learnSpell(pAbility->spellId,true);
18114 void Player::SendAurasForTarget(Unit *target)
18116 if(target->GetVisibleAuras()->empty()) // speedup things
18117 return;
18119 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18120 data.append(target->GetPackGUID());
18122 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18123 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18125 for(uint32 j = 0; j < 3; ++j)
18127 if(Aura *aura = target->GetAura(itr->second, j))
18129 data << uint8(aura->GetAuraSlot());
18130 data << uint32(aura->GetId());
18132 if(aura->GetId())
18134 uint8 auraFlags = aura->GetAuraFlags();
18135 // flags
18136 data << uint8(auraFlags);
18137 // level
18138 data << uint8(aura->GetAuraLevel());
18139 // charges
18140 data << uint8(aura->GetAuraCharges());
18142 if(!(auraFlags & AFLAG_NOT_CASTER))
18144 data << uint8(0); // packed GUID of someone (caster?)
18147 if(auraFlags & AFLAG_DURATION) // include aura duration
18149 data << uint32(aura->GetAuraMaxDuration());
18150 data << uint32(aura->GetAuraDuration());
18153 break;
18158 GetSession()->SendPacket(&data);
18161 void Player::SetDailyQuestStatus( uint32 quest_id )
18163 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18165 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18167 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18168 m_lastDailyQuestTime = time(NULL); // last daily quest time
18169 m_DailyQuestChanged = true;
18170 break;
18175 void Player::ResetDailyQuestStatus()
18177 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18178 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18180 // DB data deleted in caller
18181 m_DailyQuestChanged = false;
18182 m_lastDailyQuestTime = 0;
18185 BattleGround* Player::GetBattleGround() const
18187 if(GetBattleGroundId()==0)
18188 return NULL;
18190 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
18193 bool Player::InArena() const
18195 BattleGround *bg = GetBattleGround();
18196 if(!bg || !bg->isArena())
18197 return false;
18199 return true;
18202 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18204 // get a template bg instead of running one
18205 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18206 if(!bg)
18207 return false;
18209 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18210 return false;
18212 return true;
18215 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18217 //returned to hardcoded version of this function, because there is no way to code it dynamic
18218 uint32 level = getLevel();
18219 if( bgTypeId == BATTLEGROUND_AV )
18220 level--;
18222 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18223 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18225 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18226 return QUEUE_ID_MAX_LEVEL_80;
18228 return BGQueueIdBasedOnLevel(queue_id);
18231 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18233 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18234 if(!vendor_faction || !vendor_faction->faction)
18235 return 1.0f;
18237 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18238 if(rank <= REP_NEUTRAL)
18239 return 1.0f;
18241 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18244 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18246 uint32 racemask = getRaceMask();
18247 uint32 classmask = getClassMask();
18249 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18250 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18251 if(lower==upper)
18252 return true;
18254 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18256 // skip wrong race skills
18257 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18258 continue;
18260 // skip wrong class skills
18261 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18262 continue;
18264 return true;
18267 return false;
18270 bool Player::HasQuestForGO(int32 GOId) const
18272 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18274 uint32 questid = GetQuestSlotQuestId(i);
18275 if ( questid == 0 )
18276 continue;
18278 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18279 if(qs_itr == mQuestStatus.end())
18280 continue;
18282 QuestStatusData const& qs = qs_itr->second;
18284 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18286 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18287 if(!qinfo)
18288 continue;
18290 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18291 continue;
18293 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
18295 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18296 continue;
18298 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18299 return true;
18303 return false;
18306 void Player::UpdateForQuestsGO()
18308 if(m_clientGUIDs.empty())
18309 return;
18311 UpdateData udata;
18312 WorldPacket packet;
18313 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18315 if(IS_GAMEOBJECT_GUID(*itr))
18317 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18318 if(obj)
18319 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18322 udata.BuildPacket(&packet);
18323 GetSession()->SendPacket(&packet);
18326 void Player::SummonIfPossible(bool agree)
18328 if(!agree)
18330 m_summon_expire = 0;
18331 return;
18334 // expire and auto declined
18335 if(m_summon_expire < time(NULL))
18336 return;
18338 // stop taxi flight at summon
18339 if(isInFlight())
18341 GetMotionMaster()->MovementExpired();
18342 m_taxi.ClearTaxiDestinations();
18345 // drop flag at summon
18346 // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
18347 if(BattleGround *bg = GetBattleGround())
18348 bg->EventPlayerDroppedFlag(this);
18350 m_summon_expire = 0;
18352 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18355 void Player::RemoveItemDurations( Item *item )
18357 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18359 if(*itr==item)
18361 m_itemDuration.erase(itr);
18362 break;
18367 void Player::AddItemDurations( Item *item )
18369 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18371 m_itemDuration.push_back(item);
18372 item->SendTimeUpdate(this);
18376 void Player::AutoUnequipOffhandIfNeed()
18378 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18379 if(!offItem)
18380 return;
18382 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18383 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18384 return;
18386 ItemPosCountVec off_dest;
18387 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18388 if( off_msg == EQUIP_ERR_OK )
18390 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18391 StoreItem( off_dest, offItem, true );
18393 else
18395 MailItemsInfo mi;
18396 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18397 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18398 CharacterDatabase.BeginTransaction();
18399 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18400 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18401 CharacterDatabase.CommitTransaction();
18403 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18404 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18408 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18410 if(spellInfo->EquippedItemClass < 0)
18411 return true;
18413 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18414 // for optimize check 2 used cases only
18415 switch(spellInfo->EquippedItemClass)
18417 case ITEM_CLASS_WEAPON:
18419 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18420 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18421 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18422 return true;
18423 break;
18425 case ITEM_CLASS_ARMOR:
18427 // tabard not have dependent spells
18428 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18429 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18430 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18431 return true;
18433 // shields can be equipped to offhand slot
18434 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18435 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18436 return true;
18438 // ranged slot can have some armor subclasses
18439 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18440 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18441 return true;
18443 break;
18445 default:
18446 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18447 break;
18450 return false;
18453 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18455 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18456 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18457 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18458 return true;
18460 // Check no reagent use mask
18461 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18462 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18463 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18464 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18465 return true;
18467 return false;
18470 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18472 AuraMap& auras = GetAuras();
18473 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
18475 Aura* aura = itr->second;
18477 // skip passive (passive item dependent spells work in another way) and not self applied auras
18478 SpellEntry const* spellInfo = aura->GetSpellProto();
18479 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18481 ++itr;
18482 continue;
18485 // skip if not item dependent or have alternative item
18486 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18488 ++itr;
18489 continue;
18492 // no alt item, remove aura, restart check
18493 RemoveAurasDueToSpell(aura->GetId());
18494 itr = auras.begin();
18497 // currently casted spells can be dependent from item
18498 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
18500 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18501 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18502 InterruptSpell(i);
18506 uint32 Player::GetResurrectionSpellId()
18508 // search priceless resurrection possibilities
18509 uint32 prio = 0;
18510 uint32 spell_id = 0;
18511 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18512 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18514 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18515 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18517 switch((*itr)->GetId())
18519 case 20707: spell_id = 3026; break; // rank 1
18520 case 20762: spell_id = 20758; break; // rank 2
18521 case 20763: spell_id = 20759; break; // rank 3
18522 case 20764: spell_id = 20760; break; // rank 4
18523 case 20765: spell_id = 20761; break; // rank 5
18524 case 27239: spell_id = 27240; break; // rank 6
18525 case 47883: spell_id = 47882; break; // rank 7
18526 default:
18527 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
18528 continue;
18531 prio = 3;
18533 // Twisting Nether // prio: 2 (max)
18534 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18536 prio = 2;
18537 spell_id = 23700;
18541 // Reincarnation (passive spell) // prio: 1
18542 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18543 spell_id = 21169;
18545 return spell_id;
18548 // Used in triggers for check "Only to targets that grant experience or honor" req
18549 bool Player::isHonorOrXPTarget(Unit* pVictim)
18551 uint32 v_level = pVictim->getLevel();
18552 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18554 // Victim level less gray level
18555 if(v_level<=k_grey)
18556 return false;
18558 if(pVictim->GetTypeId() == TYPEID_UNIT)
18560 if (((Creature*)pVictim)->isTotem() ||
18561 ((Creature*)pVictim)->isPet() ||
18562 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18563 return false;
18565 return true;
18568 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18570 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18572 // prepare data for near group iteration (PvP and !PvP cases)
18573 uint32 xp = 0;
18574 bool honored_kill = false;
18576 if(Group *pGroup = GetGroup())
18578 uint32 count = 0;
18579 uint32 sum_level = 0;
18580 Player* member_with_max_level = NULL;
18581 Player* not_gray_member_with_max_level = NULL;
18583 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18585 if(member_with_max_level)
18587 /// not get Xp in PvP or no not gray players in group
18588 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18590 /// skip in check PvP case (for speed, not used)
18591 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18592 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18593 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18595 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18597 Player* pGroupGuy = itr->getSource();
18598 if(!pGroupGuy)
18599 continue;
18601 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18602 continue; // member (alive or dead) or his corpse at req. distance
18604 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18605 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18606 honored_kill = true;
18608 // xp and reputation only in !PvP case
18609 if(!PvP)
18611 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18613 // if is in dungeon then all receive full reputation at kill
18614 // rewarded any alive/dead/near_corpse group member
18615 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18617 // XP updated only for alive group member
18618 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18619 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18621 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18623 pGroupGuy->GiveXP(itr_xp, pVictim);
18624 if(Pet* pet = pGroupGuy->GetPet())
18625 pet->GivePetXP(itr_xp/2);
18628 // quest objectives updated only for alive group member or dead but with not released body
18629 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18631 // normal creature (not pet/etc) can be only in !PvP case
18632 if(pVictim->GetTypeId()==TYPEID_UNIT)
18633 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18639 else // if (!pGroup)
18641 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18643 // honor can be in PvP and !PvP (racial leader) cases
18644 if(RewardHonor(pVictim,1))
18645 honored_kill = true;
18647 // xp and reputation only in !PvP case
18648 if(!PvP)
18650 RewardReputation(pVictim,1);
18651 GiveXP(xp, pVictim);
18653 if(Pet* pet = GetPet())
18654 pet->GivePetXP(xp);
18656 // normal creature (not pet/etc) can be only in !PvP case
18657 if(pVictim->GetTypeId()==TYPEID_UNIT)
18658 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18661 return xp || honored_kill;
18664 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
18666 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
18668 // prepare data for near group iteration
18669 if(Group *pGroup = GetGroup())
18671 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18673 Player* pGroupGuy = itr->getSource();
18674 if(!pGroupGuy)
18675 continue;
18677 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
18678 continue; // member (alive or dead) or his corpse at req. distance
18680 // quest objectives updated only for alive group member or dead but with not released body
18681 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18682 pGroupGuy->KilledMonster(creature_id, creature_guid);
18685 else // if (!pGroup)
18686 KilledMonster(creature_id, creature_guid);
18689 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18691 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
18692 return true;
18694 if(isAlive())
18695 return false;
18697 Corpse* corpse = GetCorpse();
18698 if(!corpse)
18699 return false;
18701 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
18704 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18706 Item* item = GetWeaponForAttack(attType,true);
18708 // unarmed only with base attack
18709 if(attType != BASE_ATTACK && !item)
18710 return 0;
18712 // weapon skill or (unarmed for base attack)
18713 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
18714 return GetBaseSkillValue(skill);
18717 void Player::ResurectUsingRequestData()
18719 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18720 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18722 ResurrectPlayer(0.0f,false);
18724 if(GetMaxHealth() > m_resurrectHealth)
18725 SetHealth( m_resurrectHealth );
18726 else
18727 SetHealth( GetMaxHealth() );
18729 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18730 SetPower(POWER_MANA, m_resurrectMana );
18731 else
18732 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18734 SetPower(POWER_RAGE, 0 );
18736 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18738 SpawnCorpseBones();
18741 void Player::SetClientControl(Unit* target, uint8 allowMove)
18743 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18744 data.append(target->GetPackGUID());
18745 data << uint8(allowMove);
18746 GetSession()->SendPacket(&data);
18749 void Player::UpdateZoneDependentAuras( uint32 newZone )
18751 // remove new continent flight forms
18752 if( !IsAllowUseFlyMountsHere() )
18754 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18755 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18758 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18759 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
18760 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18761 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
18762 if( !HasAura(itr->second->spellId,0) )
18763 CastSpell(this,itr->second->spellId,true);
18766 void Player::UpdateAreaDependentAuras( uint32 newArea )
18768 // remove auras from spells with area limitations
18769 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18771 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18772 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
18773 RemoveAura(iter);
18774 else
18775 ++iter;
18778 // some auras applied at subzone enter
18779 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
18780 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18781 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
18782 if( !HasAura(itr->second->spellId,0) )
18783 CastSpell(this,itr->second->spellId,true);
18786 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18788 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18789 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18791 return copseReclaimDelay[0];
18794 time_t now = time(NULL);
18795 // 0..2 full period
18796 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18797 return copseReclaimDelay[count];
18800 void Player::UpdateCorpseReclaimDelay()
18802 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18804 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18805 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18806 return;
18808 time_t now = time(NULL);
18809 if(now < m_deathExpireTime)
18811 // full and partly periods 1..3
18812 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18813 if(count < MAX_DEATH_COUNT)
18814 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18815 else
18816 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18818 else
18819 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18822 void Player::SendCorpseReclaimDelay(bool load)
18824 Corpse* corpse = GetCorpse();
18825 if(!corpse)
18826 return;
18828 uint32 delay;
18829 if(load)
18831 if(corpse->GetGhostTime() > m_deathExpireTime)
18832 return;
18834 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18836 uint32 count;
18837 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18838 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18840 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18841 if(count>=MAX_DEATH_COUNT)
18842 count = MAX_DEATH_COUNT-1;
18844 else
18845 count=0;
18847 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18849 time_t now = time(NULL);
18850 if(now >= expected_time)
18851 return;
18853 delay = expected_time-now;
18855 else
18856 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18858 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18859 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18860 data << uint32(delay*IN_MILISECONDS);
18861 GetSession()->SendPacket( &data );
18864 Player* Player::GetNextRandomRaidMember(float radius)
18866 Group *pGroup = GetGroup();
18867 if(!pGroup)
18868 return NULL;
18870 std::vector<Player*> nearMembers;
18871 nearMembers.reserve(pGroup->GetMembersCount());
18873 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18875 Player* Target = itr->getSource();
18877 // IsHostileTo check duel and controlled by enemy
18878 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18879 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18880 nearMembers.push_back(Target);
18883 if (nearMembers.empty())
18884 return NULL;
18886 uint32 randTarget = urand(0,nearMembers.size()-1);
18887 return nearMembers[randTarget];
18890 PartyResult Player::CanUninviteFromGroup() const
18892 const Group* grp = GetGroup();
18893 if(!grp)
18894 return PARTY_RESULT_YOU_NOT_IN_GROUP;
18896 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
18897 return PARTY_RESULT_YOU_NOT_LEADER;
18899 if(InBattleGround())
18900 return PARTY_RESULT_INVITE_RESTRICTED;
18902 return PARTY_RESULT_OK;
18905 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
18907 //we must move references from m_group to m_originalGroup
18908 SetOriginalGroup(GetGroup(), GetSubGroup());
18910 m_group.unlink();
18911 m_group.link(group, this);
18912 m_group.setSubGroup((uint8)subgroup);
18915 void Player::RemoveFromBattleGroundRaid()
18917 //remove existing reference
18918 m_group.unlink();
18919 if( Group* group = GetOriginalGroup() )
18921 m_group.link(group, this);
18922 m_group.setSubGroup(GetOriginalSubGroup());
18924 SetOriginalGroup(NULL);
18927 void Player::SetOriginalGroup(Group *group, int8 subgroup)
18929 if( group == NULL )
18930 m_originalGroup.unlink();
18931 else
18933 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
18934 assert(subgroup >= 0);
18935 m_originalGroup.link(group, this);
18936 m_originalGroup.setSubGroup((uint8)subgroup);
18940 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18942 LiquidData liquid_status;
18943 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
18944 if (!res)
18946 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
18947 // Small hack for enable breath in WMO
18948 if (IsInWater())
18949 m_MirrorTimerFlags|=UNDERWATER_INWATER;
18950 return;
18953 // All liquids type - check under water position
18954 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
18956 if ( res & LIQUID_MAP_UNDER_WATER)
18957 m_MirrorTimerFlags |= UNDERWATER_INWATER;
18958 else
18959 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
18962 // Allow travel in dark water on taxi or transport
18963 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
18964 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
18965 else
18966 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
18968 // in lava check, anywhere in lava level
18969 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
18971 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
18972 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
18973 else
18974 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
18976 // in slime check, anywhere in slime level
18977 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
18979 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
18980 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
18981 else
18982 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
18986 void Player::SetCanParry( bool value )
18988 if(m_canParry==value)
18989 return;
18991 m_canParry = value;
18992 UpdateParryPercentage();
18995 void Player::SetCanBlock( bool value )
18997 if(m_canBlock==value)
18998 return;
19000 m_canBlock = value;
19001 UpdateBlockPercentage();
19004 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19006 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19007 if(itr->pos == pos)
19008 return true;
19010 return false;
19013 bool Player::CanUseBattleGroundObject()
19015 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19016 // maybe gameobject code should handle that ForceReaction usage
19017 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19018 return ( //InBattleGround() && // in battleground - not need, check in other cases
19019 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19020 //player cannot use object when he is invulnerable (immune)
19021 !isTotalImmune() && // not totally immune
19022 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19023 !HasStealthAura() && // not stealthed
19024 !HasInvisibilityAura() && // not invisible
19025 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19026 isAlive() // live player
19030 bool Player::CanCaptureTowerPoint()
19032 return ( !HasStealthAura() && // not stealthed
19033 !HasInvisibilityAura() && // not invisible
19034 isAlive() // live player
19038 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19040 uint32 level = getLevel();
19042 if(level > GT_MAX_LEVEL)
19043 level = GT_MAX_LEVEL; // max level in this dbc
19045 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19046 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19047 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19049 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19050 return 0;
19052 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19054 if(!bsc) // shouldn't happen
19055 return 0xFFFFFFFF;
19057 float cost = 0;
19059 if(hairstyle != newhairstyle)
19060 cost += bsc->cost; // full price
19062 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19063 cost += bsc->cost * 0.5f; // +1/2 of price
19065 if(facialhair != newfacialhair)
19066 cost += bsc->cost * 0.75f; // +3/4 of price
19068 return uint32(cost);
19071 void Player::InitGlyphsForLevel()
19073 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19074 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19075 if(gs->Order)
19076 SetGlyphSlot(gs->Order - 1, gs->Id);
19078 uint32 level = getLevel();
19079 uint32 value = 0;
19081 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19082 if(level >= 15)
19083 value |= (0x01 | 0x02);
19084 if(level >= 30)
19085 value |= 0x08;
19086 if(level >= 50)
19087 value |= 0x04;
19088 if(level >= 70)
19089 value |= 0x10;
19090 if(level >= 80)
19091 value |= 0x20;
19093 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19096 void Player::EnterVehicle(Vehicle *vehicle)
19098 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19099 if(!ve)
19100 return;
19102 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19103 if(!veSeat)
19104 return;
19106 vehicle->SetCharmerGUID(GetGUID());
19107 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19108 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19109 vehicle->setFaction(getFaction());
19111 SetCharm(vehicle); // charm
19112 SetFarSightGUID(vehicle->GetGUID()); // set view
19114 SetClientControl(vehicle, 1); // redirect controls to vehicle
19116 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19117 GetSession()->SendPacket(&data);
19119 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19120 data.append(GetPackGUID());
19121 data << uint32(0); // counter?
19122 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19123 data << uint16(0); // special flags
19124 data << uint32(getMSTime()); // time
19125 data << vehicle->GetPositionX(); // x
19126 data << vehicle->GetPositionY(); // y
19127 data << vehicle->GetPositionZ(); // z
19128 data << vehicle->GetOrientation(); // o
19129 // transport part, TODO: load/calculate seat offsets
19130 data << uint64(vehicle->GetGUID()); // transport guid
19131 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19132 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19133 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19134 data << float(0); // transport orientation
19135 data << uint32(getMSTime()); // transport time
19136 data << uint8(0); // seat
19137 // end of transport part
19138 data << uint32(0); // fall time
19139 GetSession()->SendPacket(&data);
19141 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
19142 data << uint64(vehicle->GetGUID());
19143 data << uint32(0x00000000);
19144 data << uint32(0x00000000);
19145 data << uint32(0x00000101);
19147 for(uint32 i = 0; i < 10; ++i)
19148 data << uint16(0) << uint8(0) << uint8(i+8);
19150 data << uint8(0);
19151 data << uint8(0);
19152 GetSession()->SendPacket(&data);
19155 void Player::ExitVehicle(Vehicle *vehicle)
19157 vehicle->SetCharmerGUID(0);
19158 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19159 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19160 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19162 SetCharm(NULL);
19163 SetFarSightGUID(0);
19165 SetClientControl(vehicle, 0);
19167 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19168 data.append(GetPackGUID());
19169 data << uint32(0); // counter?
19170 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19171 data << uint16(0x40); // special flags
19172 data << uint32(getMSTime()); // time
19173 data << vehicle->GetPositionX(); // x
19174 data << vehicle->GetPositionY(); // y
19175 data << vehicle->GetPositionZ(); // z
19176 data << vehicle->GetOrientation(); // o
19177 data << uint32(0); // fall time
19178 GetSession()->SendPacket(&data);
19180 data.Initialize(SMSG_PET_SPELLS, 8+4);
19181 data << uint64(0);
19182 data << uint32(0);
19183 GetSession()->SendPacket(&data);
19185 // only for flyable vehicles?
19186 CastSpell(this, 45472, true); // Parachute
19189 bool Player::isTotalImmune()
19191 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19193 uint32 immuneMask = 0;
19194 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19196 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19197 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19198 return true;
19200 return false;
19203 bool Player::HasTitle(uint32 bitIndex)
19205 if (bitIndex > 128)
19206 return false;
19208 uint32 fieldIndexOffset = bitIndex/32;
19209 uint32 flag = 1 << (bitIndex%32);
19210 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19213 void Player::SetTitle(CharTitlesEntry const* title)
19215 uint32 fieldIndexOffset = title->bit_index/32;
19216 uint32 flag = 1 << (title->bit_index%32);
19217 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19220 void Player::ConvertRune(uint8 index, uint8 newType)
19222 SetCurrentRune(index, newType);
19224 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19225 data << uint8(index);
19226 data << uint8(newType);
19227 GetSession()->SendPacket(&data);
19230 void Player::ResyncRunes(uint8 count)
19232 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19233 for(uint32 i = 0; i < count; ++i)
19235 data << uint8(GetCurrentRune(i)); // rune type
19236 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19238 GetSession()->SendPacket(&data);
19241 void Player::AddRunePower(uint8 index)
19243 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19244 data << uint32(1 << index); // mask (0x00-0x3F probably)
19245 GetSession()->SendPacket(&data);
19248 void Player::InitRunes()
19250 if(getClass() != CLASS_DEATH_KNIGHT)
19251 return;
19253 m_runes = new Runes;
19255 m_runes->runeState = 0;
19257 for(uint32 i = 0; i < MAX_RUNES; ++i)
19259 SetBaseRune(i, i / 2); // init base types
19260 SetCurrentRune(i, i / 2); // init current types
19261 SetRuneCooldown(i, 0); // reset cooldowns
19262 m_runes->SetRuneState(i);
19265 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19266 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19269 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19271 Loot loot;
19272 loot.FillLoot (loot_id,store,this,true);
19274 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19275 for(uint32 i = 0; i < max_slot; ++i)
19277 LootItem* lootItem = loot.LootItemInSlot(i,this);
19279 ItemPosCountVec dest;
19280 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19281 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19282 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19283 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19284 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19285 if(msg != EQUIP_ERR_OK)
19287 SendEquipError( msg, NULL, NULL );
19288 continue;
19291 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19292 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19296 uint32 Player::CalculateTalentsPoints() const
19298 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19300 if(getClass() != CLASS_DEATH_KNIGHT)
19301 return base_talent;
19303 uint32 talentPointsForLevel =
19304 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19305 + m_questRewardTalentCount;
19307 if(talentPointsForLevel > base_talent)
19308 talentPointsForLevel = base_talent;
19310 return talentPointsForLevel;
19313 bool Player::IsAllowUseFlyMountsHere() const
19315 if (isGameMaster())
19316 return true;
19318 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19319 return v_map == 530 || v_map == 571 && HasSpell(54197);
19322 void Player::learnSpellHighRank(uint32 spellid)
19324 learnSpell(spellid,false);
19326 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19327 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19328 learnSpellHighRank(itr->second);
19331 void Player::_LoadSkills()
19333 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19335 // reset skill modifiers and set correct unlearn flags
19336 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
19338 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19340 // set correct unlearn bit
19341 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19342 if(!id) continue;
19344 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19345 if(!pSkill) continue;
19347 // enable unlearn button for primary professions only
19348 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19349 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19350 else
19351 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19353 // set fixed skill ranges
19354 switch(GetSkillRangeType(pSkill,false))
19356 case SKILL_RANGE_LANGUAGE: // 300..300
19357 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19358 break;
19359 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19360 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19361 break;
19362 default:
19363 break;
19366 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19367 learnSkillRewardedSpells(id, vskill);
19370 // special settings
19371 if(getClass()==CLASS_DEATH_KNIGHT)
19373 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19374 if(base_level < 1)
19375 base_level = 1;
19376 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19377 if(base_skill < 1)
19378 base_skill = 1; // skill mast be known and then > 0 in any case
19380 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19381 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19382 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19383 SetSkill(SKILL_AXES, base_skill,base_skill);
19384 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19385 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19386 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19387 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19388 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19389 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19390 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19391 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19392 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19393 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19394 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19395 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19399 uint32 Player::GetPhaseMaskForSpawn() const
19401 uint32 phase = PHASEMASK_NORMAL;
19402 if(!isGameMaster())
19403 phase = GetPhaseMask();
19404 else
19406 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19407 if(!phases.empty())
19408 phase = phases.front()->GetMiscValue();
19411 // some aura phases include 1 normal map in addition to phase itself
19412 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19413 return n_phase;
19415 return PHASEMASK_NORMAL;
19418 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19420 ItemPrototype const* pProto = pItem->GetProto();
19422 // proto based limitations
19423 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19424 return res;
19426 // check unique-equipped on gems
19427 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19429 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19430 if(!enchant_id)
19431 continue;
19432 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19433 if(!enchantEntry)
19434 continue;
19436 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19437 if(!pGem)
19438 continue;
19440 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19441 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19442 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19444 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19445 return res;
19448 return EQUIP_ERR_OK;
19451 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19453 // check unique-equipped on item
19454 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19456 // there is an equip limit on this item
19457 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19458 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19461 // check unique-equipped limit
19462 if (itemProto->ItemLimitCategory)
19464 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19465 if(!limitEntry)
19466 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19468 if(limit_count > limitEntry->maxCount)
19469 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19471 // there is an equip limit on this item
19472 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19473 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19476 return EQUIP_ERR_OK;
19479 void Player::HandleFall(MovementInfo const& movementInfo)
19481 // calculate total z distance of the fall
19482 float z_diff = m_lastFallZ - movementInfo.z;
19483 sLog.outDebug("zDiff = %f", z_diff);
19485 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19486 // 14.57 can be calculated by resolving damageperc formula below to 0
19487 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19488 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19489 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19491 //Safe fall, fall height reduction
19492 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19494 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19496 if(damageperc >0 )
19498 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19500 float height = movementInfo.z;
19501 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19503 if (damage > 0)
19505 //Prevent fall damage from being more than the player maximum health
19506 if (damage > GetMaxHealth())
19507 damage = GetMaxHealth();
19509 // Gust of Wind
19510 if (GetDummyAura(43621))
19511 damage = GetMaxHealth()/2;
19513 EnvironmentalDamage(DAMAGE_FALL, damage);
19515 // recheck alive, might have died of EnvironmentalDamage
19516 if (isAlive())
19517 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19520 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19521 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.z, height, GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall);
19526 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19528 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
19531 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
19533 uint32 CurTalentPoints = GetFreeTalentPoints();
19535 if(CurTalentPoints == 0)
19536 return;
19538 if (talentRank >= MAX_TALENT_RANK)
19539 return;
19541 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
19543 if(!talentInfo)
19544 return;
19546 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
19548 if(!talentTabInfo)
19549 return;
19551 // prevent learn talent for different class (cheating)
19552 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
19553 return;
19555 // find current max talent rank
19556 int32 curtalent_maxrank = 0;
19557 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19559 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19561 curtalent_maxrank = k + 1;
19562 break;
19566 // we already have same or higher talent rank learned
19567 if(curtalent_maxrank >= (talentRank + 1))
19568 return;
19570 // check if we have enough talent points
19571 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19572 return;
19574 // Check if it requires another talent
19575 if (talentInfo->DependsOn > 0)
19577 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19579 bool hasEnoughRank = false;
19580 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19582 if (depTalentInfo->RankID[i] != 0)
19583 if (HasSpell(depTalentInfo->RankID[i]))
19584 hasEnoughRank = true;
19586 if (!hasEnoughRank)
19587 return;
19591 // Find out how many points we have in this field
19592 uint32 spentPoints = 0;
19594 uint32 tTab = talentInfo->TalentTab;
19595 if (talentInfo->Row > 0)
19597 unsigned int numRows = sTalentStore.GetNumRows();
19598 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19600 // Someday, someone needs to revamp
19601 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19602 if (tmpTalent) // the way talents are tracked
19604 if (tmpTalent->TalentTab == tTab)
19606 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19608 if (tmpTalent->RankID[j] != 0)
19610 if (HasSpell(tmpTalent->RankID[j]))
19612 spentPoints += j + 1;
19621 // not have required min points spent in talent tree
19622 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
19623 return;
19625 // spell not set in talent.dbc
19626 uint32 spellid = talentInfo->RankID[talentRank];
19627 if( spellid == 0 )
19629 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19630 return;
19633 // already known
19634 if(HasSpell(spellid))
19635 return;
19637 // learn! (other talent ranks will unlearned at learning)
19638 learnSpell(spellid, false);
19639 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19641 // update free talent points
19642 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19645 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
19647 Pet *pet = GetPet();
19649 if(!pet)
19650 return;
19652 if(petGuid != pet->GetGUID())
19653 return;
19655 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
19657 if(CurTalentPoints == 0)
19658 return;
19660 if (talentRank >= MAX_PET_TALENT_RANK)
19661 return;
19663 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
19665 if(!talentInfo)
19666 return;
19668 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
19670 if(!talentTabInfo)
19671 return;
19673 CreatureInfo const *ci = pet->GetCreatureInfo();
19675 if(!ci)
19676 return;
19678 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19680 if(!pet_family)
19681 return;
19683 if(pet_family->petTalentType < 0) // not hunter pet
19684 return;
19686 // prevent learn talent for different family (cheating)
19687 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19688 return;
19690 // find current max talent rank
19691 int32 curtalent_maxrank = 0;
19692 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19694 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
19696 curtalent_maxrank = k + 1;
19697 break;
19701 // we already have same or higher talent rank learned
19702 if(curtalent_maxrank >= (talentRank + 1))
19703 return;
19705 // check if we have enough talent points
19706 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19707 return;
19709 // Check if it requires another talent
19710 if (talentInfo->DependsOn > 0)
19712 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19714 bool hasEnoughRank = false;
19715 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19717 if (depTalentInfo->RankID[i] != 0)
19718 if (pet->HasSpell(depTalentInfo->RankID[i]))
19719 hasEnoughRank = true;
19721 if (!hasEnoughRank)
19722 return;
19726 // Find out how many points we have in this field
19727 uint32 spentPoints = 0;
19729 uint32 tTab = talentInfo->TalentTab;
19730 if (talentInfo->Row > 0)
19732 unsigned int numRows = sTalentStore.GetNumRows();
19733 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19735 // Someday, someone needs to revamp
19736 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19737 if (tmpTalent) // the way talents are tracked
19739 if (tmpTalent->TalentTab == tTab)
19741 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19743 if (tmpTalent->RankID[j] != 0)
19745 if (pet->HasSpell(tmpTalent->RankID[j]))
19747 spentPoints += j + 1;
19756 // not have required min points spent in talent tree
19757 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
19758 return;
19760 // spell not set in talent.dbc
19761 uint32 spellid = talentInfo->RankID[talentRank];
19762 if( spellid == 0 )
19764 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19765 return;
19768 // already known
19769 if(pet->HasSpell(spellid))
19770 return;
19772 // learn! (other talent ranks will unlearned at learning)
19773 pet->learnSpell(spellid);
19774 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19776 // update free talent points
19777 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19780 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
19782 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
19784 if(apply)
19785 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
19786 else
19787 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
19791 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
19793 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
19794 SetFallInformation(minfo.fallTime, minfo.z);
19797 void Player::UnsummonPetTemporaryIfAny()
19799 Pet* pet = GetPet();
19800 if(!pet)
19801 return;
19803 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
19805 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
19806 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
19809 RemovePet(pet, PET_SAVE_AS_CURRENT);
19812 void Player::ResummonPetTemporaryUnSummonedIfAny()
19814 if(!m_temporaryUnsummonedPetNumber)
19815 return;
19817 // not resummon in not appropriate state
19818 if(IsPetNeedBeTemporaryUnsummoned())
19819 return;
19821 if(GetPetGUID())
19822 return;
19824 Pet* NewPet = new Pet;
19825 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
19826 delete NewPet;
19828 m_temporaryUnsummonedPetNumber = 0;