[7369] Remove ReqSourceRef in quest_template.
[getmangos.git] / src / game / Player.cpp
blob3bfd72f011ef7f068cc4ee8261598cdb80bebf21
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "ObjectMgr.h"
25 #include "SpellMgr.h"
26 #include "World.h"
27 #include "WorldPacket.h"
28 #include "WorldSession.h"
29 #include "UpdateMask.h"
30 #include "Player.h"
31 #include "SkillDiscovery.h"
32 #include "QuestDef.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
35 #include "Channel.h"
36 #include "ChannelMgr.h"
37 #include "MapManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "GridNotifiers.h"
41 #include "GridNotifiersImpl.h"
42 #include "CellImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "CreatureAI.h"
46 #include "Formulas.h"
47 #include "Group.h"
48 #include "Guild.h"
49 #include "Pet.h"
50 #include "SpellAuras.h"
51 #include "Util.h"
52 #include "Transports.h"
53 #include "Weather.h"
54 #include "BattleGround.h"
55 #include "BattleGroundMgr.h"
56 #include "ArenaTeam.h"
57 #include "Chat.h"
58 #include "Database/DatabaseImpl.h"
59 #include "Spell.h"
60 #include "SocialMgr.h"
61 #include "AchievementMgr.h"
63 #include <cmath>
65 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
67 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
68 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
69 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
71 #define SKILL_VALUE(x) PAIR32_LOPART(x)
72 #define SKILL_MAX(x) PAIR32_HIPART(x)
73 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
75 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
76 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
77 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
79 enum CharacterFlags
81 CHARACTER_FLAG_NONE = 0x00000000,
82 CHARACTER_FLAG_UNK1 = 0x00000001,
83 CHARACTER_FLAG_UNK2 = 0x00000002,
84 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
85 CHARACTER_FLAG_UNK4 = 0x00000008,
86 CHARACTER_FLAG_UNK5 = 0x00000010,
87 CHARACTER_FLAG_UNK6 = 0x00000020,
88 CHARACTER_FLAG_UNK7 = 0x00000040,
89 CHARACTER_FLAG_UNK8 = 0x00000080,
90 CHARACTER_FLAG_UNK9 = 0x00000100,
91 CHARACTER_FLAG_UNK10 = 0x00000200,
92 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
93 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
94 CHARACTER_FLAG_UNK13 = 0x00001000,
95 CHARACTER_FLAG_GHOST = 0x00002000,
96 CHARACTER_FLAG_RENAME = 0x00004000,
97 CHARACTER_FLAG_UNK16 = 0x00008000,
98 CHARACTER_FLAG_UNK17 = 0x00010000,
99 CHARACTER_FLAG_UNK18 = 0x00020000,
100 CHARACTER_FLAG_UNK19 = 0x00040000,
101 CHARACTER_FLAG_UNK20 = 0x00080000,
102 CHARACTER_FLAG_UNK21 = 0x00100000,
103 CHARACTER_FLAG_UNK22 = 0x00200000,
104 CHARACTER_FLAG_UNK23 = 0x00400000,
105 CHARACTER_FLAG_UNK24 = 0x00800000,
106 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
107 CHARACTER_FLAG_DECLINED = 0x02000000,
108 CHARACTER_FLAG_UNK27 = 0x04000000,
109 CHARACTER_FLAG_UNK28 = 0x08000000,
110 CHARACTER_FLAG_UNK29 = 0x10000000,
111 CHARACTER_FLAG_UNK30 = 0x20000000,
112 CHARACTER_FLAG_UNK31 = 0x40000000,
113 CHARACTER_FLAG_UNK32 = 0x80000000
116 // corpse reclaim times
117 #define DEATH_EXPIRE_STEP (5*MINUTE)
118 #define MAX_DEATH_COUNT 3
120 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
122 //== PlayerTaxi ================================================
124 PlayerTaxi::PlayerTaxi()
126 // Taxi nodes
127 memset(m_taximask, 0, sizeof(m_taximask));
130 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
132 // capital and taxi hub masks
133 switch(race)
135 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
136 case RACE_ORC: SetTaximaskNode(23); break; // Orc
137 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
138 case RACE_NIGHTELF: SetTaximaskNode(26);
139 SetTaximaskNode(27); break; // Night Elf
140 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
141 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
142 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
143 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
144 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
145 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
148 switch(chrClass)
150 case CLASS_DEATH_KNIGHT: // TODO: figure out initial known nodes
151 break;
154 // new continent starting masks (It will be accessible only at new map)
155 switch(Player::TeamForRace(race))
157 case ALLIANCE: SetTaximaskNode(100); break;
158 case HORDE: SetTaximaskNode(99); break;
160 // level dependent taxi hubs
161 if(level>=68)
162 SetTaximaskNode(213); //Shattered Sun Staging Area
165 void PlayerTaxi::LoadTaxiMask(const char* data)
167 Tokens tokens = StrSplit(data, " ");
169 int index;
170 Tokens::iterator iter;
171 for (iter = tokens.begin(), index = 0;
172 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
174 // load and set bits only for existed taxi nodes
175 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
179 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
181 if(all)
183 for (uint8 i=0; i<TaxiMaskSize; i++)
184 data << uint32(sTaxiNodesMask[i]); // all existed nodes
186 else
188 for (uint8 i=0; i<TaxiMaskSize; i++)
189 data << uint32(m_taximask[i]); // known nodes
193 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
195 ClearTaxiDestinations();
197 Tokens tokens = StrSplit(values," ");
199 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
201 uint32 node = uint32(atol(iter->c_str()));
202 AddTaxiDestination(node);
205 if(m_TaxiDestinations.empty())
206 return true;
208 // Check integrity
209 if(m_TaxiDestinations.size() < 2)
210 return false;
212 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
214 uint32 cost;
215 uint32 path;
216 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
217 if(!path)
218 return false;
221 // can't load taxi path without mount set (quest taxi path?)
222 if(!objmgr.GetTaxiMount(GetTaxiSource(),team))
223 return false;
225 return true;
228 std::string PlayerTaxi::SaveTaxiDestinationsToString()
230 if(m_TaxiDestinations.empty())
231 return "";
233 std::ostringstream ss;
235 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
236 ss << m_TaxiDestinations[i] << " ";
238 return ss.str();
241 uint32 PlayerTaxi::GetCurrentTaxiPath() const
243 if(m_TaxiDestinations.size() < 2)
244 return 0;
246 uint32 path;
247 uint32 cost;
249 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
251 return path;
254 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
256 ss << "'";
257 for(int i = 0; i < TaxiMaskSize; ++i)
258 ss << taxi.m_taximask[i] << " ";
259 ss << "'";
260 return ss;
263 //== Player ====================================================
265 const int32 Player::ReputationRank_Length[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
267 UpdateMask Player::updateVisualBits;
269 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this)
271 m_transport = 0;
273 m_speakTime = 0;
274 m_speakCount = 0;
276 m_objectType |= TYPEMASK_PLAYER;
277 m_objectTypeId = TYPEID_PLAYER;
279 m_valuesCount = PLAYER_END;
281 m_session = session;
283 m_divider = 0;
285 m_ExtraFlags = 0;
286 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
287 SetAcceptTicket(true);
289 // players always accept
290 if(GetSession()->GetSecurity() == SEC_PLAYER)
291 SetAcceptWhispers(true);
293 m_curSelection = 0;
294 m_lootGuid = 0;
296 m_comboTarget = 0;
297 m_comboPoints = 0;
299 m_usedTalentCount = 0;
300 m_questRewardTalentCount = 0;
302 m_regenTimer = 0;
303 m_weaponChangeTimer = 0;
305 m_zoneUpdateId = 0;
306 m_zoneUpdateTimer = 0;
308 m_areaUpdateId = 0;
310 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
312 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
313 // this must help in case next save after mass player load after server startup
314 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
316 clearResurrectRequestData();
318 m_SpellModRemoveCount = 0;
320 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
322 m_social = NULL;
324 // group is initialized in the reference constructor
325 SetGroupInvite(NULL);
326 m_groupUpdateMask = 0;
327 m_auraUpdateMask = 0;
329 duel = NULL;
331 m_GuildIdInvited = 0;
332 m_ArenaTeamIdInvited = 0;
334 m_atLoginFlags = AT_LOGIN_NONE;
336 m_dontMove = false;
338 pTrader = 0;
339 ClearTrade();
341 m_cinematic = 0;
343 PlayerTalkClass = new PlayerMenu( GetSession() );
344 m_currentBuybackSlot = BUYBACK_SLOT_START;
346 for ( int aX = 0 ; aX < 8 ; aX++ )
347 m_Tutorials[ aX ] = 0x00;
348 m_TutorialsChanged = false;
350 m_DailyQuestChanged = false;
351 m_lastDailyQuestTime = 0;
353 m_regenTimer = 0;
354 m_weaponChangeTimer = 0;
355 m_breathTimer = 0;
356 m_isunderwater = UNDERWATER_NONE;
357 m_isInWater = false;
358 m_drunkTimer = 0;
359 m_drunk = 0;
360 m_restTime = 0;
361 m_deathTimer = 0;
362 m_deathExpireTime = 0;
364 m_swingErrorMsg = 0;
366 m_DetectInvTimer = 1*IN_MILISECONDS;
368 m_bgBattleGroundID = 0;
369 m_bgTypeID = BATTLEGROUND_TYPE_NONE;
370 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; j++)
372 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
373 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
375 m_bgTeam = 0;
377 m_logintime = time(NULL);
378 m_Last_tick = m_logintime;
379 m_WeaponProficiency = 0;
380 m_ArmorProficiency = 0;
381 m_canParry = false;
382 m_canBlock = false;
383 m_canDualWield = false;
384 m_canTitanGrip = false;
385 m_ammoDPS = 0.0f;
387 m_temporaryUnsummonedPetNumber = 0;
388 //cache for UNIT_CREATED_BY_SPELL to allow
389 //returning reagents for temporarily removed pets
390 //when dying/logging out
391 m_oldpetspell = 0;
393 ////////////////////Rest System/////////////////////
394 time_inn_enter=0;
395 inn_pos_mapid=0;
396 inn_pos_x=0;
397 inn_pos_y=0;
398 inn_pos_z=0;
399 m_rest_bonus=0;
400 rest_type=REST_TYPE_NO;
401 ////////////////////Rest System/////////////////////
403 m_mailsLoaded = false;
404 m_mailsUpdated = false;
405 unReadMails = 0;
406 m_nextMailDelivereTime = 0;
408 m_resetTalentsCost = 0;
409 m_resetTalentsTime = 0;
410 m_itemUpdateQueueBlocked = false;
412 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
413 m_forced_speed_changes[i] = 0;
415 m_stableSlots = 0;
417 /////////////////// Instance System /////////////////////
419 m_HomebindTimer = 0;
420 m_InstanceValid = true;
421 m_dungeonDifficulty = DIFFICULTY_NORMAL;
423 m_lastPotionId = 0;
425 for (int i = 0; i < BASEMOD_END; i++)
427 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
428 m_auraBaseMod[i][PCT_MOD] = 1.0f;
431 for (int i = 0; i < MAX_COMBAT_RATING; i++)
432 m_baseRatingValue[i] = 0;
434 m_baseSpellDamage = 0;
435 m_baseSpellHealing = 0;
436 m_baseFeralAP = 0;
437 m_baseManaRegen = 0;
439 // Honor System
440 m_lastHonorUpdateTime = time(NULL);
442 // Player summoning
443 m_summon_expire = 0;
444 m_summon_mapid = 0;
445 m_summon_x = 0.0f;
446 m_summon_y = 0.0f;
447 m_summon_z = 0.0f;
449 //Default movement to run mode
450 m_unit_movement_flags = 0;
452 m_mover = NULL;
454 m_miniPet = 0;
455 m_bgAfkReportedTimer = 0;
456 m_contestedPvPTimer = 0;
458 m_declinedname = NULL;
459 m_runes = NULL;
462 Player::~Player ()
464 CleanupsBeforeDelete();
466 // it must be unloaded already in PlayerLogout and accessed only for loggined player
467 //m_social = NULL;
469 // Note: buy back item already deleted from DB when player was saved
470 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
472 if(m_items[i])
473 delete m_items[i];
475 CleanupChannels();
477 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
478 delete itr->second;
480 //all mailed items should be deleted, also all mail should be deallocated
481 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
482 delete *itr;
484 for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
485 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
487 delete PlayerTalkClass;
489 if (m_transport)
491 m_transport->RemovePassenger(this);
494 for(size_t x = 0; x < ItemSetEff.size(); x++)
495 if(ItemSetEff[x])
496 delete ItemSetEff[x];
498 // clean up player-instance binds, may unload some instance saves
499 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
500 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
501 itr->second.save->RemovePlayer(this);
503 delete m_declinedname;
504 delete m_runes;
507 void Player::CleanupsBeforeDelete()
509 if(m_uint32Values) // only for fully created Object
511 TradeCancel(false);
512 DuelComplete(DUEL_INTERUPTED);
514 Unit::CleanupsBeforeDelete();
517 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 )
519 //FIXME: outfitId not used in player creating
521 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
523 m_name = name;
525 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
526 if(!info)
528 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
529 return false;
532 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
533 m_items[i] = NULL;
535 m_race = race;
536 m_class = class_;
538 SetMapId(info->mapId);
539 Relocate(info->positionX,info->positionY,info->positionZ);
541 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
542 if(!cEntry)
544 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
545 return false;
548 uint8 powertype = cEntry->powerType;
550 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
551 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
553 switch(gender)
555 case GENDER_FEMALE:
556 SetDisplayId(info->displayId_f );
557 SetNativeDisplayId(info->displayId_f );
558 break;
559 case GENDER_MALE:
560 SetDisplayId(info->displayId_m );
561 SetNativeDisplayId(info->displayId_m );
562 break;
563 default:
564 sLog.outError("Invalid gender %u for player",gender);
565 return false;
566 break;
569 setFactionForRace(m_race);
571 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
573 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
574 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
575 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
576 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
577 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
578 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
580 // -1 is default value
581 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
583 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
584 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
585 SetByteValue(PLAYER_BYTES_3, 0, gender);
587 SetUInt32Value( PLAYER_GUILDID, 0 );
588 SetUInt32Value( PLAYER_GUILDRANK, 0 );
589 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
591 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
592 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
593 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
594 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
595 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
596 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
597 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
599 // set starting level
600 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
601 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
602 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
604 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
606 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
607 if(gm_level > start_level)
608 start_level = gm_level;
611 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
613 InitRunes();
615 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
616 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
617 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
619 // Played time
620 m_Last_tick = time(NULL);
621 m_Played_time[0] = 0;
622 m_Played_time[1] = 0;
624 // base stats and related field values
625 InitStatsForLevel();
626 InitTaxiNodesForLevel();
627 InitGlyphsForLevel();
628 InitTalentForLevel();
629 InitPrimaryProffesions(); // to max set before any spell added
631 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
632 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
633 SetHealth(GetMaxHealth());
634 if (getPowerType()==POWER_MANA)
636 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
637 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
640 if(getPowerType() == POWER_RUNIC_POWER)
642 SetPower(POWER_RUNE, 8);
643 SetMaxPower(POWER_RUNE, 8);
644 SetPower(POWER_RUNIC_POWER, 0);
645 SetMaxPower(POWER_RUNIC_POWER, 1000);
648 // original spells
649 learnDefaultSpells();
651 // original action bar
652 std::list<uint16>::const_iterator action_itr[4];
653 for(int i=0; i<4; i++)
654 action_itr[i] = info->action[i].begin();
656 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
658 uint16 taction[4];
659 for(int i=0; i<4 ;i++)
660 taction[i] = (*action_itr[i]);
662 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
664 for(int i=0; i<4 ;i++)
665 ++action_itr[i];
668 // original items
669 CharStartOutfitEntry const* oEntry = NULL;
670 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
672 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
674 if(entry->RaceClassGender == RaceClassGender)
676 oEntry = entry;
677 break;
682 if(oEntry)
684 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
686 if(oEntry->ItemId[j] <= 0)
687 continue;
689 uint32 item_id = oEntry->ItemId[j];
692 // Hack for not existed item id in dbc 3.0.3
693 if(item_id==40582)
694 continue;
696 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
697 if(!iProto)
699 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
700 continue;
703 // max stack by default (mostly 1), 1 for infinity stackable
704 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
706 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
708 switch(iProto->Spells[0].SpellCategory)
710 case 11: // food
711 if(iProto->Stackable > 4)
712 count = 4;
713 break;
714 case 59: // drink
715 if(iProto->Stackable > 2)
716 count = 2;
717 break;
721 StoreNewItemInBestSlots(item_id, count);
725 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
726 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
728 // bags and main-hand weapon must equipped at this moment
729 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
730 // or ammo not equipped in special bag
731 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
733 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
735 uint16 eDest;
736 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
737 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
738 if( msg == EQUIP_ERR_OK )
740 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
741 EquipItem( eDest, pItem, true);
743 // move other items to more appropriate slots (ammo not equipped in special bag)
744 else
746 ItemPosCountVec sDest;
747 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
748 if( msg == EQUIP_ERR_OK )
750 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
751 pItem = StoreItem( sDest, pItem, true);
754 // if this is ammo then use it
755 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
756 if( msg == EQUIP_ERR_OK )
757 SetAmmo( pItem->GetProto()->ItemId );
761 // all item positions resolved
763 return true;
766 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
768 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
770 // attempt equip by one
771 while(titem_amount > 0)
773 uint16 eDest;
774 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
775 if( msg != EQUIP_ERR_OK )
776 break;
778 EquipNewItem( eDest, titem_id, true);
779 AutoUnequipOffhandIfNeed();
780 --titem_amount;
783 if(titem_amount == 0)
784 return true; // equipped
786 // attempt store
787 ItemPosCountVec sDest;
788 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
789 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
790 if( msg == EQUIP_ERR_OK )
792 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
793 return true; // stored
796 // item can't be added
797 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
798 return false;
801 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
803 uint32 BreathRegen = (uint32)-1;
805 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
806 data << (uint32)Type;
807 data << MaxValue;
808 data << MaxValue;
809 data << BreathRegen;
810 data << (uint8)0;
811 data << (uint32)0; // spell id
812 GetSession()->SendPacket(&data);
815 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
817 if(Type==BREATH_TIMER)
818 m_breathTimer = ((MaxValue + 1*IN_MILISECONDS) - CurrentValue) / Regen;
820 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
821 data << (uint32)Type;
822 data << CurrentValue;
823 data << MaxValue;
824 data << Regen;
825 data << (uint8)0;
826 data << (uint32)0; // spell id
827 GetSession()->SendPacket( &data );
830 void Player::StopMirrorTimer(MirrorTimerType Type)
832 if(Type==BREATH_TIMER)
833 m_breathTimer = 0;
835 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
836 data << (uint32)Type;
837 GetSession()->SendPacket( &data );
840 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
842 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
843 data << (uint64)guid;
844 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
845 data << (uint32)damage;
846 data << (uint32)0;
847 data << (uint32)0;
848 SendMessageToSet(&data, true);
850 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
852 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
854 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
855 DurabilityLossAll(0.10f,false);
856 // durability lost message
857 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
858 GetSession()->SendPacket(&data);
862 void Player::HandleDrowning()
864 if(!(m_isunderwater&~UNDERWATER_INLAVA))
865 return;
867 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
868 if(isGameMaster() || !isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
870 StopMirrorTimer(BREATH_TIMER);
871 // drop every flag _except_ LAVA - otherwise waterbreathing will prevent lava damage
872 m_isunderwater &= UNDERWATER_INLAVA;
873 return;
876 uint32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS; // default duration
878 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
879 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
880 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
882 if ((m_isunderwater & UNDERWATER_INWATER) && !(m_isunderwater & UNDERWATER_INLAVA) && isAlive())
884 //single trigger timer
885 if (!(m_isunderwater & UNDERWATER_WATER_TRIGGER))
887 m_isunderwater|= UNDERWATER_WATER_TRIGGER;
888 m_breathTimer = UnderWaterTime + 1*IN_MILISECONDS;
890 //single trigger "show Breathbar"
891 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & UNDERWATER_WATER_BREATHB))
893 m_isunderwater|= UNDERWATER_WATER_BREATHB;
894 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
896 //continuous trigger drowning "Damage"
897 if ((m_breathTimer == 0) && (m_isunderwater & UNDERWATER_INWATER))
899 //TODO: Check this formula
900 uint64 guid = GetGUID();
901 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
903 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
904 m_breathTimer = 2000;
907 //single trigger retract bar
908 else if (!(m_isunderwater & UNDERWATER_INWATER) && (m_isunderwater & UNDERWATER_WATER_TRIGGER) && (m_breathTimer > 0) && isAlive())
910 uint32 BreathRegen = 10;
911 // m_breathTimer will be reduced in ModifyMirrorTimer
912 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
913 m_isunderwater = UNDERWATER_WATER_BREATHB_RETRACTING;
915 //remove bar
916 else if ((m_breathTimer < 50) && !(m_isunderwater & UNDERWATER_INWATER) && (m_isunderwater == UNDERWATER_WATER_BREATHB_RETRACTING))
918 StopMirrorTimer(BREATH_TIMER);
919 m_isunderwater = UNDERWATER_NONE;
923 void Player::HandleLava()
925 if ((m_isunderwater & UNDERWATER_INLAVA) && isAlive())
928 * arrai: how is this supposed to work? UNDERWATER_INLAVA is always set in this scope!
929 // Single trigger Set BreathTimer
930 if (!(m_isunderwater & UNDERWATER_INLAVA))
932 m_isunderwater|= UNDERWATER_WATER_BREATHB;
933 m_breathTimer = 1*IN_MILISECONDS;
936 // Reset BreathTimer and still in the lava
937 if (!m_breathTimer)
939 uint64 guid = GetGUID();
940 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
942 // if not gamemaster then deal damage
943 if ( !isGameMaster() )
944 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
946 m_breathTimer = 1*IN_MILISECONDS;
949 else if (!isAlive()) // Disable breath timer and reset underwater flags
951 m_breathTimer = 0;
952 m_isunderwater = UNDERWATER_NONE;
956 ///The player sobers by 256 every 10 seconds
957 void Player::HandleSobering()
959 m_drunkTimer = 0;
961 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
962 SetDrunkValue(drunk);
965 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
967 if(value >= 23000)
968 return DRUNKEN_SMASHED;
969 if(value >= 12800)
970 return DRUNKEN_DRUNK;
971 if(value & 0xFFFE)
972 return DRUNKEN_TIPSY;
973 return DRUNKEN_SOBER;
976 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
978 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
980 m_drunk = newDrunkenValue;
981 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
983 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
985 // special drunk invisibility detection
986 if(newDrunkenState >= DRUNKEN_DRUNK)
987 m_detectInvisibilityMask |= (1<<6);
988 else
989 m_detectInvisibilityMask &= ~(1<<6);
991 if(newDrunkenState == oldDrunkenState)
992 return;
994 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
995 data << uint64(GetGUID());
996 data << uint32(newDrunkenState);
997 data << uint32(itemId);
999 SendMessageToSet(&data, true);
1002 void Player::Update( uint32 p_time )
1004 if(!IsInWorld())
1005 return;
1007 // undelivered mail
1008 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1010 SendNewMail();
1011 ++unReadMails;
1013 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1014 m_nextMailDelivereTime = 0;
1017 Unit::Update( p_time );
1019 // update player only attacks
1020 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1022 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1025 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1027 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1030 time_t now = time (NULL);
1032 UpdatePvPFlag(now);
1034 UpdateContestedPvP(p_time);
1036 UpdateDuelFlag(now);
1038 CheckDuelDistance(now);
1040 UpdateAfkReport(now);
1042 CheckExploreSystem();
1044 // Update items that have just a limited lifetime
1045 if (now>m_Last_tick)
1046 UpdateItemDuration(uint32(now- m_Last_tick));
1048 if (!m_timedquests.empty())
1050 std::set<uint32>::iterator iter = m_timedquests.begin();
1051 while (iter != m_timedquests.end())
1053 QuestStatusData& q_status = mQuestStatus[*iter];
1054 if( q_status.m_timer <= p_time )
1056 uint32 quest_id = *iter;
1057 ++iter; // current iter will be removed in FailTimedQuest
1058 FailTimedQuest( quest_id );
1060 else
1062 q_status.m_timer -= p_time;
1063 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1064 ++iter;
1069 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1071 Unit *pVictim = getVictim();
1072 if( !IsNonMeleeSpellCasted(false) && pVictim)
1074 // default combat reach 10
1075 // TODO add weapon,skill check
1077 float pldistance = ATTACK_DISTANCE;
1079 if (isAttackReady(BASE_ATTACK))
1081 if(!IsWithinDistInMap(pVictim, pldistance))
1083 setAttackTimer(BASE_ATTACK,100);
1084 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1086 SendAttackSwingNotInRange();
1087 m_swingErrorMsg = 1;
1090 //120 degrees of radiant range
1091 else if( !HasInArc( 2*M_PI/3, pVictim ))
1093 setAttackTimer(BASE_ATTACK,100);
1094 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1096 SendAttackSwingBadFacingAttack();
1097 m_swingErrorMsg = 2;
1100 else
1102 m_swingErrorMsg = 0; // reset swing error state
1104 // prevent base and off attack in same time, delay attack at 0.2 sec
1105 if(haveOffhandWeapon())
1107 uint32 off_att = getAttackTimer(OFF_ATTACK);
1108 if(off_att < ATTACK_DISPLAY_DELAY)
1109 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1111 AttackerStateUpdate(pVictim, BASE_ATTACK);
1112 resetAttackTimer(BASE_ATTACK);
1116 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1118 if(!IsWithinDistInMap(pVictim, pldistance))
1120 setAttackTimer(OFF_ATTACK,100);
1122 else if( !HasInArc( 2*M_PI/3, pVictim ))
1124 setAttackTimer(OFF_ATTACK,100);
1126 else
1128 // prevent base and off attack in same time, delay attack at 0.2 sec
1129 uint32 base_att = getAttackTimer(BASE_ATTACK);
1130 if(base_att < ATTACK_DISPLAY_DELAY)
1131 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1132 // do attack
1133 AttackerStateUpdate(pVictim, OFF_ATTACK);
1134 resetAttackTimer(OFF_ATTACK);
1138 Unit *owner = pVictim->GetOwner();
1139 Unit *u = owner ? owner : pVictim;
1140 if(u->IsPvP() && (!duel || duel->opponent != u))
1142 UpdatePvP(true);
1143 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1148 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1150 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1152 int time_inn = time(NULL)-GetTimeInnEnter();
1153 if (time_inn >= 10) //freeze update
1155 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1156 //speed collect rest bonus (section/in hour)
1157 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1158 UpdateInnerTime(time(NULL));
1163 if(m_regenTimer > 0)
1165 if(p_time >= m_regenTimer)
1166 m_regenTimer = 0;
1167 else
1168 m_regenTimer -= p_time;
1171 if (m_weaponChangeTimer > 0)
1173 if(p_time >= m_weaponChangeTimer)
1174 m_weaponChangeTimer = 0;
1175 else
1176 m_weaponChangeTimer -= p_time;
1179 if (m_zoneUpdateTimer > 0)
1181 if(p_time >= m_zoneUpdateTimer)
1183 uint32 newzone = GetZoneId();
1184 if( m_zoneUpdateId != newzone )
1185 UpdateZone(newzone); // also update area
1186 else
1188 // use area updates as well
1189 // needed for free far all arenas for example
1190 uint32 newarea = GetAreaId();
1191 if( m_areaUpdateId != newarea )
1192 UpdateArea(newarea);
1194 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1197 else
1198 m_zoneUpdateTimer -= p_time;
1201 if (isAlive())
1203 RegenerateAll();
1206 if (m_deathState == JUST_DIED)
1208 KillPlayer();
1211 if(m_nextSave > 0)
1213 if(p_time >= m_nextSave)
1215 // m_nextSave reseted in SaveToDB call
1216 SaveToDB();
1217 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1219 else
1221 m_nextSave -= p_time;
1225 //Breathtimer
1226 if(m_breathTimer > 0)
1228 if(p_time >= m_breathTimer)
1229 m_breathTimer = 0;
1230 else
1231 m_breathTimer -= p_time;
1235 //Handle Water/drowning
1236 HandleDrowning();
1238 //Handle lava
1239 HandleLava();
1241 //Handle detect stealth players
1242 if (m_DetectInvTimer > 0)
1244 if (p_time >= m_DetectInvTimer)
1246 m_DetectInvTimer = 3000;
1247 HandleStealthedUnitsDetection();
1249 else
1250 m_DetectInvTimer -= p_time;
1253 // Played time
1254 if (now > m_Last_tick)
1256 uint32 elapsed = uint32(now - m_Last_tick);
1257 m_Played_time[0] += elapsed; // Total played time
1258 m_Played_time[1] += elapsed; // Level played time
1259 m_Last_tick = now;
1262 if (m_drunk)
1264 m_drunkTimer += p_time;
1266 if (m_drunkTimer > 10*IN_MILISECONDS)
1267 HandleSobering();
1270 // not auto-free ghost from body in instances
1271 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1273 if(p_time >= m_deathTimer)
1275 m_deathTimer = 0;
1276 BuildPlayerRepop();
1277 RepopAtGraveyard();
1279 else
1280 m_deathTimer -= p_time;
1283 UpdateEnchantTime(p_time);
1284 UpdateHomebindTime(p_time);
1286 // group update
1287 SendUpdateToOutOfRangeGroupMembers();
1289 Pet* pet = GetPet();
1290 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1292 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1293 return;
1297 void Player::setDeathState(DeathState s)
1299 uint32 ressSpellId = 0;
1301 bool cur = isAlive();
1303 if(s == JUST_DIED && cur)
1305 // drunken state is cleared on death
1306 SetDrunkValue(0);
1307 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1308 ClearComboPoints();
1310 clearResurrectRequestData();
1312 // remove form before other mods to prevent incorrect stats calculation
1313 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1315 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1316 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1318 // remove uncontrolled pets
1319 RemoveMiniPet();
1320 RemoveGuardians();
1322 // save value before aura remove in Unit::setDeathState
1323 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1325 // passive spell
1326 if(!ressSpellId)
1327 ressSpellId = GetResurrectionSpellId();
1328 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1330 Unit::setDeathState(s);
1332 // restore resurrection spell id for player after aura remove
1333 if(s == JUST_DIED && cur && ressSpellId)
1334 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1336 if(isAlive() && !cur)
1338 //clear aura case after resurrection by another way (spells will be applied before next death)
1339 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1341 // restore default warrior stance
1342 if(getClass()== CLASS_WARRIOR)
1343 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1347 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1349 Field *fields = result->Fetch();
1351 *p_data << uint64(GetGUID());
1352 *p_data << m_name;
1354 *p_data << uint8(getRace());
1355 uint8 pClass = getClass();
1356 *p_data << uint8(pClass);
1357 *p_data << uint8(getGender());
1359 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1360 *p_data << uint8(bytes);
1361 *p_data << uint8(bytes >> 8);
1362 *p_data << uint8(bytes >> 16);
1363 *p_data << uint8(bytes >> 24);
1365 bytes = GetUInt32Value(PLAYER_BYTES_2);
1366 *p_data << uint8(bytes);
1368 *p_data << uint8(getLevel()); // player level
1369 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1370 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1371 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1372 *p_data << uint32(zoneId);
1373 *p_data << uint32(GetMapId());
1375 *p_data << GetPositionX();
1376 *p_data << GetPositionY();
1377 *p_data << GetPositionZ();
1379 // guild id
1380 *p_data << (result ? fields[13].GetUInt32() : 0);
1382 uint32 char_flags = 0;
1383 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1384 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1385 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1386 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1387 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1388 char_flags |= CHARACTER_FLAG_GHOST;
1389 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1390 char_flags |= CHARACTER_FLAG_RENAME;
1391 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1392 char_flags |= CHARACTER_FLAG_DECLINED;
1394 *p_data << uint32(char_flags); // character flags
1395 // character customize (flags?)
1396 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1397 *p_data << uint8(1); // unknown
1399 // Pets info
1401 uint32 petDisplayId = 0;
1402 uint32 petLevel = 0;
1403 uint32 petFamily = 0;
1405 // show pet at selection character in character list only for non-ghost character
1406 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1408 uint32 entry = fields[10].GetUInt32();
1409 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1410 if(cInfo)
1412 petDisplayId = fields[11].GetUInt32();
1413 petLevel = fields[12].GetUInt32();
1414 petFamily = cInfo->family;
1418 *p_data << uint32(petDisplayId);
1419 *p_data << uint32(petLevel);
1420 *p_data << uint32(petFamily);
1423 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1425 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1426 uint32 item_id = GetUInt32Value(visualbase);
1427 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1428 SpellItemEnchantmentEntry const *enchant = NULL;
1430 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1432 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1433 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1434 break;
1437 if (proto != NULL)
1439 *p_data << uint32(proto->DisplayInfoID);
1440 *p_data << uint8(proto->InventoryType);
1441 *p_data << uint32(enchant ? enchant->aura_id : 0);
1443 else
1445 *p_data << uint32(0);
1446 *p_data << uint8(0);
1447 *p_data << uint32(0); // enchant?
1450 *p_data << uint32(0); // first bag display id
1451 *p_data << uint8(0); // first bag inventory type
1452 *p_data << uint32(0); // enchant?
1455 bool Player::ToggleAFK()
1457 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1459 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1461 // afk player not allowed in battleground
1462 if(state && InBattleGround())
1463 LeaveBattleground();
1465 return state;
1468 bool Player::ToggleDND()
1470 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1472 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1475 uint8 Player::chatTag() const
1477 // it's bitmask
1478 // 0x8 - ??
1479 // 0x4 - gm
1480 // 0x2 - dnd
1481 // 0x1 - afk
1482 if(isGMChat())
1483 return 4;
1484 else if(isDND())
1485 return 3;
1486 if(isAFK())
1487 return 1;
1488 else
1489 return 0;
1492 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1494 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1496 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1497 return false;
1500 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1501 Pet* pet = GetPet();
1503 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1505 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1506 // don't let gm level > 1 either
1507 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1508 return false;
1510 // client without expansion support
1511 if(GetSession()->Expansion() < mEntry->Expansion())
1513 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1515 if(GetTransport())
1516 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1518 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1520 return false; // normal client can't teleport to this map...
1522 else
1524 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1527 // if we were on a transport, leave
1528 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1530 m_transport->RemovePassenger(this);
1531 m_transport = NULL;
1532 m_movementInfo.t_x = 0.0f;
1533 m_movementInfo.t_y = 0.0f;
1534 m_movementInfo.t_z = 0.0f;
1535 m_movementInfo.t_o = 0.0f;
1536 m_movementInfo.t_time = 0;
1539 SetSemaphoreTeleport(true);
1541 // The player was ported to another map and looses the duel immediately.
1542 // We have to perform this check before the teleport, otherwise the
1543 // ObjectAccessor won't find the flag.
1544 if (duel && GetMapId()!=mapid)
1546 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1547 if (obj)
1548 DuelComplete(DUEL_FLED);
1551 // reset movement flags at teleport, because player will continue move with these flags after teleport
1552 SetUnitMovementFlags(0);
1554 if ((GetMapId() == mapid) && (!m_transport))
1556 // prepare zone change detect
1557 uint32 old_zone = GetZoneId();
1559 // near teleport
1560 if(!GetSession()->PlayerLogout())
1562 WorldPacket data;
1563 BuildTeleportAckMsg(&data, x, y, z, orientation);
1564 GetSession()->SendPacket(&data);
1565 SetPosition( x, y, z, orientation, true);
1567 else
1568 // this will be used instead of the current location in SaveToDB
1569 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1570 SetFallInformation(0, z);
1572 //BuildHeartBeatMsg(&data);
1573 //SendMessageToSet(&data, true);
1574 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1576 //same map, only remove pet if out of range
1577 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1579 if(pet->isControlled() && !pet->isTemporarySummoned() )
1580 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1581 else
1582 m_temporaryUnsummonedPetNumber = 0;
1584 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1588 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1589 CombatStop();
1591 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1593 // resummon pet
1594 if(pet && m_temporaryUnsummonedPetNumber)
1596 Pet* NewPet = new Pet;
1597 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1598 delete NewPet;
1600 m_temporaryUnsummonedPetNumber = 0;
1604 if(!GetSession()->PlayerLogout())
1606 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1607 SetSemaphoreTeleport(false);
1609 UpdateZone(GetZoneId());
1612 // new zone
1613 if(old_zone != GetZoneId())
1615 // honorless target
1616 if(pvpInfo.inHostileArea)
1617 CastSpell(this, 2479, true);
1620 else
1622 // far teleport to another map
1623 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1624 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1626 // Check enter rights before map getting to avoid creating instance copy for player
1627 // this check not dependent from map instance copy and same for all instance copies of selected map
1628 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1630 SetSemaphoreTeleport(false);
1631 return false;
1634 // If the map is not created, assume it is possible to enter it.
1635 // It will be created in the WorldPortAck.
1636 Map *map = MapManager::Instance().FindMap(mapid);
1637 if (!map || map->CanEnter(this))
1639 SetSelection(0);
1641 CombatStop();
1643 ResetContestedPvP();
1645 // remove player from battleground on far teleport (when changing maps)
1646 if(BattleGround const* bg = GetBattleGround())
1648 // Note: at battleground join battleground id set before teleport
1649 // and we already will found "current" battleground
1650 // just need check that this is targeted map or leave
1651 if(bg->GetMapId() != mapid)
1652 LeaveBattleground(false); // don't teleport to entry point
1655 // remove pet on map change
1656 if (pet)
1658 //leaving map -> delete pet right away (doing this later will cause problems)
1659 if(pet->isControlled() && !pet->isTemporarySummoned())
1660 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1661 else
1662 m_temporaryUnsummonedPetNumber = 0;
1664 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1667 // remove all dyn objects
1668 RemoveAllDynObjects();
1670 // stop spellcasting
1671 // not attempt interrupt teleportation spell at caster teleport
1672 if(!(options & TELE_TO_SPELL))
1673 if(IsNonMeleeSpellCasted(true))
1674 InterruptNonMeleeSpells(true);
1676 if(!GetSession()->PlayerLogout())
1678 // send transfer packets
1679 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1680 data << uint32(mapid);
1681 if (m_transport)
1683 data << m_transport->GetEntry() << GetMapId();
1685 GetSession()->SendPacket(&data);
1687 data.Initialize(SMSG_NEW_WORLD, (20));
1688 if (m_transport)
1690 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1692 else
1694 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1696 GetSession()->SendPacket( &data );
1697 SendSavedInstances();
1699 // remove from old map now
1700 if(oldmap) oldmap->Remove(this, false);
1703 // new final coordinates
1704 float final_x = x;
1705 float final_y = y;
1706 float final_z = z;
1707 float final_o = orientation;
1709 if(m_transport)
1711 final_x += m_movementInfo.t_x;
1712 final_y += m_movementInfo.t_y;
1713 final_z += m_movementInfo.t_z;
1714 final_o += m_movementInfo.t_o;
1717 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1718 SetFallInformation(0, final_z);
1719 // if the player is saved before worldportack (at logout for example)
1720 // this will be used instead of the current location in SaveToDB
1722 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1724 // move packet sent by client always after far teleport
1725 // SetPosition(final_x, final_y, final_z, final_o, true);
1726 SetDontMove(true);
1728 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1730 else
1731 return false;
1733 return true;
1736 void Player::AddToWorld()
1738 ///- Do not add/remove the player from the object storage
1739 ///- It will crash when updating the ObjectAccessor
1740 ///- The player should only be added when logging in
1741 Unit::AddToWorld();
1743 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1745 if(m_items[i])
1746 m_items[i]->AddToWorld();
1750 void Player::RemoveFromWorld()
1752 // cleanup
1753 if(IsInWorld())
1755 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1756 Uncharm();
1757 UnsummonAllTotems();
1758 RemoveMiniPet();
1759 RemoveGuardians();
1762 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1764 if(m_items[i])
1765 m_items[i]->RemoveFromWorld();
1768 ///- Do not add/remove the player from the object storage
1769 ///- It will crash when updating the ObjectAccessor
1770 ///- The player should only be removed when logging out
1771 Unit::RemoveFromWorld();
1774 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1776 float addRage;
1778 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1780 if(attacker)
1782 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1784 // talent who gave more rage on attack
1785 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1787 else
1789 addRage = damage/rageconversion*2.5;
1791 // Berserker Rage effect
1792 if(HasAura(18499,0))
1793 addRage *= 1.3;
1796 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1798 ModifyPower(POWER_RAGE, uint32(addRage*10));
1801 void Player::RegenerateAll()
1803 if (m_regenTimer != 0)
1804 return;
1805 uint32 regenDelay = 2000;
1807 // Not in combat or they have regeneration
1808 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1809 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1811 RegenerateHealth();
1812 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1814 Regenerate(POWER_RAGE);
1815 if(getClass() == CLASS_DEATH_KNIGHT)
1816 Regenerate(POWER_RUNIC_POWER);
1820 Regenerate( POWER_ENERGY );
1822 Regenerate( POWER_MANA );
1824 if(getClass() == CLASS_DEATH_KNIGHT)
1825 Regenerate( POWER_RUNE );
1827 m_regenTimer = regenDelay;
1830 void Player::Regenerate(Powers power)
1832 uint32 curValue = GetPower(power);
1833 uint32 maxValue = GetMaxPower(power);
1835 float addvalue = 0.0f;
1837 switch (power)
1839 case POWER_MANA:
1841 bool recentCast = IsUnderLastManaUseEffect();
1842 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1843 if (recentCast)
1845 // Mangos Updates Mana in intervals of 2s, which is correct
1846 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1848 else
1850 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1852 } break;
1853 case POWER_RAGE: // Regenerate rage
1855 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1856 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1857 } break;
1858 case POWER_ENERGY: // Regenerate energy (rogue)
1859 addvalue = 20;
1860 break;
1861 case POWER_RUNIC_POWER:
1863 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1864 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1865 } break;
1866 case POWER_RUNE:
1868 for(uint32 i = 0; i < MAX_RUNES; ++i)
1869 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1870 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1871 } break;
1872 case POWER_FOCUS:
1873 case POWER_HAPPINESS:
1874 break;
1877 // Mana regen calculated in Player::UpdateManaRegen()
1878 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1879 if(power != POWER_MANA)
1881 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1882 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1883 if ((*i)->GetModifier()->m_miscvalue == power)
1884 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1887 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1889 curValue += uint32(addvalue);
1890 if (curValue > maxValue)
1891 curValue = maxValue;
1893 else
1895 if(curValue <= uint32(addvalue))
1896 curValue = 0;
1897 else
1898 curValue -= uint32(addvalue);
1900 SetPower(power, curValue);
1903 void Player::RegenerateHealth()
1905 uint32 curValue = GetHealth();
1906 uint32 maxValue = GetMaxHealth();
1908 if (curValue >= maxValue) return;
1910 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1912 float addvalue = 0.0f;
1914 // polymorphed case
1915 if ( IsPolymorphed() )
1916 addvalue = GetMaxHealth()/3;
1917 // normal regen case (maybe partly in combat case)
1918 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1920 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1921 if (!isInCombat())
1923 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1924 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1925 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1927 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1928 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1930 if(!IsStandState())
1931 addvalue *= 1.5;
1934 // always regeneration bonus (including combat)
1935 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1937 if(addvalue < 0)
1938 addvalue = 0;
1940 ModifyHealth(int32(addvalue));
1943 bool Player::CanInteractWithNPCs(bool alive) const
1945 if(alive && !isAlive())
1946 return false;
1947 if(isInFlight())
1948 return false;
1950 return true;
1953 bool Player::IsUnderWater() const
1955 return IsInWater() &&
1956 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1959 void Player::SetInWater(bool apply)
1961 if(m_isInWater==apply)
1962 return;
1964 //define player in water by opcodes
1965 //move player's guid into HateOfflineList of those mobs
1966 //which can't swim and move guid back into ThreatList when
1967 //on surface.
1968 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1969 m_isInWater = apply;
1971 // remove auras that need water/land
1972 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1974 getHostilRefManager().updateThreatTables();
1977 void Player::SetGameMaster(bool on)
1979 if(on)
1981 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1982 setFaction(35);
1983 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1985 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
1986 ResetContestedPvP();
1988 getHostilRefManager().setOnlineOfflineState(false);
1989 CombatStop();
1991 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
1993 else
1995 // restore phase
1996 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
1997 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
1999 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2000 setFactionForRace(getRace());
2001 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2003 // restore FFA PvP Server state
2004 if(sWorld.IsFFAPvPRealm())
2005 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2007 // restore FFA PvP area state, remove not allowed for GM mounts
2008 UpdateArea(m_areaUpdateId);
2010 getHostilRefManager().setOnlineOfflineState(true);
2013 ObjectAccessor::UpdateVisibilityForPlayer(this);
2016 void Player::SetGMVisible(bool on)
2018 if(on)
2020 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2022 // Reapply stealth/invisibility if active or show if not any
2023 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2024 SetVisibility(VISIBILITY_GROUP_STEALTH);
2025 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2026 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2027 else
2028 SetVisibility(VISIBILITY_ON);
2030 else
2032 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2034 SetAcceptWhispers(false);
2035 SetGameMaster(true);
2037 SetVisibility(VISIBILITY_OFF);
2041 bool Player::IsGroupVisibleFor(Player* p) const
2043 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2045 default: return IsInSameGroupWith(p);
2046 case 1: return IsInSameRaidWith(p);
2047 case 2: return GetTeam()==p->GetTeam();
2051 bool Player::IsInSameGroupWith(Player const* p) const
2053 return p==this || GetGroup() != NULL &&
2054 GetGroup() == p->GetGroup() &&
2055 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2058 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2059 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2060 void Player::UninviteFromGroup()
2062 Group* group = GetGroupInvite();
2063 if(!group)
2064 return;
2066 group->RemoveInvite(this);
2068 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2070 if(group->IsCreated())
2072 group->Disband(true);
2073 objmgr.RemoveGroup(group);
2075 else
2076 group->RemoveAllInvites();
2078 delete group;
2082 void Player::RemoveFromGroup(Group* group, uint64 guid)
2084 if(group)
2086 if (group->RemoveMember(guid, 0) <= 1)
2088 // group->Disband(); already disbanded in RemoveMember
2089 objmgr.RemoveGroup(group);
2090 delete group;
2091 // removemember sets the player's group pointer to NULL
2096 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2098 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2099 data << uint64(victim ? victim->GetGUID() : 0); // guid
2100 data << uint32(GivenXP+RestXP); // given experience
2101 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2102 if(victim)
2104 data << uint32(GivenXP); // experience without rested bonus
2105 data << float(1); // 1 - none 0 - 100% group bonus output
2107 data << uint8(0); // new 2.4.0
2108 GetSession()->SendPacket(&data);
2111 void Player::GiveXP(uint32 xp, Unit* victim)
2113 if ( xp < 1 )
2114 return;
2116 if(!isAlive())
2117 return;
2119 uint32 level = getLevel();
2121 // XP to money conversion processed in Player::RewardQuest
2122 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2123 return;
2125 // handle SPELL_AURA_MOD_XP_PCT auras
2126 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2127 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2128 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2130 // XP resting bonus for kill
2131 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2133 SendLogXPGain(xp,victim,rested_bonus_xp);
2135 uint32 curXP = GetUInt32Value(PLAYER_XP);
2136 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2137 uint32 newXP = curXP + xp + rested_bonus_xp;
2139 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2141 newXP -= nextLvlXP;
2143 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2144 GiveLevel(level + 1);
2146 level = getLevel();
2147 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2150 SetUInt32Value(PLAYER_XP, newXP);
2153 // Update player to next level
2154 // Current player experience not update (must be update by caller)
2155 void Player::GiveLevel(uint32 level)
2157 if ( level == getLevel() )
2158 return;
2160 PlayerLevelInfo info;
2161 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2163 PlayerClassLevelInfo classInfo;
2164 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2166 // send levelup info to client
2167 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2168 data << uint32(level);
2169 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2170 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2171 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2172 data << uint32(0);
2173 data << uint32(0);
2174 data << uint32(0);
2175 data << uint32(0);
2176 data << uint32(0);
2177 data << uint32(0);
2178 // end for
2179 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2180 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2182 GetSession()->SendPacket(&data);
2184 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2186 //update level, max level of skills
2187 if(getLevel()!= level)
2188 m_Played_time[1] = 0; // Level Played Time reset
2189 SetLevel(level);
2190 UpdateSkillsForLevel ();
2192 // save base values (bonuses already included in stored stats
2193 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2194 SetCreateStat(Stats(i), info.stats[i]);
2196 SetCreateHealth(classInfo.basehealth);
2197 SetCreateMana(classInfo.basemana);
2199 InitTalentForLevel();
2200 InitTaxiNodesForLevel();
2201 InitGlyphsForLevel();
2203 UpdateAllStats();
2205 // set current level health and mana/energy to maximum after applying all mods.
2206 SetHealth(GetMaxHealth());
2207 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2208 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2209 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2210 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2211 SetPower(POWER_FOCUS, 0);
2212 SetPower(POWER_HAPPINESS, 0);
2214 // give level to summoned pet
2215 Pet* pet = GetPet();
2216 if(pet && pet->getPetType()==SUMMON_PET)
2217 pet->GivePetLevel(level);
2218 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2221 void Player::InitTalentForLevel()
2223 uint32 level = getLevel();
2224 // talents base at level diff ( talents = level - 9 but some can be used already)
2225 if(level < 10)
2227 // Remove all talent points
2228 if(m_usedTalentCount > 0) // Free any used talents
2230 resetTalents(true);
2231 SetFreeTalentPoints(0);
2234 else
2236 uint32 talentPointsForLevel = CalculateTalentsPoints();
2238 // if used more that have then reset
2239 if(m_usedTalentCount > talentPointsForLevel)
2241 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2242 resetTalents(true);
2243 else
2244 SetFreeTalentPoints(0);
2246 // else update amount of free points
2247 else
2248 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2252 void Player::InitStatsForLevel(bool reapplyMods)
2254 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2255 _RemoveAllStatBonuses();
2257 PlayerClassLevelInfo classInfo;
2258 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2260 PlayerLevelInfo info;
2261 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2263 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2264 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2266 UpdateSkillsForLevel ();
2268 // set default cast time multiplier
2269 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2271 // reset size before reapply auras
2272 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2274 // save base values (bonuses already included in stored stats
2275 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2276 SetCreateStat(Stats(i), info.stats[i]);
2278 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2279 SetStat(Stats(i), info.stats[i]);
2281 SetCreateHealth(classInfo.basehealth);
2283 //set create powers
2284 SetCreateMana(classInfo.basemana);
2286 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2288 InitStatBuffMods();
2290 //reset rating fields values
2291 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2292 SetUInt32Value(index, 0);
2294 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2295 for (int i = 0; i < 7; i++)
2297 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2298 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2299 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2302 //reset attack power, damage and attack speed fields
2303 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2304 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2305 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2307 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2308 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2309 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2310 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2311 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2312 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2314 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2315 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2316 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2317 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2318 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2319 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2321 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2322 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2323 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2324 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2326 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2327 for (uint8 i = 0; i < 7; ++i)
2328 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2330 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2331 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2332 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2334 // Dodge percentage
2335 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2337 // set armor (resistance 0) to original value (create_agility*2)
2338 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2339 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2340 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2341 // set other resistance to original value (0)
2342 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2344 SetResistance(SpellSchools(i), 0);
2345 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2346 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2349 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2350 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2351 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2353 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2354 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2356 // Reset no reagent cost field
2357 for(int i = 0; i < 3; i++)
2358 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2359 // Init data for form but skip reapply item mods for form
2360 InitDataForForm(reapplyMods);
2362 // save new stats
2363 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2364 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2366 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2368 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2369 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2371 // cleanup unit flags (will be re-applied if need at aura load).
2372 RemoveFlag( UNIT_FIELD_FLAGS,
2373 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2374 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2375 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2376 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2377 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2378 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2380 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2382 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2383 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2385 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2386 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2388 // restore if need some important flags
2389 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2391 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2392 _ApplyAllStatBonuses();
2394 // set current level health and mana/energy to maximum after applying all mods.
2395 SetHealth(GetMaxHealth());
2396 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2397 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2398 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2399 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2400 SetPower(POWER_FOCUS, 0);
2401 SetPower(POWER_HAPPINESS, 0);
2402 SetPower(POWER_RUNIC_POWER, 0);
2405 void Player::SendInitialSpells()
2407 time_t curTime = time(NULL);
2408 time_t infTime = curTime + MONTH/2;
2410 uint16 spellCount = 0;
2412 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2413 data << uint8(0);
2415 size_t countPos = data.wpos();
2416 data << uint16(spellCount); // spell count placeholder
2418 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2420 if(itr->second->state == PLAYERSPELL_REMOVED)
2421 continue;
2423 if(!itr->second->active || itr->second->disabled)
2424 continue;
2426 data << uint16(itr->first);
2427 data << uint16(0); // it's not slot id
2429 spellCount +=1;
2432 data.put<uint16>(countPos,spellCount); // write real count value
2434 uint16 spellCooldowns = m_spellCooldowns.size();
2435 data << uint16(spellCooldowns);
2436 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2438 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2439 if(!sEntry)
2440 continue;
2442 // not send infinity cooldown
2443 if(itr->second.end > infTime)
2444 continue;
2446 data << uint16(itr->first);
2448 time_t cooldown = 0;
2449 if(itr->second.end > curTime)
2450 cooldown = (itr->second.end-curTime)*IN_MILISECONDS;
2452 data << uint16(itr->second.itemid); // cast item id
2453 data << uint16(sEntry->Category); // spell category
2454 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2456 data << uint32(0); // cooldown
2457 data << uint32(cooldown); // category cooldown
2459 else
2461 data << uint32(cooldown); // cooldown
2462 data << uint32(0); // category cooldown
2466 GetSession()->SendPacket(&data);
2468 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2471 void Player::RemoveMail(uint32 id)
2473 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2475 if ((*itr)->messageID == id)
2477 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2478 m_mail.erase(itr);
2479 return;
2484 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2486 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2487 data << (uint32) mailId;
2488 data << (uint32) mailAction;
2489 data << (uint32) mailError;
2490 if ( mailError == MAIL_ERR_BAG_FULL )
2491 data << (uint32) equipError;
2492 else if( mailAction == MAIL_ITEM_TAKEN )
2494 data << (uint32) item_guid; // item guid low?
2495 data << (uint32) item_count; // item count?
2497 GetSession()->SendPacket(&data);
2500 void Player::SendNewMail()
2502 // deliver undelivered mail
2503 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2504 data << (uint32) 0;
2505 GetSession()->SendPacket(&data);
2508 void Player::UpdateNextMailTimeAndUnreads()
2510 // calculate next delivery time (min. from non-delivered mails
2511 // and recalculate unReadMail
2512 time_t cTime = time(NULL);
2513 m_nextMailDelivereTime = 0;
2514 unReadMails = 0;
2515 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2517 if((*itr)->deliver_time > cTime)
2519 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2520 m_nextMailDelivereTime = (*itr)->deliver_time;
2522 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2523 ++unReadMails;
2527 void Player::AddNewMailDeliverTime(time_t deliver_time)
2529 if(deliver_time <= time(NULL)) // ready now
2531 ++unReadMails;
2532 SendNewMail();
2534 else // not ready and no have ready mails
2536 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2537 m_nextMailDelivereTime = deliver_time;
2541 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2543 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2544 if (!spellInfo)
2546 // do character spell book cleanup (all characters)
2547 if(!IsInWorld() && !learning) // spell load case
2549 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2550 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2552 else
2553 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2555 return false;
2558 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2560 // do character spell book cleanup (all characters)
2561 if(!IsInWorld() && !learning) // spell load case
2563 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2564 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2566 else
2567 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2569 return false;
2572 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2574 bool dependent_set = false;
2575 bool disabled_case = false;
2576 bool superceded_old = false;
2578 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2579 if (itr != m_spells.end())
2581 uint32 next_active_spell_id = 0;
2582 // fix activate state for non-stackable low rank (and find next spell for !active case)
2583 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2585 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2586 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2588 if(HasSpell(next_itr->second))
2590 // high rank already known so this must !active
2591 active = false;
2592 next_active_spell_id = next_itr->second;
2593 break;
2598 // not do anything if already known in expected state
2599 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2600 itr->second->dependent == dependent && itr->second->disabled == disabled)
2602 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2603 itr->second->state = PLAYERSPELL_UNCHANGED;
2605 return false;
2608 // dependent spell known as not dependent, overwrite state
2609 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2611 itr->second->dependent = dependent;
2612 if (itr->second->state != PLAYERSPELL_NEW)
2613 itr->second->state = PLAYERSPELL_CHANGED;
2614 dependent_set = true;
2617 // update active state for known spell
2618 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2620 itr->second->active = active;
2622 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2623 itr->second->state = PLAYERSPELL_UNCHANGED;
2624 else if(itr->second->state != PLAYERSPELL_NEW)
2625 itr->second->state = PLAYERSPELL_CHANGED;
2627 if(active)
2629 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2630 CastSpell (this,spell_id,true);
2632 else if(IsInWorld())
2634 if(next_active_spell_id)
2636 // update spell ranks in spellbook and action bar
2637 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2638 data << uint16(spell_id);
2639 data << uint16(next_active_spell_id);
2640 GetSession()->SendPacket( &data );
2642 else
2644 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2645 data << uint16(spell_id);
2646 GetSession()->SendPacket(&data);
2650 return active; // learn (show in spell book if active now)
2653 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2655 if(itr->second->state != PLAYERSPELL_NEW)
2656 itr->second->state = PLAYERSPELL_CHANGED;
2657 itr->second->disabled = disabled;
2659 if(disabled)
2660 return false;
2662 disabled_case = true;
2664 else switch(itr->second->state)
2666 case PLAYERSPELL_UNCHANGED: // known saved spell
2667 return false;
2668 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2670 delete itr->second;
2671 m_spells.erase(itr);
2672 state = PLAYERSPELL_CHANGED;
2673 break; // need re-add
2675 default: // known not saved yet spell (new or modified)
2677 // can be in case spell loading but learned at some previous spell loading
2678 if(!IsInWorld() && !learning && !dependent_set)
2679 itr->second->state = PLAYERSPELL_UNCHANGED;
2681 return false;
2686 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2688 // talent: unlearn all other talent ranks (high and low)
2689 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2691 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2693 for(int i=0; i <5; ++i)
2695 // skip learning spell and no rank spell case
2696 uint32 rankSpellId = talentInfo->RankID[i];
2697 if(!rankSpellId || rankSpellId==spell_id)
2698 continue;
2700 removeSpell(rankSpellId);
2704 // non talent spell: learn low ranks (recursive call)
2705 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2707 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2708 addSpell(prev_spell,active,true,true,disabled);
2709 else // at normal learning
2710 learnSpell(prev_spell,true);
2713 PlayerSpell *newspell = new PlayerSpell;
2714 newspell->state = state;
2715 newspell->active = active;
2716 newspell->dependent = dependent;
2717 newspell->disabled = disabled;
2719 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2720 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2722 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2724 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2725 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2726 if(!i_spellInfo) continue;
2728 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2730 if(itr->second->active)
2732 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2734 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2736 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2737 data << uint16(itr->first);
2738 data << uint16(spell_id);
2739 GetSession()->SendPacket( &data );
2742 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2743 itr->second->active = false;
2744 if(itr->second->state != PLAYERSPELL_NEW)
2745 itr->second->state = PLAYERSPELL_CHANGED;
2746 superceded_old = true; // new spell replace old in action bars and spell book.
2748 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2750 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2752 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2753 data << uint16(spell_id);
2754 data << uint16(itr->first);
2755 GetSession()->SendPacket( &data );
2758 // mark new spell as disable (not learned yet for client and will not learned)
2759 newspell->active = false;
2760 if(newspell->state != PLAYERSPELL_NEW)
2761 newspell->state = PLAYERSPELL_CHANGED;
2768 m_spells[spell_id] = newspell;
2770 // return false if spell disabled
2771 if (newspell->disabled)
2772 return false;
2775 uint32 talentCost = GetTalentSpellCost(spell_id);
2777 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2778 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2779 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2781 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2782 CastSpell(this, spell_id, true);
2784 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2785 else if (IsPassiveSpell(spell_id))
2787 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2788 CastSpell(this, spell_id, true);
2790 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2792 CastSpell(this, spell_id, true);
2793 return false;
2796 // update used talent points count
2797 m_usedTalentCount += talentCost;
2799 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2800 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2802 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2803 SetFreePrimaryProffesions(freeProfs-1);
2806 // add dependent skills
2807 uint16 maxskill = GetMaxSkillValueForLevel();
2809 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2811 if(spellLearnSkill)
2813 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2814 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2816 if(skill_value < spellLearnSkill->value)
2817 skill_value = spellLearnSkill->value;
2819 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2821 if(skill_max_value < new_skill_max_value)
2822 skill_max_value = new_skill_max_value;
2824 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2826 else
2828 // not ranked skills
2829 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2830 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2832 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2834 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2835 if(!pSkill)
2836 continue;
2838 if(HasSkill(pSkill->id))
2839 continue;
2841 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2842 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2843 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2845 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2847 case SKILL_RANGE_LANGUAGE:
2848 SetSkill(pSkill->id, 300, 300 );
2849 break;
2850 case SKILL_RANGE_LEVEL:
2851 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2852 break;
2853 case SKILL_RANGE_MONO:
2854 SetSkill(pSkill->id, 1, 1 );
2855 break;
2856 default:
2857 break;
2863 // learn dependent spells
2864 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2865 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2867 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2869 if(!itr->second.autoLearned)
2871 if(!IsInWorld() || !itr->second.active) // at spells loading, no output, but allow save
2872 addSpell(itr->second.spell,itr->second.active,true,true,false);
2873 else // at normal learning
2874 learnSpell(itr->second.spell,true);
2878 if(IsInWorld())
2880 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL);
2881 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS);
2884 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2885 return active && !disabled && !superceded_old;
2888 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
2890 bool need_cast = false;
2892 switch(spellInfo->Id)
2894 // some spells not have stance data expacted cast at form change or present
2895 case 5420: need_cast = (m_form == FORM_TREE); break;
2896 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
2897 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
2898 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
2899 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
2900 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
2901 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
2902 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
2903 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2904 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2905 // another spells have proper stance data
2906 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
2909 //Check CasterAuraStates
2910 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
2913 void Player::learnSpell(uint32 spell_id, bool dependent)
2915 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2917 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2918 bool active = disabled ? itr->second->active : true;
2920 bool learning = addSpell(spell_id,active,true,dependent,false);
2922 // learn all disabled higher ranks (recursive)
2923 if(disabled)
2925 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2926 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2928 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2929 if (iter != m_spells.end() && iter->second->disabled)
2930 learnSpell(i->second,false);
2934 // prevent duplicated entires in spell book, also not send if not in world (loading)
2935 if(!learning || !IsInWorld ())
2936 return;
2938 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2939 data << uint32(spell_id);
2940 GetSession()->SendPacket(&data);
2943 void Player::removeSpell(uint32 spell_id, bool disabled, bool update_action_bar_for_low_rank)
2945 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2946 if (itr == m_spells.end())
2947 return;
2949 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2950 return;
2952 // unlearn non talent higher ranks (recursive)
2953 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2954 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2955 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2956 removeSpell(itr2->second,disabled);
2958 bool cur_active = itr->second->active;
2959 bool cur_dependent = itr->second->dependent;
2961 if (disabled)
2963 itr->second->disabled = disabled;
2964 if(itr->second->state != PLAYERSPELL_NEW)
2965 itr->second->state = PLAYERSPELL_CHANGED;
2967 else
2969 if(itr->second->state == PLAYERSPELL_NEW)
2971 delete itr->second;
2972 m_spells.erase(itr);
2974 else
2975 itr->second->state = PLAYERSPELL_REMOVED;
2978 RemoveAurasDueToSpell(spell_id);
2980 // remove pet auras
2981 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2982 RemovePetAura(petSpell);
2984 // free talent points
2985 uint32 talentCosts = GetTalentSpellCost(spell_id);
2986 if(talentCosts > 0)
2988 if(talentCosts < m_usedTalentCount)
2989 m_usedTalentCount -= talentCosts;
2990 else
2991 m_usedTalentCount = 0;
2994 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2995 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2997 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2998 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
2999 SetFreePrimaryProffesions(freeProfs);
3002 // remove dependent skill
3003 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3004 if(spellLearnSkill)
3006 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3007 if(!prev_spell) // first rank, remove skill
3008 SetSkill(spellLearnSkill->skill,0,0);
3009 else
3011 // search prev. skill setting by spell ranks chain
3012 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3013 while(!prevSkill && prev_spell)
3015 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3016 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3019 if(!prevSkill) // not found prev skill setting, remove skill
3020 SetSkill(spellLearnSkill->skill,0,0);
3021 else // set to prev. skill setting values
3023 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3024 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3026 if(skill_value > prevSkill->value)
3027 skill_value = prevSkill->value;
3029 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3031 if(skill_max_value > new_skill_max_value)
3032 skill_max_value = new_skill_max_value;
3034 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3039 else
3041 // not ranked skills
3042 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3043 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3045 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3047 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3048 if(!pSkill)
3049 continue;
3051 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3052 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3053 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
3055 // not reset skills for professions and racial abilities
3056 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3057 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3058 continue;
3060 SetSkill(pSkill->id, 0, 0 );
3065 // remove dependent spells
3066 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3067 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3069 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3070 removeSpell(itr2->second.spell, disabled);
3072 // activate lesser rank in spellbook/action bar, and cast it if need
3073 bool prev_activate = false;
3075 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3077 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3079 // if talent then lesser rank also talent and need learn
3080 if(talentCosts)
3081 learnSpell (prev_id,false);
3082 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3083 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3085 // need manually update dependence state (learn spell ignore like attempts)
3086 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3087 if (prev_itr != m_spells.end())
3089 if(prev_itr->second->dependent != cur_dependent)
3091 prev_itr->second->dependent = cur_dependent;
3092 if(prev_itr->second->state != PLAYERSPELL_NEW)
3093 prev_itr->second->state = PLAYERSPELL_CHANGED;
3096 // now re-learn if need re-activate
3097 if(cur_active && !prev_itr->second->active)
3099 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3101 if(update_action_bar_for_low_rank)
3103 // downgrade spell ranks in spellbook and action bar
3104 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
3105 data << uint16(spell_id);
3106 data << uint16(prev_id);
3107 GetSession()->SendPacket( &data );
3108 prev_activate = true;
3116 // remove from spell book if not replaced by lesser rank
3117 if(!prev_activate)
3119 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3120 data << uint16(spell_id);
3121 GetSession()->SendPacket(&data);
3125 void Player::RemoveArenaSpellCooldowns()
3127 // remove cooldowns on spells that has < 15 min CD
3128 SpellCooldowns::iterator itr, next;
3129 // iterate spell cooldowns
3130 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3132 next = itr;
3133 ++next;
3134 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3135 // check if spellentry is present and if the cooldown is less than 15 mins
3136 if( entry &&
3137 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3138 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3140 // notify player
3141 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3142 data << uint32(itr->first);
3143 data << GetGUID();
3144 GetSession()->SendPacket(&data);
3145 // remove cooldown
3146 m_spellCooldowns.erase(itr);
3151 void Player::RemoveAllSpellCooldown()
3153 if(!m_spellCooldowns.empty())
3155 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3157 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3158 data << uint32(itr->first);
3159 data << uint64(GetGUID());
3160 GetSession()->SendPacket(&data);
3162 m_spellCooldowns.clear();
3166 void Player::_LoadSpellCooldowns(QueryResult *result)
3168 // some cooldowns can be already set at aura loading...
3170 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3172 if(result)
3174 time_t curTime = time(NULL);
3178 Field *fields = result->Fetch();
3180 uint32 spell_id = fields[0].GetUInt32();
3181 uint32 item_id = fields[1].GetUInt32();
3182 time_t db_time = (time_t)fields[2].GetUInt64();
3184 if(!sSpellStore.LookupEntry(spell_id))
3186 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3187 continue;
3190 // skip outdated cooldown
3191 if(db_time <= curTime)
3192 continue;
3194 AddSpellCooldown(spell_id, item_id, db_time);
3196 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3198 while( result->NextRow() );
3200 delete result;
3204 void Player::_SaveSpellCooldowns()
3206 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3208 time_t curTime = time(NULL);
3209 time_t infTime = curTime + MONTH/2;
3211 // remove outdated and save active
3212 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3214 if(itr->second.end <= curTime)
3215 m_spellCooldowns.erase(itr++);
3216 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3218 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));
3219 ++itr;
3221 else
3222 ++itr;
3226 uint32 Player::resetTalentsCost() const
3228 // The first time reset costs 1 gold
3229 if(m_resetTalentsCost < 1*GOLD)
3230 return 1*GOLD;
3231 // then 5 gold
3232 else if(m_resetTalentsCost < 5*GOLD)
3233 return 5*GOLD;
3234 // After that it increases in increments of 5 gold
3235 else if(m_resetTalentsCost < 10*GOLD)
3236 return 10*GOLD;
3237 else
3239 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3240 if(months > 0)
3242 // This cost will be reduced by a rate of 5 gold per month
3243 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3244 // to a minimum of 10 gold.
3245 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3247 else
3249 // After that it increases in increments of 5 gold
3250 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3251 // until it hits a cap of 50 gold.
3252 if(new_cost > 50*GOLD)
3253 new_cost = 50*GOLD;
3254 return new_cost;
3259 bool Player::resetTalents(bool no_cost)
3261 // not need after this call
3262 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3264 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3265 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3268 uint32 talentPointsForLevel = CalculateTalentsPoints();
3270 if (m_usedTalentCount == 0)
3272 SetFreeTalentPoints(talentPointsForLevel);
3273 return false;
3276 uint32 cost = 0;
3278 if(!no_cost)
3280 cost = resetTalentsCost();
3282 if (GetMoney() < cost)
3284 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3285 return false;
3289 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3291 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3293 if (!talentInfo) continue;
3295 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3297 if(!talentTabInfo)
3298 continue;
3300 // unlearn only talents for character class
3301 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3302 // to prevent unexpected lost normal learned spell skip another class talents
3303 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3304 continue;
3306 for (int j = 0; j < 5; j++)
3308 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3310 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3312 ++itr;
3313 continue;
3316 // remove learned spells (all ranks)
3317 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3319 // unlearn if first rank is talent or learned by talent
3320 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3322 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3323 itr = GetSpellMap().begin();
3324 continue;
3326 else
3327 ++itr;
3332 SetFreeTalentPoints(talentPointsForLevel);
3334 if(!no_cost)
3336 ModifyMoney(-(int32)cost);
3338 m_resetTalentsCost = cost;
3339 m_resetTalentsTime = time(NULL);
3342 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3343 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3345 if(m_canTitanGrip)
3347 m_canTitanGrip = false;
3348 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3349 AutoUnequipOffhandIfNeed();
3352 return true;
3355 Mail* Player::GetMail(uint32 id)
3357 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3359 if ((*itr)->messageID == id)
3361 return (*itr);
3364 return NULL;
3367 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3369 if(target == this)
3371 Object::_SetCreateBits(updateMask, target);
3373 else
3375 for(uint16 index = 0; index < m_valuesCount; index++)
3377 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3378 updateMask->SetBit(index);
3383 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3385 if(target == this)
3387 Object::_SetUpdateBits(updateMask, target);
3389 else
3391 Object::_SetUpdateBits(updateMask, target);
3392 *updateMask &= updateVisualBits;
3396 void Player::InitVisibleBits()
3398 updateVisualBits.SetCount(PLAYER_END);
3400 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3401 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3402 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3403 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3404 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3405 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3406 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3407 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3408 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3409 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3410 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3411 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3412 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3413 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3414 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3415 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3416 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3417 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3418 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3419 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3420 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3421 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3422 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3423 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3424 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3425 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3426 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3427 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3428 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3429 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3430 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3431 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3432 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3433 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3434 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3435 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3436 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3437 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3438 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3439 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3440 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3441 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3442 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3443 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3444 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3445 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3446 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3447 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3448 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3449 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3450 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3451 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3452 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3453 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3454 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3456 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3457 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3458 updateVisualBits.SetBit(PLAYER_FLAGS);
3459 updateVisualBits.SetBit(PLAYER_GUILDID);
3460 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3461 updateVisualBits.SetBit(PLAYER_BYTES);
3462 updateVisualBits.SetBit(PLAYER_BYTES_2);
3463 updateVisualBits.SetBit(PLAYER_BYTES_3);
3464 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3465 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3467 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3468 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3469 updateVisualBits.SetBit(i);
3471 // Players visible items are not inventory stuff
3472 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3474 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3476 // item creator
3477 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3478 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3480 // item entry
3481 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3483 // item enchantments
3484 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3485 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3487 // random properties
3488 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3489 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3490 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3493 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3496 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3498 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3500 if(m_items[i] == NULL)
3501 continue;
3503 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3506 if(target == this)
3508 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3510 if(m_items[i] == NULL)
3511 continue;
3513 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3515 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3517 if(m_items[i] == NULL)
3518 continue;
3520 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3524 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3527 void Player::DestroyForPlayer( Player *target ) const
3529 Unit::DestroyForPlayer( target );
3531 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3533 if(m_items[i] == NULL)
3534 continue;
3536 m_items[i]->DestroyForPlayer( target );
3539 if(target == this)
3541 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3543 if(m_items[i] == NULL)
3544 continue;
3546 m_items[i]->DestroyForPlayer( target );
3548 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3550 if(m_items[i] == NULL)
3551 continue;
3553 m_items[i]->DestroyForPlayer( target );
3558 bool Player::HasSpell(uint32 spell) const
3560 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3561 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3562 !itr->second->disabled);
3565 bool Player::HasActiveSpell(uint32 spell) const
3567 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3568 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3569 itr->second->active && !itr->second->disabled);
3572 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3574 if (!trainer_spell)
3575 return TRAINER_SPELL_RED;
3577 if (!trainer_spell->learnedSpell)
3578 return TRAINER_SPELL_RED;
3580 // known spell
3581 if(HasSpell(trainer_spell->learnedSpell))
3582 return TRAINER_SPELL_GRAY;
3584 // check race/class requirement
3585 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3586 return TRAINER_SPELL_RED;
3588 // check level requirement
3589 if(getLevel() < trainer_spell->reqLevel)
3590 return TRAINER_SPELL_RED;
3592 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3594 // check prev.rank requirement
3595 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3596 return TRAINER_SPELL_RED;
3598 // check additional spell requirement
3599 if(spell_chain->req && !HasSpell(spell_chain->req))
3600 return TRAINER_SPELL_RED;
3603 // check skill requirement
3604 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3605 return TRAINER_SPELL_RED;
3607 // exist, already checked at loading
3608 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3610 // secondary prof. or not prof. spell
3611 uint32 skill = spell->EffectMiscValue[1];
3613 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3614 return TRAINER_SPELL_GREEN;
3616 // check primary prof. limit
3617 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3618 return TRAINER_SPELL_RED;
3620 return TRAINER_SPELL_GREEN;
3623 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3625 uint32 guid = GUID_LOPART(playerguid);
3627 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3628 // bones will be deleted by corpse/bones deleting thread shortly
3629 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3631 // remove from guild
3632 uint32 guildId = GetGuildIdFromDB(playerguid);
3633 if(guildId != 0)
3635 Guild* guild = objmgr.GetGuildById(guildId);
3636 if(guild)
3637 guild->DelMember(guid);
3640 // remove from arena teams
3641 LeaveAllArenaTeams(playerguid);
3643 // the player was uninvited already on logout so just remove from group
3644 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3645 if(resultGroup)
3647 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3648 delete resultGroup;
3649 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3650 if(group)
3652 RemoveFromGroup(group, playerguid);
3656 // remove signs from petitions (also remove petitions if owner);
3657 RemovePetitionsAndSigns(playerguid, 10);
3659 // return back all mails with COD and Item 0 1 2 3 4 5 6
3660 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);
3661 if(resultMail)
3665 Field *fields = resultMail->Fetch();
3667 uint32 mail_id = fields[0].GetUInt32();
3668 uint16 mailTemplateId= fields[1].GetUInt16();
3669 uint32 sender = fields[2].GetUInt32();
3670 std::string subject = fields[3].GetCppString();
3671 uint32 itemTextId = fields[4].GetUInt32();
3672 uint32 money = fields[5].GetUInt32();
3673 bool has_items = fields[6].GetBool();
3675 //we can return mail now
3676 //so firstly delete the old one
3677 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3679 MailItemsInfo mi;
3680 if(has_items)
3682 // data needs to be at first place for Item::LoadFromDB
3683 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);
3684 if(resultItems)
3688 Field *fields2 = resultItems->Fetch();
3690 uint32 item_guidlow = fields2[1].GetUInt32();
3691 uint32 item_template = fields2[2].GetUInt32();
3693 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3694 if(!itemProto)
3696 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3697 continue;
3700 Item *pItem = NewItemOrBag(itemProto);
3701 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3703 pItem->FSetState(ITEM_REMOVED);
3704 pItem->SaveToDB(); // it also deletes item object !
3705 continue;
3708 mi.AddItem(item_guidlow, item_template, pItem);
3710 while (resultItems->NextRow());
3712 delete resultItems;
3716 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3718 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3720 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3722 while (resultMail->NextRow());
3724 delete resultMail;
3727 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3728 // Get guids of character's pets, will deleted in transaction
3729 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3731 // NOW we can finally clear other DB data related to character
3732 CharacterDatabase.BeginTransaction();
3733 if (resultPets)
3737 Field *fields3 = resultPets->Fetch();
3738 uint32 petguidlow = fields3[0].GetUInt32();
3739 Pet::DeleteFromDB(petguidlow);
3740 } while (resultPets->NextRow());
3741 delete resultPets;
3744 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3745 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3746 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3747 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3748 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3749 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3750 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3751 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3752 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3753 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3754 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3755 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3756 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3757 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3758 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3759 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3760 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3761 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3762 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3763 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3764 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3765 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3766 CharacterDatabase.CommitTransaction();
3768 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3769 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3772 void Player::SetMovement(PlayerMovementType pType)
3774 WorldPacket data;
3775 switch(pType)
3777 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3778 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3779 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3780 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3781 default:
3782 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3783 return;
3785 data.append(GetPackGUID());
3786 data << uint32(0);
3787 GetSession()->SendPacket( &data );
3790 /* Preconditions:
3791 - a resurrectable corpse must not be loaded for the player (only bones)
3792 - the player must be in world
3794 void Player::BuildPlayerRepop()
3796 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3797 data.append(GetPackGUID());
3798 GetSession()->SendPacket(&data);
3800 if(getRace() == RACE_NIGHTELF)
3801 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)
3802 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3804 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3805 // there must be SMSG.STOP_MIRROR_TIMER
3806 // there we must send 888 opcode
3808 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3809 if(GetCorpse())
3811 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3812 assert(false);
3815 // create a corpse and place it at the player's location
3816 CreateCorpse();
3817 Corpse *corpse = GetCorpse();
3818 if(!corpse)
3820 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3821 return;
3823 GetMap()->Add(corpse);
3825 // convert player body to ghost
3826 SetHealth( 1 );
3828 SetMovement(MOVE_WATER_WALK);
3829 if(!GetSession()->isLogingOut())
3830 SetMovement(MOVE_UNROOT);
3832 // BG - remove insignia related
3833 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3835 SendCorpseReclaimDelay();
3837 // to prevent cheating
3838 corpse->ResetGhostTime();
3840 StopMirrorTimers(); //disable timers(bars)
3842 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3844 // set and clear other
3845 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
3848 void Player::SendDelayResponse(const uint32 ml_seconds)
3850 //FIXME: is this delay time arg really need? 50msec by default in code
3851 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3852 data << (uint32)time(NULL);
3853 data << (uint32)0;
3854 GetSession()->SendPacket( &data );
3857 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3859 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3860 data << uint32(-1);
3861 data << float(0);
3862 data << float(0);
3863 data << float(0);
3864 GetSession()->SendPacket(&data);
3866 // speed change, land walk
3868 // remove death flag + set aura
3869 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3870 if(getRace() == RACE_NIGHTELF)
3871 RemoveAurasDueToSpell(20584); // speed bonuses
3872 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3874 setDeathState(ALIVE);
3876 SetMovement(MOVE_LAND_WALK);
3877 SetMovement(MOVE_UNROOT);
3879 m_deathTimer = 0;
3881 // set health/powers (0- will be set in caller)
3882 if(restore_percent>0.0f)
3884 SetHealth(uint32(GetMaxHealth()*restore_percent));
3885 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3886 SetPower(POWER_RAGE, 0);
3887 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3890 // trigger update zone for alive state zone updates
3891 UpdateZone(GetZoneId());
3893 // update visibility
3894 ObjectAccessor::UpdateVisibilityForPlayer(this);
3896 if(!applySickness)
3897 return;
3899 //Characters from level 1-10 are not affected by resurrection sickness.
3900 //Characters from level 11-19 will suffer from one minute of sickness
3901 //for each level they are above 10.
3902 //Characters level 20 and up suffer from ten minutes of sickness.
3903 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3905 if(int32(getLevel()) >= startLevel)
3907 // set resurrection sickness
3908 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3910 // not full duration
3911 if(int32(getLevel()) < startLevel+9)
3913 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3915 for(int i =0; i < 3; ++i)
3917 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3919 Aur->SetAuraDuration(delta*IN_MILISECONDS);
3920 Aur->SendAuraUpdate(false);
3927 void Player::KillPlayer()
3929 SetMovement(MOVE_ROOT);
3931 StopMirrorTimers(); //disable timers(bars)
3933 setDeathState(CORPSE);
3934 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3936 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3937 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3939 // 6 minutes until repop at graveyard
3940 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
3942 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3944 // don't create corpse at this moment, player might be falling
3946 // update visibility
3947 ObjectAccessor::UpdateObjectVisibility(this);
3950 void Player::CreateCorpse()
3952 // prevent existence 2 corpse for player
3953 SpawnCorpseBones();
3955 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3957 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3958 SetPvPDeath(false);
3960 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
3962 delete corpse;
3963 return;
3966 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3967 _pb = GetUInt32Value(PLAYER_BYTES);
3968 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3970 uint8 race = (uint8)(_uf);
3971 uint8 skin = (uint8)(_pb);
3972 uint8 face = (uint8)(_pb >> 8);
3973 uint8 hairstyle = (uint8)(_pb >> 16);
3974 uint8 haircolor = (uint8)(_pb >> 24);
3975 uint8 facialhair = (uint8)(_pb2);
3977 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3978 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3980 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3981 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3983 uint32 flags = CORPSE_FLAG_UNK2;
3984 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3985 flags |= CORPSE_FLAG_HIDE_HELM;
3986 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3987 flags |= CORPSE_FLAG_HIDE_CLOAK;
3988 if(InBattleGround())
3989 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3990 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3992 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3994 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
3996 uint32 iDisplayID;
3997 uint16 iIventoryType;
3998 uint32 _cfi;
3999 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
4001 if(m_items[i])
4003 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4004 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4006 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4007 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4011 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4012 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4013 assert(entry);
4014 if(entry->map_type != MAP_BATTLEGROUND)
4015 corpse->SaveToDB();
4017 // register for player, but not show
4018 ObjectAccessor::Instance().AddCorpse(corpse);
4021 void Player::SpawnCorpseBones()
4023 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4024 SaveToDB(); // prevent loading as ghost without corpse
4027 Corpse* Player::GetCorpse() const
4029 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4032 void Player::DurabilityLossAll(double percent, bool inventory)
4034 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
4035 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4036 DurabilityLoss(pItem,percent);
4038 if(inventory)
4040 // bags not have durability
4041 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4043 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
4044 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4045 DurabilityLoss(pItem,percent);
4047 // keys not have durability
4048 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4050 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4051 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4052 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
4053 if(Item* pItem = GetItemByPos( i, j ))
4054 DurabilityLoss(pItem,percent);
4058 void Player::DurabilityLoss(Item* item, double percent)
4060 if(!item )
4061 return;
4063 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4065 if(!pMaxDurability)
4066 return;
4068 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4070 if(pDurabilityLoss < 1 )
4071 pDurabilityLoss = 1;
4073 DurabilityPointsLoss(item,pDurabilityLoss);
4076 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4078 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
4079 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4080 DurabilityPointsLoss(pItem,points);
4082 if(inventory)
4084 // bags not have durability
4085 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4087 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
4088 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4089 DurabilityPointsLoss(pItem,points);
4091 // keys not have durability
4092 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4094 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4095 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4096 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
4097 if(Item* pItem = GetItemByPos( i, j ))
4098 DurabilityPointsLoss(pItem,points);
4102 void Player::DurabilityPointsLoss(Item* item, int32 points)
4104 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4105 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4106 int32 pNewDurability = pOldDurability - points;
4108 if (pNewDurability < 0)
4109 pNewDurability = 0;
4110 else if (pNewDurability > pMaxDurability)
4111 pNewDurability = pMaxDurability;
4113 if (pOldDurability != pNewDurability)
4115 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4116 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4117 _ApplyItemMods(item,item->GetSlot(), false);
4119 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4121 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4122 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4123 _ApplyItemMods(item,item->GetSlot(), true);
4125 item->SetState(ITEM_CHANGED, this);
4129 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4131 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4132 DurabilityPointsLoss(pItem,1);
4135 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4137 uint32 TotalCost = 0;
4138 // equipped, backpack, bags itself
4139 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
4140 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4142 // bank, buyback and keys not repaired
4144 // items in inventory bags
4145 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
4146 for(int i = 0; i < MAX_BAG_SIZE; i++)
4147 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4148 return TotalCost;
4151 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4153 Item* item = GetItemByPos(pos);
4155 uint32 TotalCost = 0;
4156 if(!item)
4157 return TotalCost;
4159 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4160 if(!maxDurability)
4161 return TotalCost;
4163 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4165 if(cost)
4167 uint32 LostDurability = maxDurability - curDurability;
4168 if(LostDurability>0)
4170 ItemPrototype const *ditemProto = item->GetProto();
4172 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4173 if(!dcost)
4175 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4176 return TotalCost;
4179 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4180 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4181 if(!dQualitymodEntry)
4183 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4184 return TotalCost;
4187 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4188 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4190 costs = uint32(costs * discountMod);
4192 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4193 costs = 1;
4195 if (guildBank)
4197 if (GetGuildId()==0)
4199 DEBUG_LOG("You are not member of a guild");
4200 return TotalCost;
4203 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4204 if (!pGuild)
4205 return TotalCost;
4207 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4209 DEBUG_LOG("You do not have rights to withdraw for repairs");
4210 return TotalCost;
4213 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4215 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4216 return TotalCost;
4219 if (pGuild->GetGuildBankMoney() < costs)
4221 DEBUG_LOG("There is not enough money in bank");
4222 return TotalCost;
4225 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4226 TotalCost = costs;
4228 else if (GetMoney() < costs)
4230 DEBUG_LOG("You do not have enough money");
4231 return TotalCost;
4233 else
4234 ModifyMoney( -int32(costs) );
4238 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4239 item->SetState(ITEM_CHANGED, this);
4241 // reapply mods for total broken and repaired item if equipped
4242 if(IsEquipmentPos(pos) && !curDurability)
4243 _ApplyItemMods(item,pos & 255, true);
4244 return TotalCost;
4247 void Player::RepopAtGraveyard()
4249 // note: this can be called also when the player is alive
4250 // for example from WorldSession::HandleMovementOpcodes
4252 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4254 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4255 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4257 ResurrectPlayer(0.5f);
4258 SpawnCorpseBones();
4261 WorldSafeLocsEntry const *ClosestGrave = NULL;
4263 // Special handle for battleground maps
4264 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
4266 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4267 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4268 else
4269 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4271 // stop countdown until repop
4272 m_deathTimer = 0;
4274 // if no grave found, stay at the current location
4275 // and don't show spirit healer location
4276 if(ClosestGrave)
4278 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4279 if(isDead()) // not send if alive, because it used in TeleportTo()
4281 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4282 data << ClosestGrave->map_id;
4283 data << ClosestGrave->x;
4284 data << ClosestGrave->y;
4285 data << ClosestGrave->z;
4286 GetSession()->SendPacket(&data);
4291 void Player::JoinedChannel(Channel *c)
4293 m_channels.push_back(c);
4296 void Player::LeftChannel(Channel *c)
4298 m_channels.remove(c);
4301 void Player::CleanupChannels()
4303 while(!m_channels.empty())
4305 Channel* ch = *m_channels.begin();
4306 m_channels.erase(m_channels.begin()); // remove from player's channel list
4307 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4308 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4309 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4312 sLog.outDebug("Player: channels cleaned up!");
4315 void Player::UpdateLocalChannels(uint32 newZone )
4317 if(m_channels.empty())
4318 return;
4320 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4321 if(!current_zone)
4322 return;
4324 ChannelMgr* cMgr = channelMgr(GetTeam());
4325 if(!cMgr)
4326 return;
4328 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4330 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4332 next = i; ++next;
4334 // skip non built-in channels
4335 if(!(*i)->IsConstant())
4336 continue;
4338 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4339 if(!ch)
4340 continue;
4342 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4343 continue;
4345 // new channel
4346 char new_channel_name_buf[100];
4347 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4348 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4350 if((*i)!=new_channel)
4352 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4354 // leave old channel
4355 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4356 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4357 LeftChannel(*i); // remove from player's channel list
4358 cMgr->LeftChannel(name); // delete if empty
4361 sLog.outDebug("Player: channels cleaned up!");
4364 void Player::LeaveLFGChannel()
4366 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4368 if((*i)->IsLFG())
4370 (*i)->Leave(GetGUID());
4371 break;
4376 void Player::UpdateDefense()
4378 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4380 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4382 // update dependent from defense skill part
4383 UpdateDefenseBonusesMod();
4387 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4389 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4391 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4392 return;
4395 float val = 1.0f;
4397 switch(modType)
4399 case FLAT_MOD:
4400 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4401 break;
4402 case PCT_MOD:
4403 if(amount <= -100.0f)
4404 amount = -200.0f;
4406 val = (100.0f + amount) / 100.0f;
4407 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4408 break;
4411 if(!CanModifyStats())
4412 return;
4414 switch(modGroup)
4416 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4417 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4418 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4419 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4420 default: break;
4424 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4426 if(modGroup >= BASEMOD_END || modType > MOD_END)
4428 sLog.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4429 return 0.0f;
4432 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4433 return 0.0f;
4435 return m_auraBaseMod[modGroup][modType];
4438 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4440 if(modGroup >= BASEMOD_END)
4442 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4443 return 0.0f;
4446 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4447 return 0.0f;
4449 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4452 uint32 Player::GetShieldBlockValue() const
4454 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4456 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH) * 0.5f - 10;
4458 value = (value < 0) ? 0 : value;
4460 return uint32(value);
4463 float Player::GetMeleeCritFromAgility()
4465 uint32 level = getLevel();
4466 uint32 pclass = getClass();
4468 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4470 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4471 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4472 if (critBase==NULL || critRatio==NULL)
4473 return 0.0f;
4475 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4476 return crit*100.0f;
4479 float Player::GetDodgeFromAgility()
4481 // Table for base dodge values
4482 float dodge_base[MAX_CLASSES] = {
4483 0.0075f, // Warrior
4484 0.00652f, // Paladin
4485 -0.0545f, // Hunter
4486 -0.0059f, // Rogue
4487 0.03183f, // Priest
4488 0.0114f, // DK
4489 0.0167f, // Shaman
4490 0.034575f, // Mage
4491 0.02011f, // Warlock
4492 0.0f, // ??
4493 -0.0187f // Druid
4495 // Crit/agility to dodge/agility coefficient multipliers
4496 float crit_to_dodge[MAX_CLASSES] = {
4497 1.1f, // Warrior
4498 1.0f, // Paladin
4499 1.6f, // Hunter
4500 2.0f, // Rogue
4501 1.0f, // Priest
4502 1.0f, // DK?
4503 1.0f, // Shaman
4504 1.0f, // Mage
4505 1.0f, // Warlock
4506 0.0f, // ??
4507 1.7f // Druid
4510 uint32 level = getLevel();
4511 uint32 pclass = getClass();
4513 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4515 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4516 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4517 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4518 return 0.0f;
4520 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4521 return dodge*100.0f;
4524 float Player::GetSpellCritFromIntellect()
4526 uint32 level = getLevel();
4527 uint32 pclass = getClass();
4529 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4531 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4532 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4533 if (critBase==NULL || critRatio==NULL)
4534 return 0.0f;
4536 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4537 return crit*100.0f;
4540 float Player::GetRatingCoefficient(CombatRating cr) const
4542 uint32 level = getLevel();
4544 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4546 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4547 if (Rating == NULL)
4548 return 1.0f; // By default use minimum coefficient (not must be called)
4550 return Rating->ratio;
4553 float Player::GetRatingBonusValue(CombatRating cr) const
4555 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4558 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4560 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4561 if (melee>25.0f) melee = 25.0f;
4562 return uint32 (melee * damage /100.0f);
4565 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4567 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4568 if (ranged>25.0f) ranged=25.0f;
4569 return uint32 (ranged * damage /100.0f);
4572 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4574 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4575 // In wow script resilience limited to 25%
4576 if (spell>25.0f)
4577 spell = 25.0f;
4578 return uint32 (spell * damage / 100.0f);
4581 uint32 Player::GetDotDamageReduction(uint32 damage) const
4583 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4584 // Dot resilience not limited (limit it by 100%)
4585 if (spellDot > 100.0f)
4586 spellDot = 100.0f;
4587 return uint32 (spellDot * damage / 100.0f);
4590 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4592 switch (attType)
4594 case BASE_ATTACK:
4595 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4596 case OFF_ATTACK:
4597 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4598 default:
4599 break;
4601 return 0.0f;
4604 float Player::OCTRegenHPPerSpirit()
4606 uint32 level = getLevel();
4607 uint32 pclass = getClass();
4609 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4611 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4612 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4613 if (baseRatio==NULL || moreRatio==NULL)
4614 return 0.0f;
4616 // Formula from PaperDollFrame script
4617 float spirit = GetStat(STAT_SPIRIT);
4618 float baseSpirit = spirit;
4619 if (baseSpirit>50) baseSpirit = 50;
4620 float moreSpirit = spirit - baseSpirit;
4621 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4622 return regen;
4625 float Player::OCTRegenMPPerSpirit()
4627 uint32 level = getLevel();
4628 uint32 pclass = getClass();
4630 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4632 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4633 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4634 if (moreRatio==NULL)
4635 return 0.0f;
4637 // Formula get from PaperDollFrame script
4638 float spirit = GetStat(STAT_SPIRIT);
4639 float regen = spirit * moreRatio->ratio;
4640 return regen;
4643 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4645 m_baseRatingValue[cr]+=(apply ? value : -value);
4647 int32 amount = uint32(m_baseRatingValue[cr]);
4648 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4649 // stat used stored in miscValueB for this aura
4650 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4651 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4652 if ((*i)->GetMiscValue() & (1<<cr))
4653 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4654 if (amount < 0)
4655 amount = 0;
4656 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4658 float RatingCoeffecient = GetRatingCoefficient(cr);
4659 float RatingChange = 0.0f;
4661 bool affectStats = CanModifyStats();
4663 switch (cr)
4665 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4666 case CR_DEFENSE_SKILL:
4667 UpdateDefenseBonusesMod();
4668 break;
4669 case CR_DODGE:
4670 UpdateDodgePercentage();
4671 break;
4672 case CR_PARRY:
4673 UpdateParryPercentage();
4674 break;
4675 case CR_BLOCK:
4676 UpdateBlockPercentage();
4677 break;
4678 case CR_HIT_MELEE:
4679 UpdateMeleeHitChances();
4680 break;
4681 case CR_HIT_RANGED:
4682 UpdateRangedHitChances();
4683 break;
4684 case CR_HIT_SPELL:
4685 UpdateSpellHitChances();
4686 break;
4687 case CR_CRIT_MELEE:
4688 if(affectStats)
4690 UpdateCritPercentage(BASE_ATTACK);
4691 UpdateCritPercentage(OFF_ATTACK);
4693 break;
4694 case CR_CRIT_RANGED:
4695 if(affectStats)
4696 UpdateCritPercentage(RANGED_ATTACK);
4697 break;
4698 case CR_CRIT_SPELL:
4699 if(affectStats)
4700 UpdateAllSpellCritChances();
4701 break;
4702 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4703 case CR_HIT_TAKEN_RANGED:
4704 break;
4705 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4706 break;
4707 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4708 case CR_CRIT_TAKEN_RANGED:
4709 break;
4710 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4711 break;
4712 case CR_HASTE_MELEE:
4713 RatingChange = value / RatingCoeffecient;
4714 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4715 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4716 break;
4717 case CR_HASTE_RANGED:
4718 RatingChange = value / RatingCoeffecient;
4719 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4720 break;
4721 case CR_HASTE_SPELL:
4722 RatingChange = value / RatingCoeffecient;
4723 ApplyCastTimePercentMod(RatingChange,apply);
4724 break;
4725 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4726 case CR_WEAPON_SKILL_OFFHAND:
4727 case CR_WEAPON_SKILL_RANGED:
4728 break;
4729 case CR_EXPERTISE:
4730 if(affectStats)
4732 UpdateExpertise(BASE_ATTACK);
4733 UpdateExpertise(OFF_ATTACK);
4735 break;
4739 void Player::SetRegularAttackTime()
4741 for(int i = 0; i < MAX_ATTACK; ++i)
4743 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4744 if(tmpitem && !tmpitem->IsBroken())
4746 ItemPrototype const *proto = tmpitem->GetProto();
4747 if(proto->Delay)
4748 SetAttackTime(WeaponAttackType(i), proto->Delay);
4749 else
4750 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4755 //skill+step, checking for max value
4756 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4758 if(!skill_id)
4759 return false;
4761 uint16 i=0;
4762 for (; i < PLAYER_MAX_SKILLS; i++)
4763 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4764 break;
4766 if(i>=PLAYER_MAX_SKILLS)
4767 return false;
4769 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4770 uint32 value = SKILL_VALUE(data);
4771 uint32 max = SKILL_MAX(data);
4773 if ((!max) || (!value) || (value >= max))
4774 return false;
4776 if (value*512 < max*urand(0,512))
4778 uint32 new_value = value+step;
4779 if(new_value > max)
4780 new_value = max;
4782 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4783 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4784 return true;
4787 return false;
4790 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4792 if ( SkillValue >= GrayLevel )
4793 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4794 if ( SkillValue >= GreenLevel )
4795 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4796 if ( SkillValue >= YellowLevel )
4797 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4798 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4801 bool Player::UpdateCraftSkill(uint32 spellid)
4803 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4805 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4806 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4808 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4810 if(_spell_idx->second->skillId)
4812 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4814 // Alchemy Discoveries here
4815 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4816 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4818 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4819 learnSpell(discoveredSpell,false);
4822 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4824 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4825 _spell_idx->second->max_value,
4826 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4827 _spell_idx->second->min_value),
4828 craft_skill_gain);
4831 return false;
4834 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4836 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4838 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4840 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4841 switch (SkillId)
4843 case SKILL_HERBALISM:
4844 case SKILL_LOCKPICKING:
4845 case SKILL_JEWELCRAFTING:
4846 case SKILL_INSCRIPTION:
4847 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4848 case SKILL_SKINNING:
4849 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4850 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4851 else
4852 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4853 case SKILL_MINING:
4854 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4855 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4856 else
4857 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4859 return false;
4862 bool Player::UpdateFishingSkill()
4864 sLog.outDebug("UpdateFishingSkill");
4866 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4868 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4870 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4872 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4875 // levels sync. with spell requirement for skill levels to learn
4876 // bonus abilities in sSkillLineAbilityStore
4877 // Used only to avoid scan DBC at each skill grow
4878 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
4880 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4882 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4883 if ( !SkillId )
4884 return false;
4886 if(Chance <= 0) // speedup in 0 chance case
4888 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4889 return false;
4892 uint16 i=0;
4893 for (; i < PLAYER_MAX_SKILLS; i++)
4894 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4895 if ( i >= PLAYER_MAX_SKILLS )
4896 return false;
4898 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4899 uint16 SkillValue = SKILL_VALUE(data);
4900 uint16 MaxValue = SKILL_MAX(data);
4902 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4903 return false;
4905 int32 Roll = irand(1,1000);
4907 if ( Roll <= Chance )
4909 uint32 new_value = SkillValue+step;
4910 if(new_value > MaxValue)
4911 new_value = MaxValue;
4913 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4914 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
4916 if((SkillValue < *bsl && new_value >= *bsl))
4918 learnSkillRewardedSpells( SkillId, new_value);
4919 break;
4922 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4923 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4924 return true;
4927 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4928 return false;
4931 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4933 // no skill gain in pvp
4934 Unit *pVictim = getVictim();
4935 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4936 return;
4938 if(IsInFeralForm())
4939 return; // always maximized SKILL_FERAL_COMBAT in fact
4941 if(m_form == FORM_TREE)
4942 return; // use weapon but not skill up
4944 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4946 switch(attType)
4948 case BASE_ATTACK:
4950 Item *tmpitem = GetWeaponForAttack(attType,true);
4952 if (!tmpitem)
4953 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4954 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4955 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4956 break;
4958 case OFF_ATTACK:
4959 case RANGED_ATTACK:
4961 Item *tmpitem = GetWeaponForAttack(attType,true);
4962 if (tmpitem)
4963 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4964 break;
4967 UpdateAllCritPercentages();
4970 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
4972 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4973 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4974 uint32 moblevel = pVictim->getLevelForTarget(this);
4975 if(moblevel < greylevel)
4976 return;
4978 if (moblevel > plevel + 5)
4979 moblevel = plevel + 5;
4981 uint32 lvldif = moblevel - greylevel;
4982 if(lvldif < 3)
4983 lvldif = 3;
4985 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4986 if(skilldif <= 0)
4987 return;
4989 float chance = float(3 * lvldif * skilldif) / plevel;
4990 if(!defence)
4992 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4993 chance *= 0.1f * GetStat(STAT_INTELLECT);
4996 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4998 if(roll_chance_f(chance))
5000 if(defence)
5001 UpdateDefense();
5002 else
5003 UpdateWeaponSkill(attType);
5005 else
5006 return;
5009 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5011 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5012 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5014 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5015 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5016 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5018 if(talent) // permanent bonus stored in high part
5019 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5020 else // temporary/item bonus stored in low part
5021 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5022 return;
5026 void Player::UpdateSkillsForLevel()
5028 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5029 uint32 maxSkill = GetMaxSkillValueForLevel();
5031 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5033 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5034 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5036 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5038 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5039 if(!pSkill)
5040 continue;
5042 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5043 continue;
5045 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5046 uint32 max = SKILL_MAX(data);
5047 uint32 val = SKILL_VALUE(data);
5049 /// update only level dependent max skill values
5050 if(max!=1)
5052 /// miximize skill always
5053 if(alwaysMaxSkill)
5054 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5055 /// update max skill value if current max skill not maximized
5056 else if(max != maxconfskill)
5057 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5062 void Player::UpdateSkillsToMaxSkillsForLevel()
5064 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5065 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5067 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5068 if( IsProfessionOrRidingSkill(pskill))
5069 continue;
5070 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5072 uint32 max = SKILL_MAX(data);
5074 if(max > 1)
5075 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5077 if(pskill == SKILL_DEFENSE)
5078 UpdateDefenseBonusesMod();
5082 // This functions sets a skill line value (and adds if doesn't exist yet)
5083 // To "remove" a skill line, set it's values to zero
5084 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5086 if(!id)
5087 return;
5089 uint16 i=0;
5090 for (; i < PLAYER_MAX_SKILLS; i++)
5091 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5093 if(i<PLAYER_MAX_SKILLS) //has skill
5095 if(currVal)
5097 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5098 learnSkillRewardedSpells(id, currVal);
5099 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
5101 else //remove
5103 // clear skill fields
5104 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5105 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5106 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5108 // remove all spells that related to this skill
5109 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5110 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5111 if (pAbility->skillId==id)
5112 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5115 else if(currVal) //add
5117 for (i=0; i < PLAYER_MAX_SKILLS; i++)
5118 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5120 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5121 if(!pSkill)
5123 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5124 return;
5126 // enable unlearn button for primary professions only
5127 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5128 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5129 else
5130 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5131 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5132 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
5134 // apply skill bonuses
5135 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5137 // temporary bonuses
5138 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5139 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
5140 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5141 (*i)->ApplyModifier(true);
5143 // permanent bonuses
5144 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5145 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
5146 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5147 (*i)->ApplyModifier(true);
5149 // Learn all spells for skill
5150 learnSkillRewardedSpells(id, currVal);
5151 return;
5156 bool Player::HasSkill(uint32 skill) const
5158 if(!skill)return false;
5159 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5161 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5163 return true;
5166 return false;
5169 uint16 Player::GetSkillValue(uint32 skill) const
5171 if(!skill)
5172 return 0;
5174 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5176 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5178 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5180 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5181 result += SKILL_TEMP_BONUS(bonus);
5182 result += SKILL_PERM_BONUS(bonus);
5183 return result < 0 ? 0 : result;
5186 return 0;
5189 uint16 Player::GetMaxSkillValue(uint32 skill) const
5191 if(!skill)return 0;
5192 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5194 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5196 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5198 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5199 result += SKILL_TEMP_BONUS(bonus);
5200 result += SKILL_PERM_BONUS(bonus);
5201 return result < 0 ? 0 : result;
5204 return 0;
5207 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5209 if(!skill)return 0;
5210 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5212 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5214 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5217 return 0;
5220 uint16 Player::GetBaseSkillValue(uint32 skill) const
5222 if(!skill)return 0;
5223 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5225 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5227 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5228 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5229 return result < 0 ? 0 : result;
5232 return 0;
5235 uint16 Player::GetPureSkillValue(uint32 skill) const
5237 if(!skill)return 0;
5238 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5240 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5242 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5245 return 0;
5248 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5250 if(!skill)
5251 return 0;
5253 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5255 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5257 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5261 return 0;
5264 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5266 if(!skill)
5267 return 0;
5269 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5271 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5273 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5277 return 0;
5280 void Player::SendInitialActionButtons()
5282 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5284 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5285 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5287 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5288 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5290 data << uint16(itr->second.action);
5291 data << uint8(itr->second.misc);
5292 data << uint8(itr->second.type);
5294 else
5296 data << uint32(0);
5300 GetSession()->SendPacket( &data );
5301 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5304 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5306 if(button >= MAX_ACTION_BUTTONS)
5308 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5309 return;
5312 // check cheating with adding non-known spells to action bar
5313 if(type==ACTION_BUTTON_SPELL)
5315 if(!sSpellStore.LookupEntry(action))
5317 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5318 return;
5321 if(!HasSpell(action))
5323 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5324 return;
5328 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5330 if (buttonItr==m_actionButtons.end())
5331 { // just add new button
5332 m_actionButtons[button] = ActionButton(action,type,misc);
5334 else
5335 { // change state of current button
5336 ActionButtonUpdateState uState = buttonItr->second.uState;
5337 buttonItr->second = ActionButton(action,type,misc);
5338 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5341 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5344 void Player::removeActionButton(uint8 button)
5346 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5347 if (buttonItr==m_actionButtons.end())
5348 return;
5350 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5351 m_actionButtons.erase(buttonItr); // new and not saved
5352 else
5353 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5355 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5358 void Player::SetDontMove(bool dontMove)
5360 m_dontMove = dontMove;
5363 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5365 // prevent crash when a bad coord is sent by the client
5366 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5368 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5369 return false;
5372 Map *m = GetMap();
5374 const float old_x = GetPositionX();
5375 const float old_y = GetPositionY();
5376 const float old_z = GetPositionZ();
5377 const float old_r = GetOrientation();
5379 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5381 if (teleport || old_x != x || old_y != y || old_z != z)
5382 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5383 else
5384 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5386 // move and update visible state if need
5387 m->PlayerRelocation(this, x, y, z, orientation);
5389 // reread after Map::Relocation
5390 m = GetMap();
5391 x = GetPositionX();
5392 y = GetPositionY();
5393 z = GetPositionZ();
5395 // group update
5396 if(GetGroup() && (old_x != x || old_y != y))
5397 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5400 // code block for underwater state update
5401 UpdateUnderwaterState(m, x, y, z);
5403 CheckExploreSystem();
5405 return true;
5408 void Player::SaveRecallPosition()
5410 m_recallMap = GetMapId();
5411 m_recallX = GetPositionX();
5412 m_recallY = GetPositionY();
5413 m_recallZ = GetPositionZ();
5414 m_recallO = GetOrientation();
5417 void Player::SendMessageToSet(WorldPacket *data, bool self)
5419 GetMap()->MessageBroadcast(this, data, self);
5422 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5424 GetMap()->MessageDistBroadcast(this, data, dist, self);
5427 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5429 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5432 void Player::SendDirectMessage(WorldPacket *data)
5434 GetSession()->SendPacket(data);
5437 void Player::CheckExploreSystem()
5439 if (!isAlive())
5440 return;
5442 if (isInFlight())
5443 return;
5445 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5446 if(areaFlag==0xffff)
5447 return;
5448 int offset = areaFlag / 32;
5450 if(offset >= 128)
5452 sLog.outError("ERROR: Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset);
5453 return;
5456 uint32 val = (uint32)(1 << (areaFlag % 32));
5457 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5459 if( !(currFields & val) )
5461 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5463 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5465 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5466 if(!p)
5468 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5470 else if(p->area_level > 0)
5472 uint32 area = p->ID;
5473 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5475 SendExplorationExperience(area,0);
5477 else
5479 int32 diff = int32(getLevel()) - p->area_level;
5480 uint32 XP = 0;
5481 if (diff < -5)
5483 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5485 else if (diff > 5)
5487 int32 exploration_percent = (100-((diff-5)*5));
5488 if (exploration_percent > 100)
5489 exploration_percent = 100;
5490 else if (exploration_percent < 0)
5491 exploration_percent = 0;
5493 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5495 else
5497 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5500 GiveXP( XP, NULL );
5501 SendExplorationExperience(area,XP);
5503 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5508 uint32 Player::TeamForRace(uint8 race)
5510 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5511 if(!rEntry)
5513 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5514 return ALLIANCE;
5517 switch(rEntry->TeamID)
5519 case 7: return ALLIANCE;
5520 case 1: return HORDE;
5523 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5524 return ALLIANCE;
5527 uint32 Player::getFactionForRace(uint8 race)
5529 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5530 if(!rEntry)
5532 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5533 return 0;
5536 return rEntry->FactionID;
5539 void Player::setFactionForRace(uint8 race)
5541 m_team = TeamForRace(race);
5542 setFaction( getFactionForRace(race) );
5545 void Player::UpdateReputation() const
5547 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5549 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5551 SendFactionState(&(itr->second));
5555 void Player::SendFactionState(FactionState const* faction) const
5557 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5559 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5560 data << (float) 0; // unk 2.4.0
5561 data << (uint8) 0; // wotlk 8634
5562 data << (uint32) 1; // count
5563 // for
5564 data << (uint32) faction->ReputationListID;
5565 data << (uint32) faction->Standing;
5566 // end for
5567 GetSession()->SendPacket(&data);
5571 void Player::SendInitialReputations()
5573 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5574 data << uint32 (0x00000080);
5576 RepListID a = 0;
5578 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5580 // fill in absent fields
5581 for (; a != itr->first; a++)
5583 data << uint8 (0x00);
5584 data << uint32 (0x00000000);
5587 // fill in encountered data
5588 data << uint8 (itr->second.Flags);
5589 data << uint32 (itr->second.Standing);
5591 ++a;
5594 // fill in absent fields
5595 for (; a != 128; a++)
5597 data << uint8 (0x00);
5598 data << uint32 (0x00000000);
5601 GetSession()->SendPacket(&data);
5604 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5606 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5607 if (itr != m_factions.end())
5608 return &itr->second;
5610 return NULL;
5613 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5615 // not allow declare war to own faction
5616 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5617 return;
5619 // already set
5620 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5621 return;
5623 if( atWar )
5624 faction->Flags |= FACTION_FLAG_AT_WAR;
5625 else
5626 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5628 faction->Changed = true;
5631 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5633 // always invisible or hidden faction can't be inactive
5634 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5635 return;
5637 // already set
5638 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5639 return;
5641 if(inactive)
5642 faction->Flags |= FACTION_FLAG_INACTIVE;
5643 else
5644 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5646 faction->Changed = true;
5649 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5651 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5653 if(!factionTemplateEntry)
5654 return;
5656 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5659 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5661 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5662 if(!factionEntry)
5663 return;
5665 if(factionEntry->reputationListID < 0)
5666 return;
5668 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5669 if (itr == m_factions.end())
5670 return;
5672 SetFactionVisible(&itr->second);
5675 void Player::SetFactionVisible(FactionState* faction)
5677 // always invisible or hidden faction can't be make visible
5678 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5679 return;
5681 // already set
5682 if(faction->Flags & FACTION_FLAG_VISIBLE)
5683 return;
5685 faction->Flags |= FACTION_FLAG_VISIBLE;
5686 faction->Changed = true;
5688 if(!m_session->PlayerLoading())
5690 // make faction visible in reputation list at client
5691 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5692 data << faction->ReputationListID;
5693 GetSession()->SendPacket(&data);
5697 void Player::SetInitialFactions()
5699 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5701 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5703 if( factionEntry && (factionEntry->reputationListID >= 0))
5705 FactionState newFaction;
5706 newFaction.ID = factionEntry->ID;
5707 newFaction.ReputationListID = factionEntry->reputationListID;
5708 newFaction.Standing = 0;
5709 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5710 newFaction.Changed = true;
5712 m_factions[newFaction.ReputationListID] = newFaction;
5717 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5719 if (!factionEntry)
5720 return 0;
5722 uint32 raceMask = getRaceMask();
5723 uint32 classMask = getClassMask();
5724 for (int i=0; i < 4; i++)
5726 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5727 (factionEntry->BaseRepClassMask[i]==0 ||
5728 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5729 return factionEntry->ReputationFlags[i];
5731 return 0;
5734 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5736 if (!factionEntry)
5737 return 0;
5739 uint32 raceMask = getRaceMask();
5740 uint32 classMask = getClassMask();
5741 for (int i=0; i < 4; i++)
5743 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5744 (factionEntry->BaseRepClassMask[i]==0 ||
5745 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5746 return factionEntry->BaseRepValue[i];
5749 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5750 return 0;
5753 int32 Player::GetReputation(uint32 faction_id) const
5755 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5757 if (!factionEntry)
5759 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5760 return 0;
5763 return GetReputation(factionEntry);
5766 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5768 // Faction without recorded reputation. Just ignore.
5769 if(!factionEntry)
5770 return 0;
5772 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5773 if (itr != m_factions.end())
5774 return GetBaseReputation(factionEntry) + itr->second.Standing;
5776 return 0;
5779 ReputationRank Player::GetReputationRank(uint32 faction) const
5781 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5782 if(!factionEntry)
5783 return MIN_REPUTATION_RANK;
5785 return GetReputationRank(factionEntry);
5788 ReputationRank Player::ReputationToRank(int32 standing) const
5790 int32 Limit = Reputation_Cap + 1;
5791 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5793 Limit -= ReputationRank_Length[i];
5794 if (standing >= Limit )
5795 return ReputationRank(i);
5797 return MIN_REPUTATION_RANK;
5800 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5802 int32 Reputation = GetReputation(factionEntry);
5803 return ReputationToRank(Reputation);
5806 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5808 int32 Reputation = GetBaseReputation(factionEntry);
5809 return ReputationToRank(Reputation);
5812 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5814 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5816 if(!factionTemplateEntry)
5818 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5819 return false;
5822 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5824 // Faction without recorded reputation. Just ignore.
5825 if(!factionEntry)
5826 return false;
5828 return ModifyFactionReputation(factionEntry, DeltaReputation);
5831 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5833 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5834 if (flist)
5836 bool res = false;
5837 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5839 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5840 if(factionEntryCalc)
5841 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5843 return res;
5845 else
5846 return ModifyOneFactionReputation(factionEntry, standing);
5849 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5851 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5852 if (itr != m_factions.end())
5854 int32 BaseRep = GetBaseReputation(factionEntry);
5855 int32 new_rep = BaseRep + itr->second.Standing + standing;
5857 if (new_rep > Reputation_Cap)
5858 new_rep = Reputation_Cap;
5859 else
5860 if (new_rep < Reputation_Bottom)
5861 new_rep = Reputation_Bottom;
5863 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5864 SetFactionAtWar(&itr->second,true);
5866 itr->second.Standing = new_rep - BaseRep;
5867 itr->second.Changed = true;
5869 SetFactionVisible(&itr->second);
5871 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
5873 if(uint32 questid = GetQuestSlotQuestId(i))
5875 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5876 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5878 QuestStatusData& q_status = mQuestStatus[questid];
5879 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5881 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5882 if ( CanCompleteQuest( questid ) )
5883 CompleteQuest( questid );
5885 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5887 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5888 IncompleteQuest( questid );
5893 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5894 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5895 SendFactionState(&(itr->second));
5897 return true;
5899 return false;
5902 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5904 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5906 if(!factionTemplateEntry)
5908 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5909 return false;
5912 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5914 // Faction without recorded reputation. Just ignore.
5915 if(!factionEntry)
5916 return false;
5918 return SetFactionReputation(factionEntry, standing);
5921 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5923 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5924 if (flist)
5926 bool res = false;
5927 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5929 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5930 if(factionEntryCalc)
5931 res = SetOneFactionReputation(factionEntryCalc, standing);
5933 return res;
5935 else
5936 return SetOneFactionReputation(factionEntry, standing);
5939 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5941 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5942 if (itr != m_factions.end())
5944 if (standing > Reputation_Cap)
5945 standing = Reputation_Cap;
5946 else
5947 if (standing < Reputation_Bottom)
5948 standing = Reputation_Bottom;
5950 int32 BaseRep = GetBaseReputation(factionEntry);
5951 itr->second.Standing = standing - BaseRep;
5952 itr->second.Changed = true;
5954 SetFactionVisible(&itr->second);
5956 if(ReputationToRank(standing) <= REP_HOSTILE)
5957 SetFactionAtWar(&itr->second,true);
5959 SendFactionState(&(itr->second));
5960 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5961 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5962 return true;
5964 return false;
5967 //Calculate total reputation percent player gain with quest/creature level
5968 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5970 // for grey creature kill received 20%, in other case 100.
5971 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5973 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5975 percent += rep > 0 ? repMod : -repMod;
5977 if(percent <=0)
5978 return 0;
5980 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5983 //Calculates how many reputation points player gains in victim's enemy factions
5984 void Player::RewardReputation(Unit *pVictim, float rate)
5986 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5987 return;
5989 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5991 if(!Rep)
5992 return;
5994 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5996 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5997 donerep1 = int32(donerep1*rate);
5998 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5999 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
6000 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
6001 ModifyFactionReputation(factionEntry1, donerep1);
6003 // Wiki: Team factions value divided by 2
6004 if(Rep->is_teamaward1)
6006 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
6007 if(team1_factionEntry)
6008 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
6012 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
6014 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
6015 donerep2 = int32(donerep2*rate);
6016 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
6017 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
6018 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
6019 ModifyFactionReputation(factionEntry2, donerep2);
6021 // Wiki: Team factions value divided by 2
6022 if(Rep->is_teamaward2)
6024 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
6025 if(team2_factionEntry)
6026 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
6031 //Calculate how many reputation points player gain with the quest
6032 void Player::RewardReputation(Quest const *pQuest)
6034 // quest reputation reward/loss
6035 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
6037 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
6039 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest),pQuest->RewRepValue[i],true);
6040 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
6041 if(factionEntry)
6042 ModifyFactionReputation(factionEntry, rep);
6046 // TODO: implement reputation spillover
6049 void Player::UpdateArenaFields(void)
6051 /* arena calcs go here */
6054 void Player::UpdateHonorFields()
6056 /// called when rewarding honor and at each save
6057 uint64 now = time(NULL);
6058 uint64 today = uint64(time(NULL) / DAY) * DAY;
6060 if(m_lastHonorUpdateTime < today)
6062 uint64 yesterday = today - DAY;
6064 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
6066 // update yesterday's contribution
6067 if(m_lastHonorUpdateTime >= yesterday )
6069 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
6071 // this is the first update today, reset today's contribution
6072 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
6073 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
6075 else
6077 // no honor/kills yesterday or today, reset
6078 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
6079 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
6083 m_lastHonorUpdateTime = now;
6086 ///Calculate the amount of honor gained based on the victim
6087 ///and the size of the group for which the honor is divided
6088 ///An exact honor value can also be given (overriding the calcs)
6089 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
6091 // do not reward honor in arenas, but enable onkill spellproc
6092 if(InArena())
6094 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
6095 return false;
6097 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
6098 return false;
6100 return true;
6103 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6104 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
6105 return false;
6107 uint64 victim_guid = 0;
6108 uint32 victim_rank = 0;
6110 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6111 UpdateHonorFields();
6113 if(honor <= 0)
6115 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
6116 return false;
6118 victim_guid = uVictim->GetGUID();
6120 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6122 Player *pVictim = (Player *)uVictim;
6124 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6125 return false;
6127 float f = 1; //need for total kills (?? need more info)
6128 uint32 k_grey = 0;
6129 uint32 k_level = getLevel();
6130 uint32 v_level = pVictim->getLevel();
6133 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6134 // [0] Just name
6135 // [1..14] Alliance honor titles and player name
6136 // [15..28] Horde honor titles and player name
6137 // [29..38] Other title and player name
6138 // [39+] Nothing
6139 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6140 // Get Killer titles, CharTitlesEntry::bit_index
6141 // Ranks:
6142 // title[1..14] -> rank[5..18]
6143 // title[15..28] -> rank[5..18]
6144 // title[other] -> 0
6145 if (victim_title == 0)
6146 victim_guid = 0; // Don't show HK: <rank> message, only log.
6147 else if (victim_title < 15)
6148 victim_rank = victim_title + 4;
6149 else if (victim_title < 29)
6150 victim_rank = victim_title - 14 + 4;
6151 else
6152 victim_guid = 0; // Don't show HK: <rank> message, only log.
6155 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6157 if(v_level<=k_grey)
6158 return false;
6160 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6162 int32 v_rank =1; //need more info
6164 honor = ((f * diff_level * (190 + v_rank*10))/6);
6165 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6167 // count the number of playerkills in one day
6168 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6169 // and those in a lifetime
6170 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6172 else
6174 Creature *cVictim = (Creature *)uVictim;
6176 if (!cVictim->isRacialLeader())
6177 return false;
6179 honor = 100; // ??? need more info
6180 victim_rank = 19; // HK: Leader
6184 if (uVictim != NULL)
6186 honor *= sWorld.getRate(RATE_HONOR);
6188 if(groupsize > 1)
6189 honor /= groupsize;
6191 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6194 // honor - for show honor points in log
6195 // victim_guid - for show victim name in log
6196 // victim_rank [1..4] HK: <dishonored rank>
6197 // victim_rank [5..19] HK: <alliance\horde rank>
6198 // victim_rank [0,20+] HK: <>
6199 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6200 data << (uint32) honor;
6201 data << (uint64) victim_guid;
6202 data << (uint32) victim_rank;
6204 GetSession()->SendPacket(&data);
6206 // add honor points
6207 ModifyHonorPoints(int32(honor));
6209 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6210 return true;
6213 void Player::ModifyHonorPoints( int32 value )
6215 if(value < 0)
6217 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6218 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6219 else
6220 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6222 else
6223 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6226 void Player::ModifyArenaPoints( int32 value )
6228 if(value < 0)
6230 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6231 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6232 else
6233 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6235 else
6236 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6239 uint32 Player::GetGuildIdFromDB(uint64 guid)
6241 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6242 if(!result)
6243 return 0;
6245 uint32 id = result->Fetch()[0].GetUInt32();
6246 delete result;
6247 return id;
6250 uint32 Player::GetRankFromDB(uint64 guid)
6252 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6253 if( result )
6255 uint32 v = result->Fetch()[0].GetUInt32();
6256 delete result;
6257 return v;
6259 else
6260 return 0;
6263 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6265 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);
6266 if(!result)
6267 return 0;
6269 uint32 id = (*result)[0].GetUInt32();
6270 delete result;
6271 return id;
6274 uint32 Player::GetZoneIdFromDB(uint64 guid)
6276 uint32 guidLow = GUID_LOPART(guid);
6277 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6278 if (!result)
6279 return 0;
6280 Field* fields = result->Fetch();
6281 uint32 zone = fields[0].GetUInt32();
6282 delete result;
6284 if (!zone)
6286 // stored zone is zero, use generic and slow zone detection
6287 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6288 if( !result )
6289 return 0;
6290 fields = result->Fetch();
6291 uint32 map = fields[0].GetUInt32();
6292 float posx = fields[1].GetFloat();
6293 float posy = fields[2].GetFloat();
6294 float posz = fields[3].GetFloat();
6295 delete result;
6297 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6299 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6302 return zone;
6305 void Player::UpdateArea(uint32 newArea)
6307 // FFA_PVP flags are area and not zone id dependent
6308 // so apply them accordingly
6309 m_areaUpdateId = newArea;
6311 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6313 if(area && (area->flags & AREA_FLAG_ARENA))
6315 if(!isGameMaster())
6316 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6318 else
6320 // remove ffa flag only if not ffapvp realm
6321 // removal in sanctuaries and capitals is handled in zone update
6322 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6323 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6326 UpdateAreaDependentAuras(newArea);
6329 void Player::UpdateZone(uint32 newZone)
6331 m_zoneUpdateId = newZone;
6332 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6334 // zone changed, so area changed as well, update it
6335 UpdateArea(GetAreaId());
6337 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6338 if(!zone)
6339 return;
6341 if (sWorld.getConfig(CONFIG_WEATHER))
6343 Weather *wth = sWorld.FindWeather(zone->ID);
6344 if(wth)
6346 wth->SendWeatherUpdateToPlayer(this);
6348 else
6350 if(!sWorld.AddWeather(zone->ID))
6352 // send fine weather packet to remove old zone's weather
6353 Weather::SendFineWeatherUpdateToPlayer(this);
6358 pvpInfo.inHostileArea =
6359 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6360 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6361 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6362 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6364 if(pvpInfo.inHostileArea) // in hostile area
6366 if(!IsPvP() || pvpInfo.endTimer != 0)
6367 UpdatePvP(true, true);
6369 else // in friendly area
6371 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6372 pvpInfo.endTimer = time(0); // start toggle-off
6375 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6377 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6378 if(sWorld.IsFFAPvPRealm())
6379 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6381 else
6383 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6386 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6388 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6389 SetRestType(REST_TYPE_IN_CITY);
6390 InnEnter(time(0),GetMapId(),0,0,0);
6392 if(sWorld.IsFFAPvPRealm())
6393 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6395 else // anywhere else
6397 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6399 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6401 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6403 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6404 SetRestType(REST_TYPE_NO);
6406 if(sWorld.IsFFAPvPRealm())
6407 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6410 else // not in tavern (leave city then)
6412 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6413 SetRestType(REST_TYPE_NO);
6415 // Set player to FFA PVP when not in rested environment.
6416 if(sWorld.IsFFAPvPRealm())
6417 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6422 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6423 // if player resurrected at teleport this will be applied in resurrect code
6424 if(isAlive())
6425 DestroyZoneLimitedItem( true, newZone );
6427 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6428 AutoUnequipOffhandIfNeed();
6430 // recent client version not send leave/join channel packets for built-in local channels
6431 UpdateLocalChannels( newZone );
6433 // group update
6434 if(GetGroup())
6435 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6437 UpdateZoneDependentAuras(newZone);
6440 //If players are too far way of duel flag... then player loose the duel
6441 void Player::CheckDuelDistance(time_t currTime)
6443 if(!duel)
6444 return;
6446 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6447 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6448 if(!obj)
6449 return;
6451 if(duel->outOfBound == 0)
6453 if(!IsWithinDistInMap(obj, 50))
6455 duel->outOfBound = currTime;
6457 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6458 GetSession()->SendPacket(&data);
6461 else
6463 if(IsWithinDistInMap(obj, 40))
6465 duel->outOfBound = 0;
6467 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6468 GetSession()->SendPacket(&data);
6470 else if(currTime >= (duel->outOfBound+10))
6472 DuelComplete(DUEL_FLED);
6477 void Player::DuelComplete(DuelCompleteType type)
6479 // duel not requested
6480 if(!duel)
6481 return;
6483 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6484 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6485 GetSession()->SendPacket(&data);
6486 duel->opponent->GetSession()->SendPacket(&data);
6488 if(type != DUEL_INTERUPTED)
6490 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6491 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6492 data << duel->opponent->GetName();
6493 data << GetName();
6494 SendMessageToSet(&data,true);
6497 // cool-down duel spell
6498 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6500 data<<GetGUID();
6501 data<<uint8(0x0);
6503 data<<(uint32)7266;
6504 data<<uint32(0x0);
6505 GetSession()->SendPacket(&data);
6506 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6507 data<<duel->opponent->GetGUID();
6508 data<<uint8(0x0);
6509 data<<(uint32)7266;
6510 data<<uint32(0x0);
6511 duel->opponent->GetSession()->SendPacket(&data);*/
6513 //Remove Duel Flag object
6514 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6515 if(obj)
6516 duel->initiator->RemoveGameObject(obj,true);
6518 /* remove auras */
6519 std::vector<uint32> auras2remove;
6520 AuraMap const& vAuras = duel->opponent->GetAuras();
6521 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6523 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6524 auras2remove.push_back(i->second->GetId());
6527 for(size_t i=0; i<auras2remove.size(); i++)
6528 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6530 auras2remove.clear();
6531 AuraMap const& auras = GetAuras();
6532 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6534 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6535 auras2remove.push_back(i->second->GetId());
6537 for(size_t i=0; i<auras2remove.size(); i++)
6538 RemoveAurasDueToSpell(auras2remove[i]);
6540 // cleanup combo points
6541 if(GetComboTarget()==duel->opponent->GetGUID())
6542 ClearComboPoints();
6543 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6544 ClearComboPoints();
6546 if(duel->opponent->GetComboTarget()==GetGUID())
6547 duel->opponent->ClearComboPoints();
6548 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6549 duel->opponent->ClearComboPoints();
6551 //cleanups
6552 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6553 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6554 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6555 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6557 delete duel->opponent->duel;
6558 duel->opponent->duel = NULL;
6559 delete duel;
6560 duel = NULL;
6563 //---------------------------------------------------------//
6565 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6567 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6568 return;
6570 // not apply/remove mods for broken item
6571 if(item->IsBroken())
6572 return;
6574 ItemPrototype const *proto = item->GetProto();
6576 if(!proto)
6577 return;
6579 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6581 uint32 attacktype = Player::GetAttackBySlot(slot);
6582 if(attacktype < MAX_ATTACK)
6583 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6585 _ApplyItemBonuses(proto,slot,apply);
6587 if( slot==EQUIPMENT_SLOT_RANGED )
6588 _ApplyAmmoBonuses();
6590 ApplyItemEquipSpell(item,apply);
6591 ApplyEnchantment(item, apply);
6593 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6594 CorrectMetaGemEnchants(slot, apply);
6596 sLog.outDebug("_ApplyItemMods complete.");
6599 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6601 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6602 return;
6604 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6606 uint32 statType = 0;
6607 int32 val = 0;
6609 if(proto->ScalingStatDistribution)
6611 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6613 statType = ssd->StatMod[i];
6615 if(uint32 modifier = ssd->Modifier[i])
6617 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6618 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6620 uint32 multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6621 val = (multiplier * modifier) / 10000;
6626 else
6628 statType = proto->ItemStat[i].ItemStatType;
6629 val = proto->ItemStat[i].ItemStatValue;
6632 if(val == 0)
6633 continue;
6635 switch (statType)
6637 case ITEM_MOD_MANA:
6638 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6639 break;
6640 case ITEM_MOD_HEALTH: // modify HP
6641 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6642 break;
6643 case ITEM_MOD_AGILITY: // modify agility
6644 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6645 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6646 break;
6647 case ITEM_MOD_STRENGTH: //modify strength
6648 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6649 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6650 break;
6651 case ITEM_MOD_INTELLECT: //modify intellect
6652 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6653 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6654 break;
6655 case ITEM_MOD_SPIRIT: //modify spirit
6656 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6657 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6658 break;
6659 case ITEM_MOD_STAMINA: //modify stamina
6660 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6661 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6662 break;
6663 case ITEM_MOD_DEFENSE_SKILL_RATING:
6664 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6665 break;
6666 case ITEM_MOD_DODGE_RATING:
6667 ApplyRatingMod(CR_DODGE, int32(val), apply);
6668 break;
6669 case ITEM_MOD_PARRY_RATING:
6670 ApplyRatingMod(CR_PARRY, int32(val), apply);
6671 break;
6672 case ITEM_MOD_BLOCK_RATING:
6673 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6674 break;
6675 case ITEM_MOD_HIT_MELEE_RATING:
6676 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6677 break;
6678 case ITEM_MOD_HIT_RANGED_RATING:
6679 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6680 break;
6681 case ITEM_MOD_HIT_SPELL_RATING:
6682 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6683 break;
6684 case ITEM_MOD_CRIT_MELEE_RATING:
6685 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6686 break;
6687 case ITEM_MOD_CRIT_RANGED_RATING:
6688 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6689 break;
6690 case ITEM_MOD_CRIT_SPELL_RATING:
6691 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6692 break;
6693 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6694 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6695 break;
6696 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6697 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6698 break;
6699 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6700 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6701 break;
6702 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6703 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6704 break;
6705 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6706 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6707 break;
6708 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6709 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6710 break;
6711 case ITEM_MOD_HASTE_MELEE_RATING:
6712 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6713 break;
6714 case ITEM_MOD_HASTE_RANGED_RATING:
6715 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6716 break;
6717 case ITEM_MOD_HASTE_SPELL_RATING:
6718 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6719 break;
6720 case ITEM_MOD_HIT_RATING:
6721 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6722 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6723 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6724 break;
6725 case ITEM_MOD_CRIT_RATING:
6726 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6727 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6728 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6729 break;
6730 case ITEM_MOD_HIT_TAKEN_RATING:
6731 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6732 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6733 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6734 break;
6735 case ITEM_MOD_CRIT_TAKEN_RATING:
6736 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6737 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6738 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6739 break;
6740 case ITEM_MOD_RESILIENCE_RATING:
6741 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6742 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6743 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6744 break;
6745 case ITEM_MOD_HASTE_RATING:
6746 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6747 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6748 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6749 break;
6750 case ITEM_MOD_EXPERTISE_RATING:
6751 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6752 break;
6753 case ITEM_MOD_ATTACK_POWER:
6754 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6755 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6756 break;
6757 case ITEM_MOD_RANGED_ATTACK_POWER:
6758 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6759 break;
6760 case ITEM_MOD_FERAL_ATTACK_POWER:
6761 ApplyFeralAPBonus(int32(val), apply);
6762 break;
6763 case ITEM_MOD_SPELL_HEALING_DONE:
6764 ApplySpellHealingBonus(int32(val), apply);
6765 break;
6766 case ITEM_MOD_SPELL_DAMAGE_DONE:
6767 ApplySpellDamageBonus(int32(val), apply);
6768 break;
6769 case ITEM_MOD_MANA_REGENERATION:
6770 ApplyManaRegenBonus(int32(val), apply);
6771 break;
6772 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6773 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6774 break;
6775 case ITEM_MOD_SPELL_POWER:
6776 ApplySpellHealingBonus(int32(val), apply);
6777 ApplySpellDamageBonus(int32(val), apply);
6778 break;
6782 if (proto->Armor)
6783 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6785 if (proto->Block)
6786 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6788 if (proto->HolyRes)
6789 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6791 if (proto->FireRes)
6792 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6794 if (proto->NatureRes)
6795 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6797 if (proto->FrostRes)
6798 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6800 if (proto->ShadowRes)
6801 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6803 if (proto->ArcaneRes)
6804 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6806 WeaponAttackType attType = BASE_ATTACK;
6807 float damage = 0.0f;
6809 if( slot == EQUIPMENT_SLOT_RANGED && (
6810 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6811 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6813 attType = RANGED_ATTACK;
6815 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6817 attType = OFF_ATTACK;
6820 if (proto->Damage[0].DamageMin > 0 )
6822 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6823 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6824 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6827 if (proto->Damage[0].DamageMax > 0 )
6829 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6830 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6833 // Druids get feral AP bonus from weapon dps
6834 if(getClass() == CLASS_DRUID)
6836 int32 feral_bonus = proto->getFeralBonus();
6837 if (feral_bonus > 0)
6838 ApplyFeralAPBonus(feral_bonus, apply);
6841 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6842 return;
6844 if (proto->Delay)
6846 if(slot == EQUIPMENT_SLOT_RANGED)
6847 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6848 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6849 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6850 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6851 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6854 if(CanModifyStats() && (damage || proto->Delay))
6855 UpdateDamagePhysical(attType);
6858 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6860 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6861 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6862 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6864 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6865 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6866 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6868 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6869 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6870 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6873 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6875 // generic not weapon specific case processes in aura code
6876 if(aura->GetSpellProto()->EquippedItemClass == -1)
6877 return;
6879 BaseModGroup mod = BASEMOD_END;
6880 switch(attackType)
6882 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6883 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6884 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6885 default: return;
6888 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6890 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6894 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6896 // ignore spell mods for not wands
6897 Modifier const* modifier = aura->GetModifier();
6898 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6899 return;
6901 // generic not weapon specific case processes in aura code
6902 if(aura->GetSpellProto()->EquippedItemClass == -1)
6903 return;
6905 UnitMods unitMod = UNIT_MOD_END;
6906 switch(attackType)
6908 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6909 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6910 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6911 default: return;
6914 UnitModifierType unitModType = TOTAL_VALUE;
6915 switch(modifier->m_auraname)
6917 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6918 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6919 default: return;
6922 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6924 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6928 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6930 if(!item)
6931 return;
6933 ItemPrototype const *proto = item->GetProto();
6934 if(!proto)
6935 return;
6937 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6939 _Spell const& spellData = proto->Spells[i];
6941 // no spell
6942 if(!spellData.SpellId )
6943 continue;
6945 // wrong triggering type
6946 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6947 continue;
6949 // check if it is valid spell
6950 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6951 if(!spellproto)
6952 continue;
6954 ApplyEquipSpell(spellproto,item,apply,form_change);
6958 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6960 if(apply)
6962 // Cannot be used in this stance/form
6963 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6964 return;
6966 if(form_change) // check aura active state from other form
6968 bool found = false;
6969 for (int k=0; k < 3; ++k)
6971 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6972 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6974 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6976 found = true;
6977 break;
6980 if(found)
6981 break;
6984 if(found) // and skip re-cast already active aura at form change
6985 return;
6988 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6990 CastSpell(this,spellInfo,true,item);
6992 else
6994 if(form_change) // check aura compatibility
6996 // Cannot be used in this stance/form
6997 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6998 return; // and remove only not compatible at form change
7001 if(item)
7002 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
7003 else
7004 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
7008 void Player::UpdateEquipSpellsAtFormChange()
7010 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7012 if(m_items[i] && !m_items[i]->IsBroken())
7014 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
7015 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
7019 // item set bonuses not dependent from item broken state
7020 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
7022 ItemSetEffect* eff = ItemSetEff[setindex];
7023 if(!eff)
7024 continue;
7026 for(uint32 y=0;y<8; ++y)
7028 SpellEntry const* spellInfo = eff->spells[y];
7029 if(!spellInfo)
7030 continue;
7032 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
7033 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
7038 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
7040 if(!item || item->IsBroken())
7041 return;
7043 ItemPrototype const *proto = item->GetProto();
7044 if(!proto)
7045 return;
7047 if (!Target || Target == this )
7048 return;
7050 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7052 _Spell const& spellData = proto->Spells[i];
7054 // no spell
7055 if(!spellData.SpellId )
7056 continue;
7058 // wrong triggering type
7059 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7060 continue;
7062 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7063 if(!spellInfo)
7065 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7066 continue;
7069 // not allow proc extra attack spell at extra attack
7070 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7071 return;
7073 float chance = spellInfo->procChance;
7075 if(spellData.SpellPPMRate)
7077 uint32 WeaponSpeed = GetAttackTime(attType);
7078 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7080 else if(chance > 100.0f)
7082 chance = GetWeaponProcChance();
7085 if (roll_chance_f(chance))
7086 CastSpell(Target, spellInfo->Id, true, item);
7089 // item combat enchantments
7090 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7092 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7093 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7094 if(!pEnchant) continue;
7095 for (int s=0;s<3;s++)
7097 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7098 continue;
7100 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7101 if (!spellInfo)
7103 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7104 continue;
7107 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7108 if (roll_chance_f(chance))
7110 if(IsPositiveSpell(pEnchant->spellid[s]))
7111 CastSpell(this, pEnchant->spellid[s], true, item);
7112 else
7113 CastSpell(Target, pEnchant->spellid[s], true, item);
7119 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7121 ItemPrototype const* proto = item->GetProto();
7122 // special learning case
7123 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7125 uint32 learn_spell_id = proto->Spells[0].SpellId;
7126 uint32 learning_spell_id = proto->Spells[1].SpellId;
7128 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7129 if(!spellInfo)
7131 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7132 SendEquipError(EQUIP_ERR_NONE,item,NULL);
7133 return;
7136 Spell *spell = new Spell(this, spellInfo, false);
7137 spell->m_CastItem = item;
7138 spell->m_cast_count = cast_count; //set count of casts
7139 spell->m_currentBasePoints[0] = learning_spell_id;
7140 spell->prepare(&targets);
7141 return;
7144 // use triggered flag only for items with many spell casts and for not first cast
7145 int count = 0;
7147 // item spells casted at use
7148 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7150 _Spell const& spellData = proto->Spells[i];
7152 // no spell
7153 if(!spellData.SpellId)
7154 continue;
7156 // wrong triggering type
7157 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7158 continue;
7160 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7161 if(!spellInfo)
7163 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7164 continue;
7167 Spell *spell = new Spell(this, spellInfo, (count > 0));
7168 spell->m_CastItem = item;
7169 spell->m_cast_count = cast_count; // set count of casts
7170 spell->m_glyphIndex = glyphIndex; // glyph index
7171 spell->prepare(&targets);
7173 ++count;
7176 // Item enchantments spells casted at use
7177 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7179 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7180 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7181 if(!pEnchant) continue;
7182 for (int s=0;s<3;s++)
7184 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7185 continue;
7187 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7188 if (!spellInfo)
7190 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7191 continue;
7194 Spell *spell = new Spell(this, spellInfo, (count > 0));
7195 spell->m_CastItem = item;
7196 spell->m_cast_count = cast_count; // set count of casts
7197 spell->m_glyphIndex = glyphIndex; // glyph index
7198 spell->prepare(&targets);
7200 ++count;
7205 void Player::_RemoveAllItemMods()
7207 sLog.outDebug("_RemoveAllItemMods start.");
7209 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7211 if(m_items[i])
7213 ItemPrototype const *proto = m_items[i]->GetProto();
7214 if(!proto)
7215 continue;
7217 // item set bonuses not dependent from item broken state
7218 if(proto->ItemSet)
7219 RemoveItemsSetItem(this,proto);
7221 if(m_items[i]->IsBroken())
7222 continue;
7224 ApplyItemEquipSpell(m_items[i],false);
7225 ApplyEnchantment(m_items[i], false);
7229 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7231 if(m_items[i])
7233 if(m_items[i]->IsBroken())
7234 continue;
7235 ItemPrototype const *proto = m_items[i]->GetProto();
7236 if(!proto)
7237 continue;
7239 uint32 attacktype = Player::GetAttackBySlot(i);
7240 if(attacktype < MAX_ATTACK)
7241 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7243 _ApplyItemBonuses(proto,i, false);
7245 if( i == EQUIPMENT_SLOT_RANGED )
7246 _ApplyAmmoBonuses();
7250 sLog.outDebug("_RemoveAllItemMods complete.");
7253 void Player::_ApplyAllItemMods()
7255 sLog.outDebug("_ApplyAllItemMods start.");
7257 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7259 if(m_items[i])
7261 if(m_items[i]->IsBroken())
7262 continue;
7264 ItemPrototype const *proto = m_items[i]->GetProto();
7265 if(!proto)
7266 continue;
7268 uint32 attacktype = Player::GetAttackBySlot(i);
7269 if(attacktype < MAX_ATTACK)
7270 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7272 _ApplyItemBonuses(proto,i, true);
7274 if( i == EQUIPMENT_SLOT_RANGED )
7275 _ApplyAmmoBonuses();
7279 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7281 if(m_items[i])
7283 ItemPrototype const *proto = m_items[i]->GetProto();
7284 if(!proto)
7285 continue;
7287 // item set bonuses not dependent from item broken state
7288 if(proto->ItemSet)
7289 AddItemsSetItem(this,m_items[i]);
7291 if(m_items[i]->IsBroken())
7292 continue;
7294 ApplyItemEquipSpell(m_items[i],true);
7295 ApplyEnchantment(m_items[i], true);
7299 sLog.outDebug("_ApplyAllItemMods complete.");
7302 void Player::_ApplyAmmoBonuses()
7304 // check ammo
7305 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7306 if(!ammo_id)
7307 return;
7309 float currentAmmoDPS;
7311 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7312 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7313 currentAmmoDPS = 0.0f;
7314 else
7315 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7317 if(currentAmmoDPS == GetAmmoDPS())
7318 return;
7320 m_ammoDPS = currentAmmoDPS;
7322 if(CanModifyStats())
7323 UpdateDamagePhysical(RANGED_ATTACK);
7326 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7328 if(!ammo_proto)
7329 return false;
7331 // check ranged weapon
7332 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7333 if(!weapon || weapon->IsBroken() )
7334 return false;
7336 ItemPrototype const* weapon_proto = weapon->GetProto();
7337 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7338 return false;
7340 // check ammo ws. weapon compatibility
7341 switch(weapon_proto->SubClass)
7343 case ITEM_SUBCLASS_WEAPON_BOW:
7344 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7345 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7346 return false;
7347 break;
7348 case ITEM_SUBCLASS_WEAPON_GUN:
7349 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7350 return false;
7351 break;
7352 default:
7353 return false;
7356 return true;
7359 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7360 Called by remove insignia spell effect */
7361 void Player::RemovedInsignia(Player* looterPlr)
7363 if (!GetBattleGroundId())
7364 return;
7366 // If not released spirit, do it !
7367 if(m_deathTimer > 0)
7369 m_deathTimer = 0;
7370 BuildPlayerRepop();
7371 RepopAtGraveyard();
7374 Corpse *corpse = GetCorpse();
7375 if (!corpse)
7376 return;
7378 // We have to convert player corpse to bones, not to be able to resurrect there
7379 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7380 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7381 if (!bones)
7382 return;
7384 // Now we must make bones lootable, and send player loot
7385 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7387 // We store the level of our player in the gold field
7388 // We retrieve this information at Player::SendLoot()
7389 bones->loot.gold = getLevel();
7390 bones->lootRecipient = looterPlr;
7391 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7394 /*Loot type MUST be
7395 1-corpse, go
7396 2-skinning
7397 3-Fishing
7400 void Player::SendLootRelease( uint64 guid )
7402 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7403 data << uint64(guid) << uint8(1);
7404 SendDirectMessage( &data );
7407 void Player::SendLoot(uint64 guid, LootType loot_type)
7409 Loot *loot = 0;
7410 PermissionTypes permission = ALL_PERMISSION;
7412 sLog.outDebug("Player::SendLoot");
7413 if (IS_GAMEOBJECT_GUID(guid))
7415 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7416 GameObject *go =
7417 ObjectAccessor::GetGameObject(*this, guid);
7419 // not check distance for GO in case owned GO (fishing bobber case, for example)
7420 // And permit out of range GO with no owner in case fishing hole
7421 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7423 SendLootRelease(guid);
7424 return;
7427 loot = &go->loot;
7429 if(go->getLootState() == GO_READY)
7431 uint32 lootid = go->GetLootId();
7433 if(lootid)
7435 sLog.outDebug(" if(lootid)");
7436 loot->clear();
7437 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7440 if(loot_type == LOOT_FISHING)
7441 go->getFishLoot(loot,this);
7443 go->SetLootState(GO_ACTIVATED);
7446 else if (IS_ITEM_GUID(guid))
7448 Item *item = GetItemByGuid( guid );
7450 if (!item)
7452 SendLootRelease(guid);
7453 return;
7456 if(loot_type == LOOT_DISENCHANTING)
7458 loot = &item->loot;
7460 if(!item->m_lootGenerated)
7462 item->m_lootGenerated = true;
7463 loot->clear();
7464 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7467 else if(loot_type == LOOT_PROSPECTING)
7469 loot = &item->loot;
7471 if(!item->m_lootGenerated)
7473 item->m_lootGenerated = true;
7474 loot->clear();
7475 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7478 else if(loot_type == LOOT_MILLING)
7480 loot = &item->loot;
7482 if(!item->m_lootGenerated)
7484 item->m_lootGenerated = true;
7485 loot->clear();
7486 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7489 else
7491 loot = &item->loot;
7493 if(!item->m_lootGenerated)
7495 item->m_lootGenerated = true;
7496 loot->clear();
7497 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7499 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7503 else if (IS_CORPSE_GUID(guid)) // remove insignia
7505 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7507 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7509 SendLootRelease(guid);
7510 return;
7513 loot = &bones->loot;
7515 if (!bones->lootForBody)
7517 bones->lootForBody = true;
7518 uint32 pLevel = bones->loot.gold;
7519 bones->loot.clear();
7520 // It may need a better formula
7521 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7522 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7525 if (bones->lootRecipient != this)
7526 permission = NONE_PERMISSION;
7528 else
7530 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7532 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7533 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7535 SendLootRelease(guid);
7536 return;
7539 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7541 SendLootRelease(guid);
7542 return;
7545 loot = &creature->loot;
7547 if(loot_type == LOOT_PICKPOCKETING)
7549 if ( !creature->lootForPickPocketed )
7551 creature->lootForPickPocketed = true;
7552 loot->clear();
7554 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7555 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7557 // Generate extra money for pick pocket loot
7558 const uint32 a = urand(0, creature->getLevel()/2);
7559 const uint32 b = urand(0, getLevel()/2);
7560 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7563 else
7565 // the player whose group may loot the corpse
7566 Player *recipient = creature->GetLootRecipient();
7567 if (!recipient)
7569 creature->SetLootRecipient(this);
7570 recipient = this;
7573 if (creature->lootForPickPocketed)
7575 creature->lootForPickPocketed = false;
7576 loot->clear();
7579 if(!creature->lootForBody)
7581 creature->lootForBody = true;
7582 loot->clear();
7584 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7585 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7587 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7589 if(Group* group = recipient->GetGroup())
7591 group->UpdateLooterGuid(creature,true);
7593 switch (group->GetLootMethod())
7595 case GROUP_LOOT:
7596 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7597 group->GroupLoot(recipient->GetGUID(), loot, creature);
7598 break;
7599 case NEED_BEFORE_GREED:
7600 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7601 break;
7602 case MASTER_LOOT:
7603 group->MasterLoot(recipient->GetGUID(), loot, creature);
7604 break;
7605 default:
7606 break;
7611 // possible only if creature->lootForBody && loot->empty() at spell cast check
7612 if (loot_type == LOOT_SKINNING)
7614 loot->clear();
7615 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7617 // set group rights only for loot_type != LOOT_SKINNING
7618 else
7620 if(Group* group = GetGroup())
7622 if( group == recipient->GetGroup() )
7624 if(group->GetLootMethod() == FREE_FOR_ALL)
7625 permission = ALL_PERMISSION;
7626 else if(group->GetLooterGuid() == GetGUID())
7628 if(group->GetLootMethod() == MASTER_LOOT)
7629 permission = MASTER_PERMISSION;
7630 else
7631 permission = ALL_PERMISSION;
7633 else
7634 permission = GROUP_PERMISSION;
7636 else
7637 permission = NONE_PERMISSION;
7639 else if(recipient == this)
7640 permission = ALL_PERMISSION;
7641 else
7642 permission = NONE_PERMISSION;
7647 SetLootGUID(guid);
7649 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7650 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA || loot_type == LOOT_MILLING)
7651 loot_type = LOOT_SKINNING;
7653 if(loot_type == LOOT_FISHINGHOLE)
7654 loot_type = LOOT_FISHING;
7656 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7658 data << uint64(guid);
7659 data << uint8(loot_type);
7660 data << LootView(*loot, this, permission);
7662 SendDirectMessage(&data);
7664 // add 'this' player as one of the players that are looting 'loot'
7665 if (permission != NONE_PERMISSION)
7666 loot->AddLooter(GetGUID());
7668 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7669 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7672 void Player::SendNotifyLootMoneyRemoved()
7674 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7675 GetSession()->SendPacket( &data );
7678 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7680 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7681 data << uint8(lootSlot);
7682 GetSession()->SendPacket( &data );
7685 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7687 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7688 data << Field;
7689 data << Value;
7690 GetSession()->SendPacket(&data);
7693 void Player::SendInitWorldStates()
7695 // data depends on zoneid/mapid...
7696 BattleGround* bg = GetBattleGround();
7697 uint16 NumberOfFields = 0;
7698 uint32 mapid = GetMapId();
7699 uint32 zoneid = GetZoneId();
7700 uint32 areaid = GetAreaId();
7701 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7702 // may be exist better way to do this...
7703 switch(zoneid)
7705 case 0:
7706 case 1:
7707 case 4:
7708 case 8:
7709 case 10:
7710 case 11:
7711 case 12:
7712 case 36:
7713 case 38:
7714 case 40:
7715 case 41:
7716 case 51:
7717 case 267:
7718 case 1519:
7719 case 1537:
7720 case 2257:
7721 case 2918:
7722 NumberOfFields = 8;
7723 break;
7724 case 139:
7725 NumberOfFields = 41;
7726 break;
7727 case 1377:
7728 NumberOfFields = 15;
7729 break;
7730 case 2597:
7731 NumberOfFields = 83;
7732 break;
7733 case 3277:
7734 NumberOfFields = 16;
7735 break;
7736 case 3358:
7737 case 3820:
7738 NumberOfFields = 40;
7739 break;
7740 case 3483:
7741 NumberOfFields = 27;
7742 break;
7743 case 3518:
7744 NumberOfFields = 39;
7745 break;
7746 case 3519:
7747 NumberOfFields = 38;
7748 break;
7749 case 3521:
7750 NumberOfFields = 37;
7751 break;
7752 case 3698:
7753 case 3702:
7754 case 3968:
7755 NumberOfFields = 11;
7756 break;
7757 case 3703:
7758 NumberOfFields = 11;
7759 break;
7760 default:
7761 NumberOfFields = 12;
7762 break;
7765 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7766 data << uint32(mapid); // mapid
7767 data << uint32(zoneid); // zone id
7768 data << uint32(areaid); // area id, new 2.1.0
7769 data << uint16(NumberOfFields); // count of uint64 blocks
7770 data << uint32(0x8d8) << uint32(0x0); // 1
7771 data << uint32(0x8d7) << uint32(0x0); // 2
7772 data << uint32(0x8d6) << uint32(0x0); // 3
7773 data << uint32(0x8d5) << uint32(0x0); // 4
7774 data << uint32(0x8d4) << uint32(0x0); // 5
7775 data << uint32(0x8d3) << uint32(0x0); // 6
7776 // 7 1 - Arena season in progress, 0 - end of season
7777 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7778 // 8 Arena season id
7779 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7780 if(mapid == 530) // Outland
7782 data << uint32(0x9bf) << uint32(0x0); // 7
7783 data << uint32(0x9bd) << uint32(0xF); // 8
7784 data << uint32(0x9bb) << uint32(0xF); // 9
7786 switch(zoneid)
7788 case 1:
7789 case 11:
7790 case 12:
7791 case 38:
7792 case 40:
7793 case 51:
7794 case 1519:
7795 case 1537:
7796 case 2257:
7797 break;
7798 case 2597: // AV
7799 data << uint32(0x7ae) << uint32(0x1); // 7
7800 data << uint32(0x532) << uint32(0x1); // 8
7801 data << uint32(0x531) << uint32(0x0); // 9
7802 data << uint32(0x52e) << uint32(0x0); // 10
7803 data << uint32(0x571) << uint32(0x0); // 11
7804 data << uint32(0x570) << uint32(0x0); // 12
7805 data << uint32(0x567) << uint32(0x1); // 13
7806 data << uint32(0x566) << uint32(0x1); // 14
7807 data << uint32(0x550) << uint32(0x1); // 15
7808 data << uint32(0x544) << uint32(0x0); // 16
7809 data << uint32(0x536) << uint32(0x0); // 17
7810 data << uint32(0x535) << uint32(0x1); // 18
7811 data << uint32(0x518) << uint32(0x0); // 19
7812 data << uint32(0x517) << uint32(0x0); // 20
7813 data << uint32(0x574) << uint32(0x0); // 21
7814 data << uint32(0x573) << uint32(0x0); // 22
7815 data << uint32(0x572) << uint32(0x0); // 23
7816 data << uint32(0x56f) << uint32(0x0); // 24
7817 data << uint32(0x56e) << uint32(0x0); // 25
7818 data << uint32(0x56d) << uint32(0x0); // 26
7819 data << uint32(0x56c) << uint32(0x0); // 27
7820 data << uint32(0x56b) << uint32(0x0); // 28
7821 data << uint32(0x56a) << uint32(0x1); // 29
7822 data << uint32(0x569) << uint32(0x1); // 30
7823 data << uint32(0x568) << uint32(0x1); // 13
7824 data << uint32(0x565) << uint32(0x0); // 32
7825 data << uint32(0x564) << uint32(0x0); // 33
7826 data << uint32(0x563) << uint32(0x0); // 34
7827 data << uint32(0x562) << uint32(0x0); // 35
7828 data << uint32(0x561) << uint32(0x0); // 36
7829 data << uint32(0x560) << uint32(0x0); // 37
7830 data << uint32(0x55f) << uint32(0x0); // 38
7831 data << uint32(0x55e) << uint32(0x0); // 39
7832 data << uint32(0x55d) << uint32(0x0); // 40
7833 data << uint32(0x3c6) << uint32(0x4); // 41
7834 data << uint32(0x3c4) << uint32(0x6); // 42
7835 data << uint32(0x3c2) << uint32(0x4); // 43
7836 data << uint32(0x516) << uint32(0x1); // 44
7837 data << uint32(0x515) << uint32(0x0); // 45
7838 data << uint32(0x3b6) << uint32(0x6); // 46
7839 data << uint32(0x55c) << uint32(0x0); // 47
7840 data << uint32(0x55b) << uint32(0x0); // 48
7841 data << uint32(0x55a) << uint32(0x0); // 49
7842 data << uint32(0x559) << uint32(0x0); // 50
7843 data << uint32(0x558) << uint32(0x0); // 51
7844 data << uint32(0x557) << uint32(0x0); // 52
7845 data << uint32(0x556) << uint32(0x0); // 53
7846 data << uint32(0x555) << uint32(0x0); // 54
7847 data << uint32(0x554) << uint32(0x1); // 55
7848 data << uint32(0x553) << uint32(0x1); // 56
7849 data << uint32(0x552) << uint32(0x1); // 57
7850 data << uint32(0x551) << uint32(0x1); // 58
7851 data << uint32(0x54f) << uint32(0x0); // 59
7852 data << uint32(0x54e) << uint32(0x0); // 60
7853 data << uint32(0x54d) << uint32(0x1); // 61
7854 data << uint32(0x54c) << uint32(0x0); // 62
7855 data << uint32(0x54b) << uint32(0x0); // 63
7856 data << uint32(0x545) << uint32(0x0); // 64
7857 data << uint32(0x543) << uint32(0x1); // 65
7858 data << uint32(0x542) << uint32(0x0); // 66
7859 data << uint32(0x540) << uint32(0x0); // 67
7860 data << uint32(0x53f) << uint32(0x0); // 68
7861 data << uint32(0x53e) << uint32(0x0); // 69
7862 data << uint32(0x53d) << uint32(0x0); // 70
7863 data << uint32(0x53c) << uint32(0x0); // 71
7864 data << uint32(0x53b) << uint32(0x0); // 72
7865 data << uint32(0x53a) << uint32(0x1); // 73
7866 data << uint32(0x539) << uint32(0x0); // 74
7867 data << uint32(0x538) << uint32(0x0); // 75
7868 data << uint32(0x537) << uint32(0x0); // 76
7869 data << uint32(0x534) << uint32(0x0); // 77
7870 data << uint32(0x533) << uint32(0x0); // 78
7871 data << uint32(0x530) << uint32(0x0); // 79
7872 data << uint32(0x52f) << uint32(0x0); // 80
7873 data << uint32(0x52d) << uint32(0x1); // 81
7874 break;
7875 case 3277: // WS
7876 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7877 bg->FillInitialWorldStates(data);
7878 else
7880 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7881 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7882 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7883 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7884 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7885 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7886 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7887 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7889 break;
7890 case 3358: // AB
7891 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7892 bg->FillInitialWorldStates(data);
7893 else
7895 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7896 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7897 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7898 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7899 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7900 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7901 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7902 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7903 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7904 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7905 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7906 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7907 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7908 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7909 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7910 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7911 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7912 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7913 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7914 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7915 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7916 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7917 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7918 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7919 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7920 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7921 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7922 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7923 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7924 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7925 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7926 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7928 break;
7929 case 3820: // EY
7930 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7931 bg->FillInitialWorldStates(data);
7932 else
7934 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7935 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7936 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7937 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7938 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7939 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7940 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7941 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7942 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7943 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7944 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7945 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7946 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7947 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7948 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7949 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7950 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7951 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7952 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7953 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7954 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7955 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7956 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7957 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7958 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7959 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7960 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7961 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7962 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7963 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7964 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7965 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7966 // and some more ... unknown
7968 break;
7969 case 3483: // Hellfire Peninsula
7970 data << uint32(0x9ba) << uint32(0x1); // 10
7971 data << uint32(0x9b9) << uint32(0x1); // 11
7972 data << uint32(0x9b5) << uint32(0x0); // 12
7973 data << uint32(0x9b4) << uint32(0x1); // 13
7974 data << uint32(0x9b3) << uint32(0x0); // 14
7975 data << uint32(0x9b2) << uint32(0x0); // 15
7976 data << uint32(0x9b1) << uint32(0x1); // 16
7977 data << uint32(0x9b0) << uint32(0x0); // 17
7978 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7979 data << uint32(0x9ac) << uint32(0x0); // 19
7980 data << uint32(0x9a8) << uint32(0x0); // 20
7981 data << uint32(0x9a7) << uint32(0x0); // 21
7982 data << uint32(0x9a6) << uint32(0x1); // 22
7983 break;
7984 case 3519: // Terokkar Forest
7985 data << uint32(0xa41) << uint32(0x0); // 10
7986 data << uint32(0xa40) << uint32(0x14); // 11
7987 data << uint32(0xa3f) << uint32(0x0); // 12
7988 data << uint32(0xa3e) << uint32(0x0); // 13
7989 data << uint32(0xa3d) << uint32(0x5); // 14
7990 data << uint32(0xa3c) << uint32(0x0); // 15
7991 data << uint32(0xa87) << uint32(0x0); // 16
7992 data << uint32(0xa86) << uint32(0x0); // 17
7993 data << uint32(0xa85) << uint32(0x0); // 18
7994 data << uint32(0xa84) << uint32(0x0); // 19
7995 data << uint32(0xa83) << uint32(0x0); // 20
7996 data << uint32(0xa82) << uint32(0x0); // 21
7997 data << uint32(0xa81) << uint32(0x0); // 22
7998 data << uint32(0xa80) << uint32(0x0); // 23
7999 data << uint32(0xa7e) << uint32(0x0); // 24
8000 data << uint32(0xa7d) << uint32(0x0); // 25
8001 data << uint32(0xa7c) << uint32(0x0); // 26
8002 data << uint32(0xa7b) << uint32(0x0); // 27
8003 data << uint32(0xa7a) << uint32(0x0); // 28
8004 data << uint32(0xa79) << uint32(0x0); // 29
8005 data << uint32(0x9d0) << uint32(0x5); // 30
8006 data << uint32(0x9ce) << uint32(0x0); // 31
8007 data << uint32(0x9cd) << uint32(0x0); // 32
8008 data << uint32(0x9cc) << uint32(0x0); // 33
8009 data << uint32(0xa88) << uint32(0x0); // 34
8010 data << uint32(0xad0) << uint32(0x0); // 35
8011 data << uint32(0xacf) << uint32(0x1); // 36
8012 break;
8013 case 3521: // Zangarmarsh
8014 data << uint32(0x9e1) << uint32(0x0); // 10
8015 data << uint32(0x9e0) << uint32(0x0); // 11
8016 data << uint32(0x9df) << uint32(0x0); // 12
8017 data << uint32(0xa5d) << uint32(0x1); // 13
8018 data << uint32(0xa5c) << uint32(0x0); // 14
8019 data << uint32(0xa5b) << uint32(0x1); // 15
8020 data << uint32(0xa5a) << uint32(0x0); // 16
8021 data << uint32(0xa59) << uint32(0x1); // 17
8022 data << uint32(0xa58) << uint32(0x0); // 18
8023 data << uint32(0xa57) << uint32(0x0); // 19
8024 data << uint32(0xa56) << uint32(0x0); // 20
8025 data << uint32(0xa55) << uint32(0x1); // 21
8026 data << uint32(0xa54) << uint32(0x0); // 22
8027 data << uint32(0x9e7) << uint32(0x0); // 23
8028 data << uint32(0x9e6) << uint32(0x0); // 24
8029 data << uint32(0x9e5) << uint32(0x0); // 25
8030 data << uint32(0xa00) << uint32(0x0); // 26
8031 data << uint32(0x9ff) << uint32(0x1); // 27
8032 data << uint32(0x9fe) << uint32(0x0); // 28
8033 data << uint32(0x9fd) << uint32(0x0); // 29
8034 data << uint32(0x9fc) << uint32(0x1); // 30
8035 data << uint32(0x9fb) << uint32(0x0); // 31
8036 data << uint32(0xa62) << uint32(0x0); // 32
8037 data << uint32(0xa61) << uint32(0x1); // 33
8038 data << uint32(0xa60) << uint32(0x1); // 34
8039 data << uint32(0xa5f) << uint32(0x0); // 35
8040 break;
8041 case 3698: // Nagrand Arena
8042 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
8043 bg->FillInitialWorldStates(data);
8044 else
8046 data << uint32(0xa0f) << uint32(0x0); // 7
8047 data << uint32(0xa10) << uint32(0x0); // 8
8048 data << uint32(0xa11) << uint32(0x0); // 9 show
8050 break;
8051 case 3702: // Blade's Edge Arena
8052 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8053 bg->FillInitialWorldStates(data);
8054 else
8056 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8057 data << uint32(0x9f1) << uint32(0x0); // 8 green
8058 data << uint32(0x9f3) << uint32(0x0); // 9 show
8060 break;
8061 case 3968: // Ruins of Lordaeron
8062 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8063 bg->FillInitialWorldStates(data);
8064 else
8066 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8067 data << uint32(0xbb9) << uint32(0x0); // 8 green
8068 data << uint32(0xbba) << uint32(0x0); // 9 show
8070 break;
8071 case 3703: // Shattrath City
8072 break;
8073 default:
8074 data << uint32(0x914) << uint32(0x0); // 7
8075 data << uint32(0x913) << uint32(0x0); // 8
8076 data << uint32(0x912) << uint32(0x0); // 9
8077 data << uint32(0x915) << uint32(0x0); // 10
8078 break;
8080 GetSession()->SendPacket(&data);
8083 uint32 Player::GetXPRestBonus(uint32 xp)
8085 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8087 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8088 rested_bonus = xp;
8090 SetRestBonus( GetRestBonus() - rested_bonus);
8092 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8093 return rested_bonus;
8096 void Player::SetBindPoint(uint64 guid)
8098 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8099 data << uint64(guid);
8100 GetSession()->SendPacket( &data );
8103 void Player::SendTalentWipeConfirm(uint64 guid)
8105 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8106 data << uint64(guid);
8107 data << uint32(resetTalentsCost());
8108 GetSession()->SendPacket( &data );
8111 void Player::SendPetSkillWipeConfirm()
8113 Pet* pet = GetPet();
8114 if(!pet)
8115 return;
8116 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8117 data << pet->GetGUID();
8118 data << uint32(pet->resetTalentsCost());
8119 GetSession()->SendPacket( &data );
8122 /*********************************************************/
8123 /*** STORAGE SYSTEM ***/
8124 /*********************************************************/
8126 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8128 assert(i < 3);
8129 if(i < 2 && item)
8131 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8132 return;
8133 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8134 if(charges == 0)
8135 return;
8136 if(charges > 1)
8137 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8138 else if(charges <= 1)
8140 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8141 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8146 void Player::SetSheath( uint32 sheathed )
8148 switch (sheathed)
8150 case SHEATH_STATE_UNARMED: // no prepared weapon
8151 SetVirtualItemSlot(0,NULL);
8152 SetVirtualItemSlot(1,NULL);
8153 SetVirtualItemSlot(2,NULL);
8154 break;
8155 case SHEATH_STATE_MELEE: // prepared melee weapon
8157 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
8158 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
8159 SetVirtualItemSlot(2,NULL);
8160 }; break;
8161 case SHEATH_STATE_RANGED: // prepared ranged weapon
8162 SetVirtualItemSlot(0,NULL);
8163 SetVirtualItemSlot(1,NULL);
8164 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
8165 break;
8166 default:
8167 SetVirtualItemSlot(0,NULL);
8168 SetVirtualItemSlot(1,NULL);
8169 SetVirtualItemSlot(2,NULL);
8170 break;
8172 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
8175 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8177 uint8 pClass = getClass();
8179 uint8 slots[4];
8180 slots[0] = NULL_SLOT;
8181 slots[1] = NULL_SLOT;
8182 slots[2] = NULL_SLOT;
8183 slots[3] = NULL_SLOT;
8184 switch( proto->InventoryType )
8186 case INVTYPE_HEAD:
8187 slots[0] = EQUIPMENT_SLOT_HEAD;
8188 break;
8189 case INVTYPE_NECK:
8190 slots[0] = EQUIPMENT_SLOT_NECK;
8191 break;
8192 case INVTYPE_SHOULDERS:
8193 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8194 break;
8195 case INVTYPE_BODY:
8196 slots[0] = EQUIPMENT_SLOT_BODY;
8197 break;
8198 case INVTYPE_CHEST:
8199 slots[0] = EQUIPMENT_SLOT_CHEST;
8200 break;
8201 case INVTYPE_ROBE:
8202 slots[0] = EQUIPMENT_SLOT_CHEST;
8203 break;
8204 case INVTYPE_WAIST:
8205 slots[0] = EQUIPMENT_SLOT_WAIST;
8206 break;
8207 case INVTYPE_LEGS:
8208 slots[0] = EQUIPMENT_SLOT_LEGS;
8209 break;
8210 case INVTYPE_FEET:
8211 slots[0] = EQUIPMENT_SLOT_FEET;
8212 break;
8213 case INVTYPE_WRISTS:
8214 slots[0] = EQUIPMENT_SLOT_WRISTS;
8215 break;
8216 case INVTYPE_HANDS:
8217 slots[0] = EQUIPMENT_SLOT_HANDS;
8218 break;
8219 case INVTYPE_FINGER:
8220 slots[0] = EQUIPMENT_SLOT_FINGER1;
8221 slots[1] = EQUIPMENT_SLOT_FINGER2;
8222 break;
8223 case INVTYPE_TRINKET:
8224 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8225 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8226 break;
8227 case INVTYPE_CLOAK:
8228 slots[0] = EQUIPMENT_SLOT_BACK;
8229 break;
8230 case INVTYPE_WEAPON:
8232 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8234 // suggest offhand slot only if know dual wielding
8235 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8236 if(CanDualWield())
8237 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8238 break;
8240 case INVTYPE_SHIELD:
8241 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8242 break;
8243 case INVTYPE_RANGED:
8244 slots[0] = EQUIPMENT_SLOT_RANGED;
8245 break;
8246 case INVTYPE_2HWEAPON:
8247 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8248 if (CanDualWield() && CanTitanGrip())
8249 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8250 break;
8251 case INVTYPE_TABARD:
8252 slots[0] = EQUIPMENT_SLOT_TABARD;
8253 break;
8254 case INVTYPE_WEAPONMAINHAND:
8255 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8256 break;
8257 case INVTYPE_WEAPONOFFHAND:
8258 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8259 break;
8260 case INVTYPE_HOLDABLE:
8261 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8262 break;
8263 case INVTYPE_THROWN:
8264 slots[0] = EQUIPMENT_SLOT_RANGED;
8265 break;
8266 case INVTYPE_RANGEDRIGHT:
8267 slots[0] = EQUIPMENT_SLOT_RANGED;
8268 break;
8269 case INVTYPE_BAG:
8270 slots[0] = INVENTORY_SLOT_BAG_1;
8271 slots[1] = INVENTORY_SLOT_BAG_2;
8272 slots[2] = INVENTORY_SLOT_BAG_3;
8273 slots[3] = INVENTORY_SLOT_BAG_4;
8274 break;
8275 case INVTYPE_RELIC:
8277 switch(proto->SubClass)
8279 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8280 if (pClass == CLASS_PALADIN)
8281 slots[0] = EQUIPMENT_SLOT_RANGED;
8282 break;
8283 case ITEM_SUBCLASS_ARMOR_IDOL:
8284 if (pClass == CLASS_DRUID)
8285 slots[0] = EQUIPMENT_SLOT_RANGED;
8286 break;
8287 case ITEM_SUBCLASS_ARMOR_TOTEM:
8288 if (pClass == CLASS_SHAMAN)
8289 slots[0] = EQUIPMENT_SLOT_RANGED;
8290 break;
8291 case ITEM_SUBCLASS_ARMOR_MISC:
8292 if (pClass == CLASS_WARLOCK)
8293 slots[0] = EQUIPMENT_SLOT_RANGED;
8294 break;
8295 case ITEM_SUBCLASS_ARMOR_SIGIL:
8296 if (pClass == CLASS_DEATH_KNIGHT)
8297 slots[0] = EQUIPMENT_SLOT_RANGED;
8298 break;
8300 break;
8302 default :
8303 return NULL_SLOT;
8306 if( slot != NULL_SLOT )
8308 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8310 for (int i = 0; i < 4; i++)
8312 if ( slots[i] == slot )
8313 return slot;
8317 else
8319 // search free slot at first
8320 for (int i = 0; i < 4; i++)
8322 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8324 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8325 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8326 return slots[i];
8330 // if not found free and can swap return first appropriate from used
8331 for (int i = 0; i < 4; i++)
8333 if ( slots[i] != NULL_SLOT && swap )
8334 return slots[i];
8338 // no free position
8339 return NULL_SLOT;
8342 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8344 Item *pItem;
8345 uint32 tempcount = 0;
8347 uint8 res = EQUIP_ERR_OK;
8349 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
8351 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8352 if( pItem && pItem->GetEntry() == item )
8354 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8355 if(ires==EQUIP_ERR_OK)
8357 tempcount += pItem->GetCount();
8358 if( tempcount >= count )
8359 return EQUIP_ERR_OK;
8361 else
8362 res = ires;
8365 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
8367 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8368 if( pItem && pItem->GetEntry() == item )
8370 tempcount += pItem->GetCount();
8371 if( tempcount >= count )
8372 return EQUIP_ERR_OK;
8375 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8377 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8378 if( pItem && pItem->GetEntry() == item )
8380 tempcount += pItem->GetCount();
8381 if( tempcount >= count )
8382 return EQUIP_ERR_OK;
8385 Bag *pBag;
8386 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8388 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8389 if( pBag )
8391 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8393 pItem = GetItemByPos( i, j );
8394 if( pItem && pItem->GetEntry() == item )
8396 tempcount += pItem->GetCount();
8397 if( tempcount >= count )
8398 return EQUIP_ERR_OK;
8404 // not found req. item count and have unequippable items
8405 return res;
8408 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8410 uint32 count = 0;
8411 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8413 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8414 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8415 count += pItem->GetCount();
8417 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8419 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8420 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8421 count += pItem->GetCount();
8423 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8425 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8426 if( pBag )
8427 count += pBag->GetItemCount(item,skipItem);
8430 if(skipItem && skipItem->GetProto()->GemProperties)
8432 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8434 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8435 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8436 count += pItem->GetGemCountWithID(item);
8440 if(inBankAlso)
8442 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8444 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8445 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8446 count += pItem->GetCount();
8448 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8450 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8451 if( pBag )
8452 count += pBag->GetItemCount(item,skipItem);
8455 if(skipItem && skipItem->GetProto()->GemProperties)
8457 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8459 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8460 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8461 count += pItem->GetGemCountWithID(item);
8466 return count;
8469 Item* Player::GetItemByGuid( uint64 guid ) const
8471 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8473 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8474 if( pItem && pItem->GetGUID() == guid )
8475 return pItem;
8477 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8479 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8480 if( pItem && pItem->GetGUID() == guid )
8481 return pItem;
8484 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8486 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8487 if( pBag )
8489 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8491 Item* pItem = pBag->GetItemByPos( j );
8492 if( pItem && pItem->GetGUID() == guid )
8493 return pItem;
8497 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8499 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8500 if( pBag )
8502 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8504 Item* pItem = pBag->GetItemByPos( j );
8505 if( pItem && pItem->GetGUID() == guid )
8506 return pItem;
8511 return NULL;
8514 Item* Player::GetItemByPos( uint16 pos ) const
8516 uint8 bag = pos >> 8;
8517 uint8 slot = pos & 255;
8518 return GetItemByPos( bag, slot );
8521 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8523 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8524 return m_items[slot];
8525 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8526 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8528 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8529 if ( pBag )
8530 return pBag->GetItemByPos(slot);
8532 return NULL;
8535 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8537 uint16 slot;
8538 switch (attackType)
8540 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8541 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8542 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8543 default: return NULL;
8546 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8547 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8548 return NULL;
8550 if(!useable)
8551 return item;
8553 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8554 return NULL;
8556 return item;
8559 Item* Player::GetShield(bool useable) const
8561 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8562 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8563 return NULL;
8565 if(!useable)
8566 return item;
8568 if( item->IsBroken())
8569 return NULL;
8571 return item;
8574 uint32 Player::GetAttackBySlot( uint8 slot )
8576 switch(slot)
8578 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8579 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8580 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8581 default: return MAX_ATTACK;
8585 bool Player::HasBankBagSlot( uint8 slot ) const
8587 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8588 if( slot < maxslot )
8589 return true;
8590 return false;
8593 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8595 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8596 return true;
8597 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8598 return true;
8599 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8600 return true;
8601 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8602 return true;
8603 return false;
8606 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8608 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8609 return true;
8610 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8611 return true;
8612 return false;
8615 bool Player::IsBankPos( uint8 bag, uint8 slot )
8617 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8618 return true;
8619 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8620 return true;
8621 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8622 return true;
8623 return false;
8626 bool Player::IsBagPos( uint16 pos )
8628 uint8 bag = pos >> 8;
8629 uint8 slot = pos & 255;
8630 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8631 return true;
8632 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8633 return true;
8634 return false;
8637 bool Player::IsValidPos( uint8 bag, uint8 slot )
8639 // post selected
8640 if(bag == NULL_BAG)
8641 return true;
8643 if (bag == INVENTORY_SLOT_BAG_0)
8645 // any post selected
8646 if (slot == NULL_SLOT)
8647 return true;
8649 // equipment
8650 if (slot < EQUIPMENT_SLOT_END)
8651 return true;
8653 // bag equip slots
8654 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8655 return true;
8657 // backpack slots
8658 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8659 return true;
8661 // keyring slots
8662 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8663 return true;
8665 // bank main slots
8666 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8667 return true;
8669 // bank bag slots
8670 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8671 return true;
8673 return false;
8676 // bag content slots
8677 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8679 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8680 if(!pBag)
8681 return false;
8683 // any post selected
8684 if (slot == NULL_SLOT)
8685 return true;
8687 return slot < pBag->GetBagSize();
8690 // bank bag content slots
8691 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8693 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8694 if(!pBag)
8695 return false;
8697 // any post selected
8698 if (slot == NULL_SLOT)
8699 return true;
8701 return slot < pBag->GetBagSize();
8704 // where this?
8705 return false;
8709 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8711 uint32 tempcount = 0;
8712 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8714 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8715 if( pItem && pItem->GetEntry() == item )
8717 tempcount += pItem->GetCount();
8718 if( tempcount >= count )
8719 return true;
8722 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8724 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8725 if( pItem && pItem->GetEntry() == item )
8727 tempcount += pItem->GetCount();
8728 if( tempcount >= count )
8729 return true;
8732 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8734 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8736 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8738 Item* pItem = GetItemByPos( i, j );
8739 if( pItem && pItem->GetEntry() == item )
8741 tempcount += pItem->GetCount();
8742 if( tempcount >= count )
8743 return true;
8749 if(inBankAlso)
8751 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8753 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8754 if( pItem && pItem->GetEntry() == item )
8756 tempcount += pItem->GetCount();
8757 if( tempcount >= count )
8758 return true;
8761 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8763 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8765 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8767 Item* pItem = GetItemByPos( i, j );
8768 if( pItem && pItem->GetEntry() == item )
8770 tempcount += pItem->GetCount();
8771 if( tempcount >= count )
8772 return true;
8779 return false;
8782 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8784 uint32 tempcount = 0;
8785 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8787 if(i==int(except_slot))
8788 continue;
8790 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8791 if( pItem && pItem->GetEntry() == item)
8793 tempcount += pItem->GetCount();
8794 if( tempcount >= count )
8795 return true;
8799 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8800 if (pProto && pProto->GemProperties)
8802 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8804 if(i==int(except_slot))
8805 continue;
8807 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8808 if( pItem && pItem->GetProto()->Socket[0].Color)
8810 tempcount += pItem->GetGemCountWithID(item);
8811 if( tempcount >= count )
8812 return true;
8817 return false;
8820 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8822 uint32 tempcount = 0;
8823 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8825 if(i==int(except_slot))
8826 continue;
8828 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8829 if (!pItem)
8830 continue;
8832 ItemPrototype const *pProto = pItem->GetProto();
8833 if (!pProto)
8834 continue;
8836 if (pProto->ItemLimitCategory == limitCategory)
8838 tempcount += pItem->GetCount();
8839 if( tempcount >= count )
8840 return true;
8843 if( pProto->Socket[0].Color)
8845 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8846 if( tempcount >= count )
8847 return true;
8851 return false;
8854 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8856 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8857 if( !pProto )
8859 if(no_space_count)
8860 *no_space_count = count;
8861 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8864 // no maximum
8865 if(pProto->MaxCount <= 0)
8866 return EQUIP_ERR_OK;
8868 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8870 if (curcount + count > uint32(pProto->MaxCount))
8872 if(no_space_count)
8873 *no_space_count = count +curcount - pProto->MaxCount;
8874 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8877 return EQUIP_ERR_OK;
8880 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8882 Item *pItem;
8883 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8885 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8886 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8887 return true;
8889 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8891 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8892 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8893 return true;
8895 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8897 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8899 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8901 pItem = GetItemByPos( i, j );
8902 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8903 return true;
8907 return false;
8910 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8912 Item* pItem2 = GetItemByPos( bag, slot );
8914 // ignore move item (this slot will be empty at move)
8915 if(pItem2==pSrcItem)
8916 pItem2 = NULL;
8918 uint32 need_space;
8920 // empty specific slot - check item fit to slot
8921 if( !pItem2 || swap )
8923 if( bag == INVENTORY_SLOT_BAG_0 )
8925 // keyring case
8926 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8927 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8929 // vanitypet case (not use, vanity pets stored as spells)
8930 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END)
8931 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8933 // currencytoken case (disabled until proper implement)
8934 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS*/))
8935 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8937 // guestbag case (disabled until proper implement)
8938 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS*/))
8939 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8941 // prevent cheating
8942 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8943 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8945 else
8947 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8948 if( !pBag )
8949 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8951 ItemPrototype const* pBagProto = pBag->GetProto();
8952 if( !pBagProto )
8953 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8955 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8956 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8959 // non empty stack with space
8960 need_space = pProto->GetMaxStackSize();
8962 // non empty slot, check item type
8963 else
8965 // check item type
8966 if(pItem2->GetEntry() != pProto->ItemId)
8967 return EQUIP_ERR_ITEM_CANT_STACK;
8969 // check free space
8970 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8971 return EQUIP_ERR_ITEM_CANT_STACK;
8973 // free stack space or infinity
8974 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8977 if(need_space > count)
8978 need_space = count;
8980 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8981 if(!newPosition.isContainedIn(dest))
8983 dest.push_back(newPosition);
8984 count -= need_space;
8986 return EQUIP_ERR_OK;
8989 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
8991 // skip specific bag already processed in first called _CanStoreItem_InBag
8992 if(bag==skip_bag)
8993 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8995 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8996 if( !pBag )
8997 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8999 ItemPrototype const* pBagProto = pBag->GetProto();
9000 if( !pBagProto )
9001 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9003 // specialized bag mode or non-specilized
9004 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
9005 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9007 if( !ItemCanGoIntoBag(pProto,pBagProto) )
9008 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9010 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9012 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9013 if(j==skip_slot)
9014 continue;
9016 Item* pItem2 = GetItemByPos( bag, j );
9018 // ignore move item (this slot will be empty at move)
9019 if(pItem2==pSrcItem)
9020 pItem2 = NULL;
9022 // if merge skip empty, if !merge skip non-empty
9023 if((pItem2!=NULL)!=merge)
9024 continue;
9026 if( pItem2 )
9028 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9030 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9031 if(need_space > count)
9032 need_space = count;
9034 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9035 if(!newPosition.isContainedIn(dest))
9037 dest.push_back(newPosition);
9038 count -= need_space;
9040 if(count==0)
9041 return EQUIP_ERR_OK;
9045 else
9047 uint32 need_space = pProto->GetMaxStackSize();
9048 if(need_space > count)
9049 need_space = count;
9051 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9052 if(!newPosition.isContainedIn(dest))
9054 dest.push_back(newPosition);
9055 count -= need_space;
9057 if(count==0)
9058 return EQUIP_ERR_OK;
9062 return EQUIP_ERR_OK;
9065 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
9067 for(uint32 j = slot_begin; j < slot_end; j++)
9069 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9070 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
9071 continue;
9073 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
9075 // ignore move item (this slot will be empty at move)
9076 if(pItem2==pSrcItem)
9077 pItem2 = NULL;
9079 // if merge skip empty, if !merge skip non-empty
9080 if((pItem2!=NULL)!=merge)
9081 continue;
9083 if( pItem2 )
9085 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9087 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9088 if(need_space > count)
9089 need_space = count;
9090 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9091 if(!newPosition.isContainedIn(dest))
9093 dest.push_back(newPosition);
9094 count -= need_space;
9096 if(count==0)
9097 return EQUIP_ERR_OK;
9101 else
9103 uint32 need_space = pProto->GetMaxStackSize();
9104 if(need_space > count)
9105 need_space = count;
9107 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9108 if(!newPosition.isContainedIn(dest))
9110 dest.push_back(newPosition);
9111 count -= need_space;
9113 if(count==0)
9114 return EQUIP_ERR_OK;
9118 return EQUIP_ERR_OK;
9121 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9123 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9125 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
9126 if( !pProto )
9128 if(no_space_count)
9129 *no_space_count = count;
9130 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9133 if(pItem && pItem->IsBindedNotWith(GetGUID()))
9135 if(no_space_count)
9136 *no_space_count = count;
9137 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9140 // check count of items (skip for auto move for same player from bank)
9141 uint32 no_similar_count = 0; // can't store this amount similar items
9142 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9143 if(res!=EQUIP_ERR_OK)
9145 if(count==no_similar_count)
9147 if(no_space_count)
9148 *no_space_count = no_similar_count;
9149 return res;
9151 count -= no_similar_count;
9154 // in specific slot
9155 if( bag != NULL_BAG && slot != NULL_SLOT )
9157 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9158 if(res!=EQUIP_ERR_OK)
9160 if(no_space_count)
9161 *no_space_count = count + no_similar_count;
9162 return res;
9165 if(count==0)
9167 if(no_similar_count==0)
9168 return EQUIP_ERR_OK;
9170 if(no_space_count)
9171 *no_space_count = count + no_similar_count;
9172 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9176 // not specific slot or have space for partly store only in specific slot
9178 // in specific bag
9179 if( bag != NULL_BAG )
9181 // search stack in bag for merge to
9182 if( pProto->Stackable != 1 )
9184 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9186 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9187 if(res!=EQUIP_ERR_OK)
9189 if(no_space_count)
9190 *no_space_count = count + no_similar_count;
9191 return res;
9194 if(count==0)
9196 if(no_similar_count==0)
9197 return EQUIP_ERR_OK;
9199 if(no_space_count)
9200 *no_space_count = count + no_similar_count;
9201 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9204 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9205 if(res!=EQUIP_ERR_OK)
9207 if(no_space_count)
9208 *no_space_count = count + no_similar_count;
9209 return res;
9212 if(count==0)
9214 if(no_similar_count==0)
9215 return EQUIP_ERR_OK;
9217 if(no_space_count)
9218 *no_space_count = count + no_similar_count;
9219 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9222 else // equipped bag
9224 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9225 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9226 if(res!=EQUIP_ERR_OK)
9227 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9229 if(res!=EQUIP_ERR_OK)
9231 if(no_space_count)
9232 *no_space_count = count + no_similar_count;
9233 return res;
9236 if(count==0)
9238 if(no_similar_count==0)
9239 return EQUIP_ERR_OK;
9241 if(no_space_count)
9242 *no_space_count = count + no_similar_count;
9243 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9248 // search free slot in bag for place to
9249 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9251 // search free slot - keyring case
9252 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9254 uint32 keyringSize = GetMaxKeyringSize();
9255 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9256 if(res!=EQUIP_ERR_OK)
9258 if(no_space_count)
9259 *no_space_count = count + no_similar_count;
9260 return res;
9263 if(count==0)
9265 if(no_similar_count==0)
9266 return EQUIP_ERR_OK;
9268 if(no_space_count)
9269 *no_space_count = count + no_similar_count;
9270 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9274 // Vanity pet case skipped as not used
9276 /* until proper implementation
9277 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9279 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9280 if(res!=EQUIP_ERR_OK)
9282 if(no_space_count)
9283 *no_space_count = count + no_similar_count;
9284 return res;
9287 if(count==0)
9289 if(no_similar_count==0)
9290 return EQUIP_ERR_OK;
9292 if(no_space_count)
9293 *no_space_count = count + no_similar_count;
9294 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9298 /* until proper implementation
9299 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9301 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9302 if(res!=EQUIP_ERR_OK)
9304 if(no_space_count)
9305 *no_space_count = count + no_similar_count;
9306 return res;
9309 if(count==0)
9311 if(no_similar_count==0)
9312 return EQUIP_ERR_OK;
9314 if(no_space_count)
9315 *no_space_count = count + no_similar_count;
9316 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9321 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9322 if(res!=EQUIP_ERR_OK)
9324 if(no_space_count)
9325 *no_space_count = count + no_similar_count;
9326 return res;
9329 if(count==0)
9331 if(no_similar_count==0)
9332 return EQUIP_ERR_OK;
9334 if(no_space_count)
9335 *no_space_count = count + no_similar_count;
9336 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9339 else // equipped bag
9341 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9342 if(res!=EQUIP_ERR_OK)
9343 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9345 if(res!=EQUIP_ERR_OK)
9347 if(no_space_count)
9348 *no_space_count = count + no_similar_count;
9349 return res;
9352 if(count==0)
9354 if(no_similar_count==0)
9355 return EQUIP_ERR_OK;
9357 if(no_space_count)
9358 *no_space_count = count + no_similar_count;
9359 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9364 // not specific bag or have space for partly store only in specific bag
9366 // search stack for merge to
9367 if( pProto->Stackable != 1 )
9369 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9370 if(res!=EQUIP_ERR_OK)
9372 if(no_space_count)
9373 *no_space_count = count + no_similar_count;
9374 return res;
9377 if(count==0)
9379 if(no_similar_count==0)
9380 return EQUIP_ERR_OK;
9382 if(no_space_count)
9383 *no_space_count = count + no_similar_count;
9384 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9387 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9388 if(res!=EQUIP_ERR_OK)
9390 if(no_space_count)
9391 *no_space_count = count + no_similar_count;
9392 return res;
9395 if(count==0)
9397 if(no_similar_count==0)
9398 return EQUIP_ERR_OK;
9400 if(no_space_count)
9401 *no_space_count = count + no_similar_count;
9402 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9405 if( pProto->BagFamily )
9407 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9409 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9410 if(res!=EQUIP_ERR_OK)
9411 continue;
9413 if(count==0)
9415 if(no_similar_count==0)
9416 return EQUIP_ERR_OK;
9418 if(no_space_count)
9419 *no_space_count = count + no_similar_count;
9420 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9425 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9427 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9428 if(res!=EQUIP_ERR_OK)
9429 continue;
9431 if(count==0)
9433 if(no_similar_count==0)
9434 return EQUIP_ERR_OK;
9436 if(no_space_count)
9437 *no_space_count = count + no_similar_count;
9438 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9443 // search free slot - special bag case
9444 if( pProto->BagFamily )
9446 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9448 uint32 keyringSize = GetMaxKeyringSize();
9449 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9450 if(res!=EQUIP_ERR_OK)
9452 if(no_space_count)
9453 *no_space_count = count + no_similar_count;
9454 return res;
9457 if(count==0)
9459 if(no_similar_count==0)
9460 return EQUIP_ERR_OK;
9462 if(no_space_count)
9463 *no_space_count = count + no_similar_count;
9464 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9468 // Vanity pet case skipped as not used
9470 /* until proper implementation
9471 else if(false pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9473 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9474 if(res!=EQUIP_ERR_OK)
9476 if(no_space_count)
9477 *no_space_count = count + no_similar_count;
9478 return res;
9481 if(count==0)
9483 if(no_similar_count==0)
9484 return EQUIP_ERR_OK;
9486 if(no_space_count)
9487 *no_space_count = count + no_similar_count;
9488 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9492 /* until proper implementation
9493 else if(false pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9495 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9496 if(res!=EQUIP_ERR_OK)
9498 if(no_space_count)
9499 *no_space_count = count + no_similar_count;
9500 return res;
9503 if(count==0)
9505 if(no_similar_count==0)
9506 return EQUIP_ERR_OK;
9508 if(no_space_count)
9509 *no_space_count = count + no_similar_count;
9510 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9515 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9517 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9518 if(res!=EQUIP_ERR_OK)
9519 continue;
9521 if(count==0)
9523 if(no_similar_count==0)
9524 return EQUIP_ERR_OK;
9526 if(no_space_count)
9527 *no_space_count = count + no_similar_count;
9528 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9533 // search free slot
9534 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9535 if(res!=EQUIP_ERR_OK)
9537 if(no_space_count)
9538 *no_space_count = count + no_similar_count;
9539 return res;
9542 if(count==0)
9544 if(no_similar_count==0)
9545 return EQUIP_ERR_OK;
9547 if(no_space_count)
9548 *no_space_count = count + no_similar_count;
9549 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9552 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9554 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9555 if(res!=EQUIP_ERR_OK)
9556 continue;
9558 if(count==0)
9560 if(no_similar_count==0)
9561 return EQUIP_ERR_OK;
9563 if(no_space_count)
9564 *no_space_count = count + no_similar_count;
9565 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9569 if(no_space_count)
9570 *no_space_count = count + no_similar_count;
9572 return EQUIP_ERR_INVENTORY_FULL;
9575 //////////////////////////////////////////////////////////////////////////
9576 uint8 Player::CanStoreItems( Item **pItems,int count) const
9578 Item *pItem2;
9580 // fill space table
9581 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9582 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9583 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9584 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9585 int inv_quests[QUESTBAG_SLOT_END-QUESTBAG_SLOT_START];
9587 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9588 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9589 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9590 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9591 memset(inv_quests,0,sizeof(int)*(QUESTBAG_SLOT_END-QUESTBAG_SLOT_START));
9593 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9595 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9597 if (pItem2 && !pItem2->IsInTrade())
9599 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9603 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9605 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9607 if (pItem2 && !pItem2->IsInTrade())
9609 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9613 // Vanity pet case skipped as not used
9615 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
9617 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9619 if (pItem2 && !pItem2->IsInTrade())
9621 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9625 for(int i = QUESTBAG_SLOT_START; i < QUESTBAG_SLOT_END; i++)
9627 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9629 if (pItem2 && !pItem2->IsInTrade())
9631 inv_quests[i-QUESTBAG_SLOT_START] = pItem2->GetCount();
9635 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9637 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9639 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9641 pItem2 = GetItemByPos( i, j );
9642 if (pItem2 && !pItem2->IsInTrade())
9644 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9650 // check free space for all items
9651 for (int k=0;k<count;k++)
9653 Item *pItem = pItems[k];
9655 // no item
9656 if (!pItem) continue;
9658 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9659 ItemPrototype const *pProto = pItem->GetProto();
9661 // strange item
9662 if( !pProto )
9663 return EQUIP_ERR_ITEM_NOT_FOUND;
9665 // item it 'bind'
9666 if(pItem->IsBindedNotWith(GetGUID()))
9667 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9669 Bag *pBag;
9670 ItemPrototype const *pBagProto;
9672 // item is 'one item only'
9673 uint8 res = CanTakeMoreSimilarItems(pItem);
9674 if(res != EQUIP_ERR_OK)
9675 return res;
9677 // search stack for merge to
9678 if( pProto->Stackable != 1 )
9680 bool b_found = false;
9682 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9684 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9685 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9687 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9688 b_found = true;
9689 break;
9692 if (b_found) continue;
9694 // Vanity pet case skipped as not used
9696 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9698 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9699 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9701 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9702 b_found = true;
9703 break;
9706 if (b_found) continue;
9708 for(int t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; t++)
9710 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9711 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_quests[t-QUESTBAG_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9713 inv_quests[t-QUESTBAG_SLOT_START] += pItem->GetCount();
9714 b_found = true;
9715 break;
9718 if (b_found) continue;
9720 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9722 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9723 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9725 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9726 b_found = true;
9727 break;
9730 if (b_found) continue;
9732 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9734 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9735 if( pBag )
9737 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9739 pItem2 = GetItemByPos( t, j );
9740 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9742 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9743 b_found = true;
9744 break;
9749 if (b_found) continue;
9752 // special bag case
9753 if( pProto->BagFamily )
9755 bool b_found = false;
9756 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9758 uint32 keyringSize = GetMaxKeyringSize();
9759 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9761 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9763 inv_keys[t-KEYRING_SLOT_START] = 1;
9764 b_found = true;
9765 break;
9770 if (b_found) continue;
9772 // Vanity pet case skipped as not used
9774 /* until proper implementation
9775 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9777 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9779 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9781 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9782 b_found = true;
9783 break;
9788 if (b_found) continue;
9790 /* until proper implementation
9791 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9793 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9795 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9797 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9798 b_found = true;
9799 break;
9804 if (b_found) continue;
9807 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9809 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9810 if( pBag )
9812 pBagProto = pBag->GetProto();
9814 // not plain container check
9815 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9816 ItemCanGoIntoBag(pProto,pBagProto) )
9818 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9820 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9822 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9823 b_found = true;
9824 break;
9830 if (b_found) continue;
9833 // search free slot
9834 bool b_found = false;
9835 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9837 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9839 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9840 b_found = true;
9841 break;
9844 if (b_found) continue;
9846 // search free slot in bags
9847 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9849 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9850 if( pBag )
9852 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9854 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9856 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9857 b_found = true;
9858 break;
9864 // no free slot found?
9865 if (!b_found)
9866 return EQUIP_ERR_INVENTORY_FULL;
9869 return EQUIP_ERR_OK;
9872 //////////////////////////////////////////////////////////////////////////
9873 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9875 dest = 0;
9876 Item *pItem = Item::CreateItem( item, 1, this );
9877 if( pItem )
9879 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9880 delete pItem;
9881 return result;
9884 return EQUIP_ERR_ITEM_NOT_FOUND;
9887 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9889 dest = 0;
9890 if( pItem )
9892 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9893 ItemPrototype const *pProto = pItem->GetProto();
9894 if( pProto )
9896 if(pItem->IsBindedNotWith(GetGUID()))
9897 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9899 // check count of items (skip for auto move for same player from bank)
9900 uint8 res = CanTakeMoreSimilarItems(pItem);
9901 if(res != EQUIP_ERR_OK)
9902 return res;
9904 // check this only in game
9905 if(not_loading)
9907 // May be here should be more stronger checks; STUNNED checked
9908 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9909 if (hasUnitState(UNIT_STAT_STUNNED))
9910 return EQUIP_ERR_YOU_ARE_STUNNED;
9912 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9913 // - combat
9914 // - in-progress arenas
9915 if( !pProto->CanChangeEquipStateInCombat() )
9917 if( isInCombat() )
9918 return EQUIP_ERR_NOT_IN_COMBAT;
9920 if(BattleGround* bg = GetBattleGround())
9921 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9922 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9925 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9926 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9928 if(IsNonMeleeSpellCasted(false))
9929 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9932 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9933 if( eslot == NULL_SLOT )
9934 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9936 uint8 msg = CanUseItem( pItem , not_loading );
9937 if( msg != EQUIP_ERR_OK )
9938 return msg;
9939 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9940 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9942 // if swap ignore item (equipped also)
9943 if(uint8 res = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9944 return res;
9946 // check unique-equipped special item classes
9947 if (pProto->Class == ITEM_CLASS_QUIVER)
9949 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9951 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9953 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9955 if( pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot ) )
9957 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9958 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9959 else
9960 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9967 uint32 type = pProto->InventoryType;
9969 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9971 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9973 if(!CanDualWield())
9974 return EQUIP_ERR_CANT_DUAL_WIELD;
9976 else if (type == INVTYPE_2HWEAPON)
9978 if(!CanDualWield() || !CanTitanGrip())
9979 return EQUIP_ERR_CANT_DUAL_WIELD;
9982 if(IsTwoHandUsed())
9983 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9986 // equip two-hand weapon case (with possible unequip 2 items)
9987 if( type == INVTYPE_2HWEAPON )
9989 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9991 if (!CanTitanGrip())
9992 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9994 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9995 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9997 if (!CanTitanGrip())
9999 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
10000 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
10001 ItemPosCountVec off_dest;
10002 if( offItem && (!not_loading ||
10003 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
10004 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
10005 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
10008 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
10009 return EQUIP_ERR_OK;
10012 if( !swap )
10013 return EQUIP_ERR_ITEM_NOT_FOUND;
10014 else
10015 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
10018 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
10020 // Applied only to equipped items and bank bags
10021 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
10022 return EQUIP_ERR_OK;
10024 Item* pItem = GetItemByPos(pos);
10026 // Applied only to existed equipped item
10027 if( !pItem )
10028 return EQUIP_ERR_OK;
10030 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
10032 ItemPrototype const *pProto = pItem->GetProto();
10033 if( !pProto )
10034 return EQUIP_ERR_ITEM_NOT_FOUND;
10036 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10037 // - combat
10038 // - in-progress arenas
10039 if( !pProto->CanChangeEquipStateInCombat() )
10041 if( isInCombat() )
10042 return EQUIP_ERR_NOT_IN_COMBAT;
10044 if(BattleGround* bg = GetBattleGround())
10045 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
10046 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
10049 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
10050 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
10052 return EQUIP_ERR_OK;
10055 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
10057 if( !pItem )
10058 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10060 uint32 count = pItem->GetCount();
10062 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
10063 ItemPrototype const *pProto = pItem->GetProto();
10064 if( !pProto )
10065 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10067 if( pItem->IsBindedNotWith(GetGUID()) )
10068 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10070 // check count of items (skip for auto move for same player from bank)
10071 uint8 res = CanTakeMoreSimilarItems(pItem);
10072 if(res != EQUIP_ERR_OK)
10073 return res;
10075 // in specific slot
10076 if( bag != NULL_BAG && slot != NULL_SLOT )
10078 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
10080 if (!pItem->IsBag())
10081 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
10083 Bag *pBag = (Bag*)pItem;
10084 if( !HasBankBagSlot( slot ) )
10085 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
10087 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
10088 return cantuse;
10091 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
10092 if(res!=EQUIP_ERR_OK)
10093 return res;
10095 if(count==0)
10096 return EQUIP_ERR_OK;
10099 // not specific slot or have space for partly store only in specific slot
10101 // in specific bag
10102 if( bag != NULL_BAG )
10104 if( pProto->InventoryType == INVTYPE_BAG )
10106 Bag *pBag = (Bag*)pItem;
10107 if( pBag && !pBag->IsEmpty() )
10108 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
10111 // search stack in bag for merge to
10112 if( pProto->Stackable != 1 )
10114 if( bag == INVENTORY_SLOT_BAG_0 )
10116 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10117 if(res!=EQUIP_ERR_OK)
10118 return res;
10120 if(count==0)
10121 return EQUIP_ERR_OK;
10123 else
10125 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
10126 if(res!=EQUIP_ERR_OK)
10127 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
10129 if(res!=EQUIP_ERR_OK)
10130 return res;
10132 if(count==0)
10133 return EQUIP_ERR_OK;
10137 // search free slot in bag
10138 if( bag == INVENTORY_SLOT_BAG_0 )
10140 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10141 if(res!=EQUIP_ERR_OK)
10142 return res;
10144 if(count==0)
10145 return EQUIP_ERR_OK;
10147 else
10149 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
10150 if(res!=EQUIP_ERR_OK)
10151 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
10153 if(res!=EQUIP_ERR_OK)
10154 return res;
10156 if(count==0)
10157 return EQUIP_ERR_OK;
10161 // not specific bag or have space for partly store only in specific bag
10163 // search stack for merge to
10164 if( pProto->Stackable != 1 )
10166 // in slots
10167 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10168 if(res!=EQUIP_ERR_OK)
10169 return res;
10171 if(count==0)
10172 return EQUIP_ERR_OK;
10174 // in special bags
10175 if( pProto->BagFamily )
10177 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10179 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10180 if(res!=EQUIP_ERR_OK)
10181 continue;
10183 if(count==0)
10184 return EQUIP_ERR_OK;
10188 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10190 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10191 if(res!=EQUIP_ERR_OK)
10192 continue;
10194 if(count==0)
10195 return EQUIP_ERR_OK;
10199 // search free place in special bag
10200 if( pProto->BagFamily )
10202 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10204 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10205 if(res!=EQUIP_ERR_OK)
10206 continue;
10208 if(count==0)
10209 return EQUIP_ERR_OK;
10213 // search free space
10214 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10215 if(res!=EQUIP_ERR_OK)
10216 return res;
10218 if(count==0)
10219 return EQUIP_ERR_OK;
10221 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10223 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10224 if(res!=EQUIP_ERR_OK)
10225 continue;
10227 if(count==0)
10228 return EQUIP_ERR_OK;
10230 return EQUIP_ERR_BANK_FULL;
10233 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10235 if( pItem )
10237 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10238 if( !isAlive() && not_loading )
10239 return EQUIP_ERR_YOU_ARE_DEAD;
10240 //if( isStunned() )
10241 // return EQUIP_ERR_YOU_ARE_STUNNED;
10242 ItemPrototype const *pProto = pItem->GetProto();
10243 if( pProto )
10245 if( pItem->IsBindedNotWith(GetGUID()) )
10246 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10247 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10248 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10249 if( pItem->GetSkill() != 0 )
10251 if( GetSkillValue( pItem->GetSkill() ) == 0 )
10252 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10254 if( pProto->RequiredSkill != 0 )
10256 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10257 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10258 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10259 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10261 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10262 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10263 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
10264 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10265 if( getLevel() < pProto->RequiredLevel )
10266 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10267 return EQUIP_ERR_OK;
10270 return EQUIP_ERR_ITEM_NOT_FOUND;
10273 bool Player::CanUseItem( ItemPrototype const *pProto )
10275 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10277 if( pProto )
10279 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10280 return false;
10281 if( pProto->RequiredSkill != 0 )
10283 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10284 return false;
10285 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10286 return false;
10288 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10289 return false;
10290 if( getLevel() < pProto->RequiredLevel )
10291 return false;
10292 return true;
10294 return false;
10297 uint8 Player::CanUseAmmo( uint32 item ) const
10299 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10300 if( !isAlive() )
10301 return EQUIP_ERR_YOU_ARE_DEAD;
10302 //if( isStunned() )
10303 // return EQUIP_ERR_YOU_ARE_STUNNED;
10304 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10305 if( pProto )
10307 if( pProto->InventoryType!= INVTYPE_AMMO )
10308 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10309 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10310 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10311 if( pProto->RequiredSkill != 0 )
10313 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10314 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10315 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10316 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10318 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10319 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10320 /*if( GetReputation() < pProto->RequiredReputation )
10321 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10323 if( getLevel() < pProto->RequiredLevel )
10324 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10326 // Requires No Ammo
10327 if(GetDummyAura(46699))
10328 return EQUIP_ERR_BAG_FULL6;
10330 return EQUIP_ERR_OK;
10332 return EQUIP_ERR_ITEM_NOT_FOUND;
10335 void Player::SetAmmo( uint32 item )
10337 if(!item)
10338 return;
10340 // already set
10341 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10342 return;
10344 // check ammo
10345 if(item)
10347 uint8 msg = CanUseAmmo( item );
10348 if( msg != EQUIP_ERR_OK )
10350 SendEquipError( msg, NULL, NULL );
10351 return;
10355 SetUInt32Value(PLAYER_AMMO_ID, item);
10357 _ApplyAmmoBonuses();
10360 void Player::RemoveAmmo()
10362 SetUInt32Value(PLAYER_AMMO_ID, 0);
10364 m_ammoDPS = 0.0f;
10366 if(CanModifyStats())
10367 UpdateDamagePhysical(RANGED_ATTACK);
10370 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10371 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10373 uint32 count = 0;
10374 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10375 count += itr->count;
10377 Item *pItem = Item::CreateItem( item, count, this );
10378 if( pItem )
10380 ItemAddedQuestCheck( item, count );
10381 if(randomPropertyId)
10382 pItem->SetItemRandomProperties(randomPropertyId);
10383 pItem = StoreItem( dest, pItem, update );
10385 return pItem;
10388 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10390 if( !pItem )
10391 return NULL;
10393 Item* lastItem = pItem;
10395 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10397 uint16 pos = itr->pos;
10398 uint32 count = itr->count;
10400 ++itr;
10402 if(itr == dest.end())
10404 lastItem = _StoreItem(pos,pItem,count,false,update);
10405 break;
10408 lastItem = _StoreItem(pos,pItem,count,true,update);
10411 return lastItem;
10414 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10415 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10417 if( !pItem )
10418 return NULL;
10420 uint8 bag = pos >> 8;
10421 uint8 slot = pos & 255;
10423 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10425 Item *pItem2 = GetItemByPos( bag, slot );
10427 if( !pItem2 )
10429 if(clone)
10430 pItem = pItem->CloneItem(count,this);
10431 else
10432 pItem->SetCount(count);
10434 if(!pItem)
10435 return NULL;
10437 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10438 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10439 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10440 pItem->SetBinding( true );
10442 if( bag == INVENTORY_SLOT_BAG_0 )
10444 m_items[slot] = pItem;
10445 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10446 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10447 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10449 pItem->SetSlot( slot );
10450 pItem->SetContainer( NULL );
10452 if( IsInWorld() && update )
10454 pItem->AddToWorld();
10455 pItem->SendUpdateToPlayer( this );
10458 pItem->SetState(ITEM_CHANGED, this);
10460 else
10462 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10463 if( pBag )
10465 pBag->StoreItem( slot, pItem, update );
10466 if( IsInWorld() && update )
10468 pItem->AddToWorld();
10469 pItem->SendUpdateToPlayer( this );
10471 pItem->SetState(ITEM_CHANGED, this);
10472 pBag->SetState(ITEM_CHANGED, this);
10476 AddEnchantmentDurations(pItem);
10477 AddItemDurations(pItem);
10479 return pItem;
10481 else
10483 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10484 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10485 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10486 pItem2->SetBinding( true );
10488 pItem2->SetCount( pItem2->GetCount() + count );
10489 if( IsInWorld() && update )
10490 pItem2->SendUpdateToPlayer( this );
10492 if(!clone)
10494 // delete item (it not in any slot currently)
10495 if( IsInWorld() && update )
10497 pItem->RemoveFromWorld();
10498 pItem->DestroyForPlayer( this );
10501 RemoveEnchantmentDurations(pItem);
10502 RemoveItemDurations(pItem);
10504 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10505 pItem->SetState(ITEM_REMOVED, this);
10507 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10508 AddEnchantmentDurations(pItem2);
10510 pItem2->SetState(ITEM_CHANGED, this);
10512 return pItem2;
10516 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10518 Item *pItem = Item::CreateItem( item, 1, this );
10519 if( pItem )
10521 ItemAddedQuestCheck( item, 1 );
10522 Item * retItem = EquipItem( pos, pItem, update );
10524 return retItem;
10526 return NULL;
10529 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10531 if( pItem )
10533 AddEnchantmentDurations(pItem);
10534 AddItemDurations(pItem);
10536 uint8 bag = pos >> 8;
10537 uint8 slot = pos & 255;
10539 Item *pItem2 = GetItemByPos( bag, slot );
10541 if( !pItem2 )
10543 VisualizeItem( slot, pItem);
10545 if(isAlive())
10547 ItemPrototype const *pProto = pItem->GetProto();
10549 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10550 if(pProto && pProto->ItemSet)
10551 AddItemsSetItem(this,pItem);
10553 _ApplyItemMods(pItem, slot, true);
10555 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10557 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10559 if (getClass() == CLASS_ROGUE)
10560 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10562 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10564 if (!spellProto)
10565 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10566 else
10568 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10570 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10571 data << uint64(GetGUID());
10572 data << uint8(1);
10573 data << uint32(cooldownSpell);
10574 data << uint32(0);
10575 GetSession()->SendPacket(&data);
10580 if( IsInWorld() && update )
10582 pItem->AddToWorld();
10583 pItem->SendUpdateToPlayer( this );
10586 ApplyEquipCooldown(pItem);
10588 if( slot == EQUIPMENT_SLOT_MAINHAND )
10589 UpdateExpertise(BASE_ATTACK);
10590 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10591 UpdateExpertise(OFF_ATTACK);
10593 else
10595 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10596 if( IsInWorld() && update )
10597 pItem2->SendUpdateToPlayer( this );
10599 // delete item (it not in any slot currently)
10600 //pItem->DeleteFromDB();
10601 if( IsInWorld() && update )
10603 pItem->RemoveFromWorld();
10604 pItem->DestroyForPlayer( this );
10607 RemoveEnchantmentDurations(pItem);
10608 RemoveItemDurations(pItem);
10610 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10611 pItem->SetState(ITEM_REMOVED, this);
10612 pItem2->SetState(ITEM_CHANGED, this);
10614 ApplyEquipCooldown(pItem2);
10616 return pItem2;
10620 return pItem;
10623 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10625 if( pItem )
10627 AddEnchantmentDurations(pItem);
10628 AddItemDurations(pItem);
10630 uint8 slot = pos & 255;
10631 VisualizeItem( slot, pItem);
10633 if( IsInWorld() )
10635 pItem->AddToWorld();
10636 pItem->SendUpdateToPlayer( this );
10641 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10643 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10644 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10645 // entry // Size: 1
10646 // inspected enchantments // Size: 6
10647 // ? // Size: 5
10648 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10649 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10650 // // = 16
10652 if(pItem)
10654 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10656 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10657 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10659 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10660 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10662 // Use SetInt16Value to prevent set high part to FFFF for negative value
10663 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10664 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10666 else
10668 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10670 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10671 SetUInt32Value(VisibleBase + 0, 0);
10673 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10674 SetUInt32Value(VisibleBase + 1 + i, 0);
10676 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10677 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10681 void Player::VisualizeItem( uint8 slot, Item *pItem)
10683 if(!pItem)
10684 return;
10686 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10687 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10688 pItem->SetBinding( true );
10690 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10692 m_items[slot] = pItem;
10693 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10694 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10695 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10696 pItem->SetSlot( slot );
10697 pItem->SetContainer( NULL );
10699 if( slot < EQUIPMENT_SLOT_END )
10700 SetVisibleItemSlot(slot,pItem);
10702 pItem->SetState(ITEM_CHANGED, this);
10705 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10707 // note: removeitem does not actually change the item
10708 // it only takes the item out of storage temporarily
10709 // note2: if removeitem is to be used for delinking
10710 // the item must be removed from the player's updatequeue
10712 Item *pItem = GetItemByPos( bag, slot );
10713 if( pItem )
10715 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10717 RemoveEnchantmentDurations(pItem);
10718 RemoveItemDurations(pItem);
10720 if( bag == INVENTORY_SLOT_BAG_0 )
10722 if ( slot < INVENTORY_SLOT_BAG_END )
10724 ItemPrototype const *pProto = pItem->GetProto();
10725 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10727 if(pProto && pProto->ItemSet)
10728 RemoveItemsSetItem(this,pProto);
10730 _ApplyItemMods(pItem, slot, false);
10732 // remove item dependent auras and casts (only weapon and armor slots)
10733 if(slot < EQUIPMENT_SLOT_END)
10734 RemoveItemDependentAurasAndCasts(pItem);
10736 // remove held enchantments
10737 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10739 if (pItem->GetItemSuffixFactor())
10741 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10742 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10744 else
10746 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10747 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10752 m_items[slot] = NULL;
10753 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10755 if ( slot < EQUIPMENT_SLOT_END )
10756 SetVisibleItemSlot(slot,NULL);
10758 else
10760 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10761 if( pBag )
10762 pBag->RemoveItem(slot, update);
10764 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10765 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10766 pItem->SetSlot( NULL_SLOT );
10767 if( IsInWorld() && update )
10768 pItem->SendUpdateToPlayer( this );
10770 if( slot == EQUIPMENT_SLOT_MAINHAND )
10771 UpdateExpertise(BASE_ATTACK);
10772 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10773 UpdateExpertise(OFF_ATTACK);
10777 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10778 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10780 if(Item* it = GetItemByPos(bag,slot))
10782 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10783 RemoveItem( bag,slot,update);
10784 it->RemoveFromUpdateQueueOf(this);
10785 if(it->IsInWorld())
10787 it->RemoveFromWorld();
10788 it->DestroyForPlayer( this );
10793 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10794 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10796 // update quest counters
10797 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10799 // store item
10800 Item* pLastItem = StoreItem( dest, pItem, update);
10802 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10803 if(pLastItem==pItem)
10805 // update owner for last item (this can be original item with wrong owner
10806 if(pLastItem->GetOwnerGUID() != GetGUID())
10807 pLastItem->SetOwnerGUID(GetGUID());
10809 // if this original item then it need create record in inventory
10810 // in case trade we already have item in other player inventory
10811 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10815 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10817 Item *pItem = GetItemByPos( bag, slot );
10818 if( pItem )
10820 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10822 // start from destroy contained items (only equipped bag can have its)
10823 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10825 for (int i = 0; i < MAX_BAG_SIZE; i++)
10826 DestroyItem(slot,i,update);
10829 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10830 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10832 RemoveEnchantmentDurations(pItem);
10833 RemoveItemDurations(pItem);
10835 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10837 if( bag == INVENTORY_SLOT_BAG_0 )
10839 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10841 // equipment and equipped bags can have applied bonuses
10842 if ( slot < INVENTORY_SLOT_BAG_END )
10844 ItemPrototype const *pProto = pItem->GetProto();
10846 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10847 if(pProto && pProto->ItemSet)
10848 RemoveItemsSetItem(this,pProto);
10850 _ApplyItemMods(pItem, slot, false);
10853 if ( slot < EQUIPMENT_SLOT_END )
10855 // remove item dependent auras and casts (only weapon and armor slots)
10856 RemoveItemDependentAurasAndCasts(pItem);
10858 // equipment visual show
10859 SetVisibleItemSlot(slot,NULL);
10862 m_items[slot] = NULL;
10864 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10865 pBag->RemoveItem(slot, update);
10867 if( IsInWorld() && update )
10869 pItem->RemoveFromWorld();
10870 pItem->DestroyForPlayer(this);
10873 //pItem->SetOwnerGUID(0);
10874 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10875 pItem->SetSlot( NULL_SLOT );
10876 pItem->SetState(ITEM_REMOVED, this);
10880 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10882 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10883 Item *pItem;
10884 ItemPrototype const *pProto;
10885 uint32 remcount = 0;
10887 // in inventory
10888 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10890 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10891 if( pItem && pItem->GetEntry() == item )
10893 if( pItem->GetCount() + remcount <= count )
10895 // all items in inventory can unequipped
10896 remcount += pItem->GetCount();
10897 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10899 if(remcount >=count)
10900 return;
10902 else
10904 pProto = pItem->GetProto();
10905 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10906 pItem->SetCount( pItem->GetCount() - count + remcount );
10907 if( IsInWorld() & update )
10908 pItem->SendUpdateToPlayer( this );
10909 pItem->SetState(ITEM_CHANGED, this);
10910 return;
10914 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10916 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10917 if( pItem && pItem->GetEntry() == item )
10919 if( pItem->GetCount() + remcount <= count )
10921 // all keys can be unequipped
10922 remcount += pItem->GetCount();
10923 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10925 if(remcount >=count)
10926 return;
10928 else
10930 pProto = pItem->GetProto();
10931 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10932 pItem->SetCount( pItem->GetCount() - count + remcount );
10933 if( IsInWorld() & update )
10934 pItem->SendUpdateToPlayer( this );
10935 pItem->SetState(ITEM_CHANGED, this);
10936 return;
10941 // in inventory bags
10942 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10944 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10946 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10948 pItem = pBag->GetItemByPos(j);
10949 if( pItem && pItem->GetEntry() == item )
10951 // all items in bags can be unequipped
10952 if( pItem->GetCount() + remcount <= count )
10954 remcount += pItem->GetCount();
10955 DestroyItem( i, j, update );
10957 if(remcount >=count)
10958 return;
10960 else
10962 pProto = pItem->GetProto();
10963 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10964 pItem->SetCount( pItem->GetCount() - count + remcount );
10965 if( IsInWorld() && update )
10966 pItem->SendUpdateToPlayer( this );
10967 pItem->SetState(ITEM_CHANGED, this);
10968 return;
10975 // in equipment and bag list
10976 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10978 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10979 if( pItem && pItem->GetEntry() == item )
10981 if( pItem->GetCount() + remcount <= count )
10983 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10985 remcount += pItem->GetCount();
10986 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10988 if(remcount >=count)
10989 return;
10992 else
10994 pProto = pItem->GetProto();
10995 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10996 pItem->SetCount( pItem->GetCount() - count + remcount );
10997 if( IsInWorld() & update )
10998 pItem->SendUpdateToPlayer( this );
10999 pItem->SetState(ITEM_CHANGED, this);
11000 return;
11006 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
11008 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
11010 // in inventory
11011 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11013 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11014 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11015 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11017 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
11019 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11020 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11021 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11024 // in inventory bags
11025 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11027 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11028 if( pBag )
11030 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11032 Item* pItem = pBag->GetItemByPos(j);
11033 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11034 DestroyItem( i, j, update);
11039 // in equipment and bag list
11040 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
11042 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11043 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11044 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11048 void Player::DestroyConjuredItems( bool update )
11050 // used when entering arena
11051 // destroys all conjured items
11052 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
11054 // in inventory
11055 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11057 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11058 if( pItem && pItem->GetProto() &&
11059 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11060 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11061 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11064 // in inventory bags
11065 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11067 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11068 if( pBag )
11070 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11072 Item* pItem = pBag->GetItemByPos(j);
11073 if( pItem && pItem->GetProto() &&
11074 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11075 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11076 DestroyItem( i, j, update);
11081 // in equipment and bag list
11082 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
11084 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11085 if( pItem && pItem->GetProto() &&
11086 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11087 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11088 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11092 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
11094 if(!pItem)
11095 return;
11097 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
11099 if( pItem->GetCount() <= count )
11101 count-= pItem->GetCount();
11103 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
11105 else
11107 ItemRemovedQuestCheck( pItem->GetEntry(), count);
11108 pItem->SetCount( pItem->GetCount() - count );
11109 count = 0;
11110 if( IsInWorld() & update )
11111 pItem->SendUpdateToPlayer( this );
11112 pItem->SetState(ITEM_CHANGED, this);
11116 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
11118 uint8 srcbag = src >> 8;
11119 uint8 srcslot = src & 255;
11121 uint8 dstbag = dst >> 8;
11122 uint8 dstslot = dst & 255;
11124 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11125 if( !pSrcItem )
11127 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11128 return;
11131 // not let split all items (can be only at cheating)
11132 if(pSrcItem->GetCount() == count)
11134 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11135 return;
11138 // not let split more existed items (can be only at cheating)
11139 if(pSrcItem->GetCount() < count)
11141 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
11142 return;
11145 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11147 //best error message found for attempting to split while looting
11148 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11149 return;
11152 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11153 Item *pNewItem = pSrcItem->CloneItem( count, this );
11154 if( !pNewItem )
11156 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11157 return;
11160 if( IsInventoryPos( dst ) )
11162 // change item amount before check (for unique max count check)
11163 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11165 ItemPosCountVec dest;
11166 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11167 if( msg != EQUIP_ERR_OK )
11169 delete pNewItem;
11170 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11171 SendEquipError( msg, pSrcItem, NULL );
11172 return;
11175 if( IsInWorld() )
11176 pSrcItem->SendUpdateToPlayer( this );
11177 pSrcItem->SetState(ITEM_CHANGED, this);
11178 StoreItem( dest, pNewItem, true);
11180 else if( IsBankPos ( dst ) )
11182 // change item amount before check (for unique max count check)
11183 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11185 ItemPosCountVec dest;
11186 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11187 if( msg != EQUIP_ERR_OK )
11189 delete pNewItem;
11190 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11191 SendEquipError( msg, pSrcItem, NULL );
11192 return;
11195 if( IsInWorld() )
11196 pSrcItem->SendUpdateToPlayer( this );
11197 pSrcItem->SetState(ITEM_CHANGED, this);
11198 BankItem( dest, pNewItem, true);
11200 else if( IsEquipmentPos ( dst ) )
11202 // change item amount before check (for unique max count check), provide space for splitted items
11203 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11205 uint16 dest;
11206 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11207 if( msg != EQUIP_ERR_OK )
11209 delete pNewItem;
11210 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11211 SendEquipError( msg, pSrcItem, NULL );
11212 return;
11215 if( IsInWorld() )
11216 pSrcItem->SendUpdateToPlayer( this );
11217 pSrcItem->SetState(ITEM_CHANGED, this);
11218 EquipItem( dest, pNewItem, true);
11219 AutoUnequipOffhandIfNeed();
11223 void Player::SwapItem( uint16 src, uint16 dst )
11225 uint8 srcbag = src >> 8;
11226 uint8 srcslot = src & 255;
11228 uint8 dstbag = dst >> 8;
11229 uint8 dstslot = dst & 255;
11231 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11232 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11234 if( !pSrcItem )
11235 return;
11237 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11239 if(!isAlive() )
11241 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11242 return;
11245 // SRC checks
11247 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11249 //best error message found for attempting to swap while looting
11250 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11251 return;
11254 // check unequip potability for equipped items and bank bags
11255 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11257 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11258 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
11259 if(msg != EQUIP_ERR_OK)
11261 SendEquipError( msg, pSrcItem, pDstItem );
11262 return;
11266 // prevent put equipped/bank bag in self
11267 if( IsBagPos ( src ) && srcslot == dstbag)
11269 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11270 return;
11273 // DST checks
11275 if (pDstItem)
11277 if(pDstItem->m_lootGenerated) // prevent swap looting item
11279 //best error message found for attempting to swap while looting
11280 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11281 return;
11284 // check unequip potability for equipped items and bank bags
11285 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11287 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11288 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
11289 if(msg != EQUIP_ERR_OK)
11291 SendEquipError( msg, pSrcItem, pDstItem );
11292 return;
11297 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11298 // or swap empty bag with another empty or not empty bag (with items exchange)
11300 // Move case
11301 if( !pDstItem )
11303 if( IsInventoryPos( dst ) )
11305 ItemPosCountVec dest;
11306 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11307 if( msg != EQUIP_ERR_OK )
11309 SendEquipError( msg, pSrcItem, NULL );
11310 return;
11313 RemoveItem(srcbag, srcslot, true);
11314 StoreItem( dest, pSrcItem, true);
11316 else if( IsBankPos ( dst ) )
11318 ItemPosCountVec dest;
11319 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11320 if( msg != EQUIP_ERR_OK )
11322 SendEquipError( msg, pSrcItem, NULL );
11323 return;
11326 RemoveItem(srcbag, srcslot, true);
11327 BankItem( dest, pSrcItem, true);
11329 else if( IsEquipmentPos ( dst ) )
11331 uint16 dest;
11332 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11333 if( msg != EQUIP_ERR_OK )
11335 SendEquipError( msg, pSrcItem, NULL );
11336 return;
11339 RemoveItem(srcbag, srcslot, true);
11340 EquipItem( dest, pSrcItem, true);
11341 AutoUnequipOffhandIfNeed();
11344 return;
11347 // attempt merge to / fill target item
11348 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11350 uint8 msg;
11351 ItemPosCountVec sDest;
11352 uint16 eDest;
11353 if( IsInventoryPos( dst ) )
11354 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11355 else if( IsBankPos ( dst ) )
11356 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11357 else if( IsEquipmentPos ( dst ) )
11358 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11359 else
11360 return;
11362 // can be merge/fill
11363 if(msg == EQUIP_ERR_OK)
11365 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11367 RemoveItem(srcbag, srcslot, true);
11369 if( IsInventoryPos( dst ) )
11370 StoreItem( sDest, pSrcItem, true);
11371 else if( IsBankPos ( dst ) )
11372 BankItem( sDest, pSrcItem, true);
11373 else if( IsEquipmentPos ( dst ) )
11375 EquipItem( eDest, pSrcItem, true);
11376 AutoUnequipOffhandIfNeed();
11379 else
11381 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11382 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11383 pSrcItem->SetState(ITEM_CHANGED, this);
11384 pDstItem->SetState(ITEM_CHANGED, this);
11385 if( IsInWorld() )
11387 pSrcItem->SendUpdateToPlayer( this );
11388 pDstItem->SendUpdateToPlayer( this );
11391 return;
11395 // impossible merge/fill, do real swap
11396 uint8 msg;
11398 // check src->dest move possibility
11399 ItemPosCountVec sDest;
11400 uint16 eDest;
11401 if( IsInventoryPos( dst ) )
11402 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11403 else if( IsBankPos( dst ) )
11404 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11405 else if( IsEquipmentPos( dst ) )
11407 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11408 if( msg == EQUIP_ERR_OK )
11409 msg = CanUnequipItem( eDest, true );
11412 if( msg != EQUIP_ERR_OK )
11414 SendEquipError( msg, pSrcItem, pDstItem );
11415 return;
11418 // check dest->src move possibility
11419 ItemPosCountVec sDest2;
11420 uint16 eDest2;
11421 if( IsInventoryPos( src ) )
11422 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11423 else if( IsBankPos( src ) )
11424 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11425 else if( IsEquipmentPos( src ) )
11427 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11428 if( msg == EQUIP_ERR_OK )
11429 msg = CanUnequipItem( eDest2, true);
11432 if( msg != EQUIP_ERR_OK )
11434 SendEquipError( msg, pDstItem, pSrcItem );
11435 return;
11438 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11439 if(pSrcItem->IsBag() && pDstItem->IsBag())
11441 Bag* emptyBag = NULL;
11442 Bag* fullBag = NULL;
11443 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11445 emptyBag = (Bag*)pSrcItem;
11446 fullBag = (Bag*)pDstItem;
11448 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11450 emptyBag = (Bag*)pDstItem;
11451 fullBag = (Bag*)pSrcItem;
11454 // bag swap (with items exchange) case
11455 if(emptyBag && fullBag)
11457 ItemPrototype const* emotyProto = emptyBag->GetProto();
11459 uint32 count = 0;
11461 for(int i=0; i < fullBag->GetBagSize(); ++i)
11463 Item *bagItem = fullBag->GetItemByPos(i);
11464 if (!bagItem)
11465 continue;
11467 ItemPrototype const* bagItemProto = bagItem->GetProto();
11468 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11470 // one from items not go to empry target bag
11471 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11472 return;
11475 ++count;
11479 if (count > emptyBag->GetBagSize())
11481 // too small targeted bag
11482 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11483 return;
11486 // Items swap
11487 count = 0; // will pos in new bag
11488 for(int i=0; i< fullBag->GetBagSize(); ++i)
11490 Item *bagItem = fullBag->GetItemByPos(i);
11491 if (!bagItem)
11492 continue;
11494 fullBag->RemoveItem(i, true);
11495 emptyBag->StoreItem(count, bagItem, true);
11496 bagItem->SetState(ITEM_CHANGED, this);
11498 ++count;
11503 // now do moves, remove...
11504 RemoveItem(dstbag, dstslot, false);
11505 RemoveItem(srcbag, srcslot, false);
11507 // add to dest
11508 if( IsInventoryPos( dst ) )
11509 StoreItem(sDest, pSrcItem, true);
11510 else if( IsBankPos( dst ) )
11511 BankItem(sDest, pSrcItem, true);
11512 else if( IsEquipmentPos( dst ) )
11513 EquipItem(eDest, pSrcItem, true);
11515 // add to src
11516 if( IsInventoryPos( src ) )
11517 StoreItem(sDest2, pDstItem, true);
11518 else if( IsBankPos( src ) )
11519 BankItem(sDest2, pDstItem, true);
11520 else if( IsEquipmentPos( src ) )
11521 EquipItem(eDest2, pDstItem, true);
11523 AutoUnequipOffhandIfNeed();
11526 void Player::AddItemToBuyBackSlot( Item *pItem )
11528 if( pItem )
11530 uint32 slot = m_currentBuybackSlot;
11531 // if current back slot non-empty search oldest or free
11532 if(m_items[slot])
11534 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11535 uint32 oldest_slot = BUYBACK_SLOT_START;
11537 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11539 // found empty
11540 if(!m_items[i])
11542 slot = i;
11543 break;
11546 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11548 if(oldest_time > i_time)
11550 oldest_time = i_time;
11551 oldest_slot = i;
11555 // find oldest
11556 slot = oldest_slot;
11559 RemoveItemFromBuyBackSlot( slot, true );
11560 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11562 m_items[slot] = pItem;
11563 time_t base = time(NULL);
11564 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11565 uint32 eslot = slot - BUYBACK_SLOT_START;
11567 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11568 ItemPrototype const *pProto = pItem->GetProto();
11569 if( pProto )
11570 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11571 else
11572 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11573 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11575 // move to next (for non filled list is move most optimized choice)
11576 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11577 ++m_currentBuybackSlot;
11581 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11583 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11584 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11585 return m_items[slot];
11586 return NULL;
11589 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11591 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11592 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11594 Item *pItem = m_items[slot];
11595 if( pItem )
11597 pItem->RemoveFromWorld();
11598 if(del) pItem->SetState(ITEM_REMOVED, this);
11601 m_items[slot] = NULL;
11603 uint32 eslot = slot - BUYBACK_SLOT_START;
11604 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11605 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11606 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11608 // if current backslot is filled set to now free slot
11609 if(m_items[m_currentBuybackSlot])
11610 m_currentBuybackSlot = slot;
11614 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11616 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11617 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11618 data << uint8(msg);
11620 if(msg)
11622 data << uint64(pItem ? pItem->GetGUID() : 0);
11623 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11624 data << uint8(0); // not 0 there...
11626 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11628 uint32 level = 0;
11630 if(pItem)
11631 if(ItemPrototype const* proto = pItem->GetProto())
11632 level = proto->RequiredLevel;
11634 data << uint32(level); // new 2.4.0
11637 GetSession()->SendPacket(&data);
11640 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11642 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11643 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11644 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11645 data << uint32(item);
11646 if( param > 0 )
11647 data << uint32(param);
11648 data << uint8(msg);
11649 GetSession()->SendPacket(&data);
11652 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11654 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11655 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11656 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11657 data << uint64(guid);
11658 if( param > 0 )
11659 data << uint32(param);
11660 data << uint8(msg);
11661 GetSession()->SendPacket(&data);
11664 void Player::ClearTrade()
11666 tradeGold = 0;
11667 acceptTrade = false;
11668 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11669 tradeItems[i] = NULL_SLOT;
11672 void Player::TradeCancel(bool sendback)
11674 if(pTrader)
11676 // send yellow "Trade canceled" message to both traders
11677 WorldSession* ws;
11678 ws = GetSession();
11679 if(sendback)
11680 ws->SendCancelTrade();
11681 ws = pTrader->GetSession();
11682 if(!ws->PlayerLogout())
11683 ws->SendCancelTrade();
11685 // cleanup
11686 ClearTrade();
11687 pTrader->ClearTrade();
11688 // prevent loss of reference
11689 pTrader->pTrader = NULL;
11690 pTrader = NULL;
11694 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11696 if(m_itemDuration.empty())
11697 return;
11699 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11701 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11703 Item* item = *itr;
11704 ++itr; // current element can be erased in UpdateDuration
11706 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11707 item->UpdateDuration(this,time);
11711 void Player::UpdateEnchantTime(uint32 time)
11713 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11715 assert(itr->item);
11716 next=itr;
11717 if(!itr->item->GetEnchantmentId(itr->slot))
11719 next = m_enchantDuration.erase(itr);
11721 else if(itr->leftduration <= time)
11723 ApplyEnchantment(itr->item,itr->slot,false,false);
11724 itr->item->ClearEnchantment(itr->slot);
11725 next = m_enchantDuration.erase(itr);
11727 else if(itr->leftduration > time)
11729 itr->leftduration -= time;
11730 ++next;
11735 void Player::AddEnchantmentDurations(Item *item)
11737 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11739 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11740 continue;
11742 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11743 if( duration > 0 )
11744 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11748 void Player::RemoveEnchantmentDurations(Item *item)
11750 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11752 if(itr->item == item)
11754 // save duration in item
11755 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11756 itr = m_enchantDuration.erase(itr);
11758 else
11759 ++itr;
11763 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11765 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11766 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11768 next = itr;
11769 if(itr->slot==slot)
11771 if(itr->item && itr->item->GetEnchantmentId(slot))
11773 // remove from stats
11774 ApplyEnchantment(itr->item,slot,false,false);
11775 // remove visual
11776 itr->item->ClearEnchantment(slot);
11778 // remove from update list
11779 next = m_enchantDuration.erase(itr);
11781 else
11782 ++next;
11785 // remove enchants from inventory items
11786 // NOTE: no need to remove these from stats, since these aren't equipped
11787 // in inventory
11788 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11790 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11791 if( pItem && pItem->GetEnchantmentId(slot) )
11792 pItem->ClearEnchantment(slot);
11795 // in inventory bags
11796 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11798 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11799 if( pBag )
11801 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11803 Item* pItem = pBag->GetItemByPos(j);
11804 if( pItem && pItem->GetEnchantmentId(slot) )
11805 pItem->ClearEnchantment(slot);
11811 // duration == 0 will remove item enchant
11812 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11814 if(!item)
11815 return;
11817 if(slot >= MAX_ENCHANTMENT_SLOT)
11818 return;
11820 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11822 if(itr->item == item && itr->slot == slot)
11824 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11825 m_enchantDuration.erase(itr);
11826 break;
11829 if(item && duration > 0 )
11831 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11832 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11836 void Player::ApplyEnchantment(Item *item,bool apply)
11838 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11839 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11842 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11844 if(!item)
11845 return;
11847 if(!item->IsEquipped())
11848 return;
11850 if(slot >= MAX_ENCHANTMENT_SLOT)
11851 return;
11853 uint32 enchant_id = item->GetEnchantmentId(slot);
11854 if(!enchant_id)
11855 return;
11857 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11858 if(!pEnchant)
11859 return;
11861 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11862 return;
11864 for (int s=0; s<3; s++)
11866 uint32 enchant_display_type = pEnchant->type[s];
11867 uint32 enchant_amount = pEnchant->amount[s];
11868 uint32 enchant_spell_id = pEnchant->spellid[s];
11870 switch(enchant_display_type)
11872 case ITEM_ENCHANTMENT_TYPE_NONE:
11873 break;
11874 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11875 // processed in Player::CastItemCombatSpell
11876 break;
11877 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11878 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11879 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11880 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11881 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11882 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11883 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11884 break;
11885 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11886 if(enchant_spell_id)
11888 if(apply)
11890 int32 basepoints = 0;
11891 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11892 if (item->GetItemRandomPropertyId())
11894 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11895 if (item_rand)
11897 // Search enchant_amount
11898 for (int k=0; k<3; k++)
11900 if(item_rand->enchant_id[k] == enchant_id)
11902 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11903 break;
11908 // Cast custom spell vs all equal basepoints getted from enchant_amount
11909 if (basepoints)
11910 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11911 else
11912 CastSpell(this,enchant_spell_id,true,item);
11914 else
11915 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11917 break;
11918 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11919 if (!enchant_amount)
11921 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11922 if(item_rand)
11924 for (int k=0; k<3; k++)
11926 if(item_rand->enchant_id[k] == enchant_id)
11928 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11929 break;
11935 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11936 break;
11937 case ITEM_ENCHANTMENT_TYPE_STAT:
11939 if (!enchant_amount)
11941 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11942 if(item_rand_suffix)
11944 for (int k=0; k<3; k++)
11946 if(item_rand_suffix->enchant_id[k] == enchant_id)
11948 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11949 break;
11955 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11956 switch (enchant_spell_id)
11958 case ITEM_MOD_AGILITY:
11959 sLog.outDebug("+ %u AGILITY",enchant_amount);
11960 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11961 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11962 break;
11963 case ITEM_MOD_STRENGTH:
11964 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11965 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11966 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11967 break;
11968 case ITEM_MOD_INTELLECT:
11969 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11970 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11971 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11972 break;
11973 case ITEM_MOD_SPIRIT:
11974 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11975 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11976 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11977 break;
11978 case ITEM_MOD_STAMINA:
11979 sLog.outDebug("+ %u STAMINA",enchant_amount);
11980 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11981 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11982 break;
11983 case ITEM_MOD_DEFENSE_SKILL_RATING:
11984 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11985 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11986 break;
11987 case ITEM_MOD_DODGE_RATING:
11988 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11989 sLog.outDebug("+ %u DODGE", enchant_amount);
11990 break;
11991 case ITEM_MOD_PARRY_RATING:
11992 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11993 sLog.outDebug("+ %u PARRY", enchant_amount);
11994 break;
11995 case ITEM_MOD_BLOCK_RATING:
11996 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11997 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11998 break;
11999 case ITEM_MOD_HIT_MELEE_RATING:
12000 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12001 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
12002 break;
12003 case ITEM_MOD_HIT_RANGED_RATING:
12004 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12005 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
12006 break;
12007 case ITEM_MOD_HIT_SPELL_RATING:
12008 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12009 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
12010 break;
12011 case ITEM_MOD_CRIT_MELEE_RATING:
12012 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12013 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
12014 break;
12015 case ITEM_MOD_CRIT_RANGED_RATING:
12016 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12017 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
12018 break;
12019 case ITEM_MOD_CRIT_SPELL_RATING:
12020 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12021 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
12022 break;
12023 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12024 // in Enchantments
12025 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12026 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12027 // break;
12028 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12029 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12030 // break;
12031 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12032 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12033 // break;
12034 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12035 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12036 // break;
12037 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12038 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12039 // break;
12040 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12041 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12042 // break;
12043 // case ITEM_MOD_HASTE_MELEE_RATING:
12044 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12045 // break;
12046 // case ITEM_MOD_HASTE_RANGED_RATING:
12047 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12048 // break;
12049 case ITEM_MOD_HASTE_SPELL_RATING:
12050 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12051 break;
12052 case ITEM_MOD_HIT_RATING:
12053 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12054 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12055 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12056 sLog.outDebug("+ %u HIT", enchant_amount);
12057 break;
12058 case ITEM_MOD_CRIT_RATING:
12059 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12060 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12061 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12062 sLog.outDebug("+ %u CRITICAL", enchant_amount);
12063 break;
12064 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12065 // case ITEM_MOD_HIT_TAKEN_RATING:
12066 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12067 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12068 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12069 // break;
12070 // case ITEM_MOD_CRIT_TAKEN_RATING:
12071 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12072 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12073 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12074 // break;
12075 case ITEM_MOD_RESILIENCE_RATING:
12076 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12077 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12078 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12079 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
12080 break;
12081 case ITEM_MOD_HASTE_RATING:
12082 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12083 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12084 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12085 sLog.outDebug("+ %u HASTE", enchant_amount);
12086 break;
12087 case ITEM_MOD_EXPERTISE_RATING:
12088 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
12089 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
12090 break;
12091 case ITEM_MOD_ATTACK_POWER:
12092 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
12093 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12094 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
12095 break;
12096 case ITEM_MOD_RANGED_ATTACK_POWER:
12097 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12098 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
12099 break;
12100 case ITEM_MOD_FERAL_ATTACK_POWER:
12101 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
12102 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
12103 break;
12104 case ITEM_MOD_SPELL_HEALING_DONE:
12105 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
12106 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
12107 break;
12108 case ITEM_MOD_SPELL_DAMAGE_DONE:
12109 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
12110 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
12111 break;
12112 case ITEM_MOD_MANA_REGENERATION:
12113 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
12114 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
12115 break;
12116 case ITEM_MOD_ARMOR_PENETRATION_RATING:
12117 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
12118 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
12119 break;
12120 case ITEM_MOD_SPELL_POWER:
12121 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
12122 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
12123 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
12124 break;
12125 default:
12126 break;
12128 break;
12130 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
12132 if(getClass() == CLASS_SHAMAN)
12134 float addValue = 0.0f;
12135 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12137 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
12138 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
12140 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
12142 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
12143 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
12146 break;
12148 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
12149 // processed in Player::CastItemUseSpell
12150 break;
12151 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
12152 // nothing do..
12153 break;
12154 default:
12155 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
12156 break;
12157 } /*switch(enchant_display_type)*/
12158 } /*for*/
12160 // visualize enchantment at player and equipped items
12161 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
12163 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
12164 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
12167 if(apply_dur)
12169 if(apply)
12171 // set duration
12172 uint32 duration = item->GetEnchantmentDuration(slot);
12173 if(duration > 0)
12174 AddEnchantmentDuration(item,slot,duration);
12176 else
12178 // duration == 0 will remove EnchantDuration
12179 AddEnchantmentDuration(item,slot,0);
12184 void Player::SendEnchantmentDurations()
12186 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
12188 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
12192 void Player::SendItemDurations()
12194 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
12196 (*itr)->SendTimeUpdate(this);
12200 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12202 if(!item) // prevent crash
12203 return;
12205 // last check 2.0.10
12206 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12207 data << GetGUID(); // player GUID
12208 data << uint32(received); // 0=looted, 1=from npc
12209 data << uint32(created); // 0=received, 1=created
12210 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12211 data << (uint8)item->GetBagSlot(); // bagslot
12212 // item slot, but when added to stack: 0xFFFFFFFF
12213 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
12214 data << uint32(item->GetEntry()); // item id
12215 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12216 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12217 data << uint32(count); // count of items
12218 data << GetItemCount(item->GetEntry()); // count of items in inventory
12220 if (broadcast && GetGroup())
12221 GetGroup()->BroadcastPacket(&data);
12222 else
12223 GetSession()->SendPacket(&data);
12226 /*********************************************************/
12227 /*** QUEST SYSTEM ***/
12228 /*********************************************************/
12230 void Player::PrepareQuestMenu( uint64 guid )
12232 Object *pObject;
12233 QuestRelations* pObjectQR;
12234 QuestRelations* pObjectQIR;
12235 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12236 if( pCreature )
12238 pObject = (Object*)pCreature;
12239 pObjectQR = &objmgr.mCreatureQuestRelations;
12240 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12242 else
12244 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12245 if( pGameObject )
12247 pObject = (Object*)pGameObject;
12248 pObjectQR = &objmgr.mGOQuestRelations;
12249 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12251 else
12252 return;
12255 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12256 qm.ClearMenu();
12258 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12260 uint32 quest_id = i->second;
12261 QuestStatus status = GetQuestStatus( quest_id );
12262 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12263 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
12264 else if ( status == QUEST_STATUS_INCOMPLETE )
12265 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
12266 else if (status == QUEST_STATUS_AVAILABLE )
12267 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12270 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12272 uint32 quest_id = i->second;
12273 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12274 if(!pQuest) continue;
12276 QuestStatus status = GetQuestStatus( quest_id );
12278 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12279 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
12280 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12281 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
12285 void Player::SendPreparedQuest( uint64 guid )
12287 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12288 if( questMenu.Empty() )
12289 return;
12291 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
12293 uint32 status = qmi0.m_qIcon;
12295 // single element case
12296 if ( questMenu.MenuItemCount() == 1 )
12298 // Auto open -- maybe also should verify there is no greeting
12299 uint32 quest_id = qmi0.m_qId;
12300 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12301 if ( pQuest )
12303 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
12304 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
12305 else if( status == DIALOG_STATUS_INCOMPLETE )
12306 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
12307 // Send completable on repeatable quest if player don't have quest
12308 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
12309 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
12310 else
12311 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
12314 // multiply entries
12315 else
12317 QEmote qe;
12318 qe._Delay = 0;
12319 qe._Emote = 0;
12320 std::string title = "";
12321 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12322 if( pCreature )
12324 uint32 textid = pCreature->GetNpcTextId();
12325 GossipText const* gossiptext = objmgr.GetGossipText(textid);
12326 if( !gossiptext )
12328 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12329 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12330 title = "";
12332 else
12334 qe = gossiptext->Options[0].Emotes[0];
12336 if(!gossiptext->Options[0].Text_0.empty())
12338 title = gossiptext->Options[0].Text_0;
12340 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12341 if (loc_idx >= 0)
12343 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12344 if (nl)
12346 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12347 title = nl->Text_0[0][loc_idx];
12351 else
12353 title = gossiptext->Options[0].Text_1;
12355 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12356 if (loc_idx >= 0)
12358 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12359 if (nl)
12361 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12362 title = nl->Text_1[0][loc_idx];
12368 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12372 bool Player::IsActiveQuest( uint32 quest_id ) const
12374 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12376 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12379 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12381 Object *pObject;
12382 QuestRelations* pObjectQR;
12383 QuestRelations* pObjectQIR;
12385 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12386 if( pCreature )
12388 pObject = (Object*)pCreature;
12389 pObjectQR = &objmgr.mCreatureQuestRelations;
12390 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12392 else
12394 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12395 if( pGameObject )
12397 pObject = (Object*)pGameObject;
12398 pObjectQR = &objmgr.mGOQuestRelations;
12399 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12401 else
12402 return NULL;
12405 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12406 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12408 if (itr->second == nextQuestID)
12409 return objmgr.GetQuestTemplate(nextQuestID);
12412 return NULL;
12415 bool Player::CanSeeStartQuest( Quest const *pQuest )
12417 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12418 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12419 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12420 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12422 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12425 return false;
12428 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12430 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12431 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12432 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12433 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12434 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12435 && SatisfyQuestDay( pQuest, msg );
12438 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12440 if( !SatisfyQuestLog( msg ) )
12441 return false;
12443 uint32 srcitem = pQuest->GetSrcItemId();
12444 if( srcitem > 0 )
12446 uint32 count = pQuest->GetSrcItemCount();
12447 ItemPosCountVec dest;
12448 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12450 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12451 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12452 return true;
12453 else if( msg != EQUIP_ERR_OK )
12455 SendEquipError( msg, NULL, NULL );
12456 return false;
12459 return true;
12462 bool Player::CanCompleteQuest( uint32 quest_id )
12464 if( quest_id )
12466 QuestStatusData& q_status = mQuestStatus[quest_id];
12467 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12468 return false; // not allow re-complete quest
12470 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12472 if(!qInfo)
12473 return false;
12475 // auto complete quest
12476 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12477 return true;
12479 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12482 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12484 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12486 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12487 return false;
12491 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12493 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12495 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12496 continue;
12498 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12499 return false;
12503 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12504 return false;
12506 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12507 return false;
12509 if ( qInfo->GetRewOrReqMoney() < 0 )
12511 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12512 return false;
12515 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12516 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12517 return false;
12519 return true;
12522 return false;
12525 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12527 // Solve problem that player don't have the quest and try complete it.
12528 // if repeatable she must be able to complete event if player don't have it.
12529 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12530 if( !CanTakeQuest(pQuest, false) )
12531 return false;
12533 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12534 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12535 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12536 return false;
12538 if( !CanRewardQuest(pQuest, false) )
12539 return false;
12541 return true;
12544 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12546 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12547 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12548 return false;
12550 // daily quest can't be rewarded (25 daily quest already completed)
12551 if(!SatisfyQuestDay(pQuest,true))
12552 return false;
12554 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12555 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12556 return false;
12558 // prevent receive reward with quest items in bank
12559 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12561 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12563 if( pQuest->ReqItemCount[i]!= 0 &&
12564 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12566 if(msg)
12567 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12568 return false;
12573 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12574 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12575 return false;
12577 return true;
12580 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12582 // prevent receive reward with quest items in bank or for not completed quest
12583 if(!CanRewardQuest(pQuest,msg))
12584 return false;
12586 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12588 if( pQuest->RewChoiceItemId[reward] )
12590 ItemPosCountVec dest;
12591 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12592 if( res != EQUIP_ERR_OK )
12594 SendEquipError( res, NULL, NULL );
12595 return false;
12600 if ( pQuest->GetRewItemsCount() > 0 )
12602 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12604 if( pQuest->RewItemId[i] )
12606 ItemPosCountVec dest;
12607 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12608 if( res != EQUIP_ERR_OK )
12610 SendEquipError( res, NULL, NULL );
12611 return false;
12617 return true;
12620 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12622 uint16 log_slot = FindQuestSlot( 0 );
12623 assert(log_slot < MAX_QUEST_LOG_SIZE);
12625 uint32 quest_id = pQuest->GetQuestId();
12627 // if not exist then created with set uState==NEW and rewarded=false
12628 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12630 // check for repeatable quests status reset
12631 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12632 questStatusData.m_explored = false;
12634 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12636 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12637 questStatusData.m_itemcount[i] = 0;
12640 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12642 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12643 questStatusData.m_creatureOrGOcount[i] = 0;
12646 GiveQuestSourceItem( pQuest );
12647 AdjustQuestReqItemCount( pQuest, questStatusData );
12649 if( pQuest->GetRepObjectiveFaction() )
12650 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
12652 uint32 qtime = 0;
12653 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12655 uint32 limittime = pQuest->GetLimitTime();
12657 // shared timed quest
12658 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12659 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12661 AddTimedQuest( quest_id );
12662 questStatusData.m_timer = limittime * IN_MILISECONDS;
12663 qtime = static_cast<uint32>(time(NULL)) + limittime;
12665 else
12666 questStatusData.m_timer = 0;
12668 SetQuestSlot(log_slot, quest_id, qtime);
12670 if (questStatusData.uState != QUEST_NEW)
12671 questStatusData.uState = QUEST_CHANGED;
12673 //starting initial quest script
12674 if(questGiver && pQuest->GetQuestStartScript()!=0)
12675 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12677 // Some spells applied at quest activation
12678 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12679 if(saBounds.first != saBounds.second)
12681 uint32 zone = GetZoneId();
12682 uint32 area = GetAreaId();
12684 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12685 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12686 if( !HasAura(itr->second->spellId,0) )
12687 CastSpell(this,itr->second->spellId,true);
12690 UpdateForQuestsGO();
12693 void Player::CompleteQuest( uint32 quest_id )
12695 if( quest_id )
12697 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12699 uint16 log_slot = FindQuestSlot( quest_id );
12700 if( log_slot < MAX_QUEST_LOG_SIZE)
12701 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12703 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12705 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12706 RewardQuest(qInfo,0,this,false);
12707 else
12708 SendQuestComplete( quest_id );
12713 void Player::IncompleteQuest( uint32 quest_id )
12715 if( quest_id )
12717 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12719 uint16 log_slot = FindQuestSlot( quest_id );
12720 if( log_slot < MAX_QUEST_LOG_SIZE)
12721 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12725 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12727 uint32 quest_id = pQuest->GetQuestId();
12729 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12731 if ( pQuest->ReqItemId[i] )
12732 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12735 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12736 // SetTimedQuest( 0 );
12737 m_timedquests.erase(pQuest->GetQuestId());
12739 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12741 if( pQuest->RewChoiceItemId[reward] )
12743 ItemPosCountVec dest;
12744 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12746 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12747 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12752 if ( pQuest->GetRewItemsCount() > 0 )
12754 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12756 if( pQuest->RewItemId[i] )
12758 ItemPosCountVec dest;
12759 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12761 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12762 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12768 RewardReputation( pQuest );
12770 if( pQuest->GetRewSpellCast() > 0 )
12771 CastSpell( this, pQuest->GetRewSpellCast(), true);
12772 else if( pQuest->GetRewSpell() > 0)
12773 CastSpell( this, pQuest->GetRewSpell(), true);
12775 uint16 log_slot = FindQuestSlot( quest_id );
12776 if( log_slot < MAX_QUEST_LOG_SIZE)
12777 SetQuestSlot(log_slot,0);
12779 QuestStatusData& q_status = mQuestStatus[quest_id];
12781 // Not give XP in case already completed once repeatable quest
12782 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12784 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12785 GiveXP( XP , NULL );
12786 else
12787 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12789 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12790 ModifyMoney( pQuest->GetRewOrReqMoney() );
12792 // honor reward
12793 if(pQuest->GetRewHonorableKills())
12794 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12796 // title reward
12797 if(pQuest->GetCharTitleId())
12799 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12800 SetTitle(titleEntry);
12803 if(pQuest->GetBonusTalents())
12805 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12806 InitTalentForLevel();
12809 // Send reward mail
12810 if(pQuest->GetRewMailTemplateId())
12812 MailMessageType mailType;
12813 uint32 senderGuidOrEntry;
12814 switch(questGiver->GetTypeId())
12816 case TYPEID_UNIT:
12817 mailType = MAIL_CREATURE;
12818 senderGuidOrEntry = questGiver->GetEntry();
12819 break;
12820 case TYPEID_GAMEOBJECT:
12821 mailType = MAIL_GAMEOBJECT;
12822 senderGuidOrEntry = questGiver->GetEntry();
12823 break;
12824 case TYPEID_ITEM:
12825 mailType = MAIL_ITEM;
12826 senderGuidOrEntry = questGiver->GetEntry();
12827 break;
12828 case TYPEID_PLAYER:
12829 mailType = MAIL_NORMAL;
12830 senderGuidOrEntry = questGiver->GetGUIDLow();
12831 break;
12832 default:
12833 mailType = MAIL_NORMAL;
12834 senderGuidOrEntry = GetGUIDLow();
12835 break;
12838 Loot questMailLoot;
12840 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12842 // fill mail
12843 MailItemsInfo mi; // item list preparing
12845 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12846 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12848 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12850 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12852 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12853 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12858 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12861 if(pQuest->IsDaily())
12863 SetDailyQuestStatus(quest_id);
12864 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12867 if ( !pQuest->IsRepeatable() )
12868 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12869 else
12870 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12872 q_status.m_rewarded = true;
12874 if(announce)
12875 SendQuestReward( pQuest, XP, questGiver );
12877 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12878 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12879 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST);
12881 uint32 zone = 0;
12882 uint32 area = 0;
12884 // remove auras from spells with quest reward state limitations
12885 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12886 if(saEndBounds.first != saEndBounds.second)
12888 uint32 zone = GetZoneId();
12889 uint32 area = GetAreaId();
12891 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12892 if(!itr->second->IsFitToRequirements(this,zone,area))
12893 RemoveAurasDueToSpell(itr->second->spellId);
12896 // Some spells applied at quest reward
12897 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12898 if(saBounds.first != saBounds.second)
12900 if(!zone) zone = GetZoneId();
12901 if(!area) area = GetAreaId();
12903 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12904 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12905 if( !HasAura(itr->second->spellId,0) )
12906 CastSpell(this,itr->second->spellId,true);
12910 void Player::FailQuest( uint32 quest_id )
12912 if( quest_id )
12914 IncompleteQuest( quest_id );
12916 uint16 log_slot = FindQuestSlot( quest_id );
12917 if( log_slot < MAX_QUEST_LOG_SIZE)
12919 SetQuestSlotTimer(log_slot, 1 );
12920 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12922 SendQuestFailed( quest_id );
12926 void Player::FailTimedQuest( uint32 quest_id )
12928 if( quest_id )
12930 QuestStatusData& q_status = mQuestStatus[quest_id];
12932 q_status.m_timer = 0;
12933 if (q_status.uState != QUEST_NEW)
12934 q_status.uState = QUEST_CHANGED;
12936 IncompleteQuest( quest_id );
12938 uint16 log_slot = FindQuestSlot( quest_id );
12939 if( log_slot < MAX_QUEST_LOG_SIZE)
12941 SetQuestSlotTimer(log_slot, 1 );
12942 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12944 SendQuestTimerFailed( quest_id );
12948 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12950 int32 zoneOrSort = qInfo->GetZoneOrSort();
12951 int32 skillOrClass = qInfo->GetSkillOrClass();
12953 // skip zone zoneOrSort and 0 case skillOrClass
12954 if( zoneOrSort >= 0 && skillOrClass == 0 )
12955 return true;
12957 int32 questSort = -zoneOrSort;
12958 uint8 reqSortClass = ClassByQuestSort(questSort);
12960 // check class sort cases in zoneOrSort
12961 if( reqSortClass != 0 && getClass() != reqSortClass)
12963 if( msg )
12964 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12965 return false;
12968 // check class
12969 if( skillOrClass < 0 )
12971 uint8 reqClass = -int32(skillOrClass);
12972 if(getClass() != reqClass)
12974 if( msg )
12975 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12976 return false;
12979 // check skill
12980 else if( skillOrClass > 0 )
12982 uint32 reqSkill = skillOrClass;
12983 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12985 if( msg )
12986 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12987 return false;
12991 return true;
12994 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12996 if( getLevel() < qInfo->GetMinLevel() )
12998 if( msg )
12999 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13000 return false;
13002 return true;
13005 bool Player::SatisfyQuestLog( bool msg )
13007 // exist free slot
13008 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
13009 return true;
13011 if( msg )
13013 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
13014 GetSession()->SendPacket( &data );
13015 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
13017 return false;
13020 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
13022 // No previous quest (might be first quest in a series)
13023 if( qInfo->prevQuests.empty())
13024 return true;
13026 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
13028 uint32 prevId = abs(*iter);
13030 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
13031 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
13033 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
13035 // If any of the positive previous quests completed, return true
13036 if( *iter > 0 && i_prevstatus->second.m_rewarded )
13038 // skip one-from-all exclusive group
13039 if(qPrevInfo->GetExclusiveGroup() >= 0)
13040 return true;
13042 // each-from-all exclusive group ( < 0)
13043 // can be start if only all quests in prev quest exclusive group completed and rewarded
13044 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13045 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13047 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13049 for(; iter != end; ++iter)
13051 uint32 exclude_Id = iter->second;
13053 // skip checked quest id, only state of other quests in group is interesting
13054 if(exclude_Id == prevId)
13055 continue;
13057 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13059 // alternative quest from group also must be completed and rewarded(reported)
13060 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
13062 if( msg )
13063 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13064 return false;
13067 return true;
13069 // If any of the negative previous quests active, return true
13070 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13071 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
13073 // skip one-from-all exclusive group
13074 if(qPrevInfo->GetExclusiveGroup() >= 0)
13075 return true;
13077 // each-from-all exclusive group ( < 0)
13078 // can be start if only all quests in prev quest exclusive group active
13079 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13080 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13082 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13084 for(; iter != end; ++iter)
13086 uint32 exclude_Id = iter->second;
13088 // skip checked quest id, only state of other quests in group is interesting
13089 if(exclude_Id == prevId)
13090 continue;
13092 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13094 // alternative quest from group also must be active
13095 if( i_exstatus == mQuestStatus.end() ||
13096 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
13097 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
13099 if( msg )
13100 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13101 return false;
13104 return true;
13109 // Has only positive prev. quests in non-rewarded state
13110 // and negative prev. quests in non-active state
13111 if( msg )
13112 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13114 return false;
13117 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
13119 uint32 reqraces = qInfo->GetRequiredRaces();
13120 if ( reqraces == 0 )
13121 return true;
13122 if( (reqraces & getRaceMask()) == 0 )
13124 if( msg )
13125 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13126 return false;
13128 return true;
13131 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13133 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13134 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13136 if( msg )
13137 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13138 return false;
13141 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13142 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13144 if( msg )
13145 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13146 return false;
13149 return true;
13152 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13154 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13155 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13157 if( msg )
13158 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13159 return false;
13161 return true;
13164 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
13166 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
13168 if( msg )
13169 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
13170 return false;
13172 return true;
13175 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13177 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13178 if(qInfo->GetExclusiveGroup() <= 0)
13179 return true;
13181 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13182 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13184 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13186 for(; iter != end; ++iter)
13188 uint32 exclude_Id = iter->second;
13190 // skip checked quest id, only state of other quests in group is interesting
13191 if(exclude_Id == qInfo->GetQuestId())
13192 continue;
13194 // not allow have daily quest if daily quest from exclusive group already recently completed
13195 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
13196 if( !SatisfyQuestDay(Nquest, false) )
13198 if( msg )
13199 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13200 return false;
13203 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13205 // alternative quest already started or completed
13206 if( i_exstatus != mQuestStatus.end()
13207 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13209 if( msg )
13210 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13211 return false;
13214 return true;
13217 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13219 if(!qInfo->GetNextQuestInChain())
13220 return true;
13222 // next quest in chain already started or completed
13223 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13224 if( itr != mQuestStatus.end()
13225 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13227 if( msg )
13228 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13229 return false;
13232 // check for all quests further up the chain
13233 // only necessary if there are quest chains with more than one quest that can be skipped
13234 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13235 return true;
13238 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13240 // No previous quest in chain
13241 if( qInfo->prevChainQuests.empty())
13242 return true;
13244 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13246 uint32 prevId = *iter;
13248 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
13250 if( i_prevstatus != mQuestStatus.end() )
13252 // If any of the previous quests in chain active, return false
13253 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13254 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13256 if( msg )
13257 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13258 return false;
13262 // check for all quests further down the chain
13263 // only necessary if there are quest chains with more than one quest that can be skipped
13264 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13265 // return false;
13268 // No previous quest in chain active
13269 return true;
13272 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13274 if(!qInfo->IsDaily())
13275 return true;
13277 bool have_slot = false;
13278 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13280 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13281 if(qInfo->GetQuestId()==id)
13282 return false;
13284 if(!id)
13285 have_slot = true;
13288 if(!have_slot)
13290 if( msg )
13291 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13292 return false;
13295 return true;
13298 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13300 uint32 srcitem = pQuest->GetSrcItemId();
13301 if( srcitem > 0 )
13303 uint32 count = pQuest->GetSrcItemCount();
13304 if( count <= 0 )
13305 count = 1;
13307 ItemPosCountVec dest;
13308 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13309 if( msg == EQUIP_ERR_OK )
13311 Item * item = StoreNewItem(dest, srcitem, true);
13312 SendNewItem(item, count, true, false);
13313 return true;
13315 // player already have max amount required item, just report success
13316 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13317 return true;
13318 else
13319 SendEquipError( msg, NULL, NULL );
13320 return false;
13323 return true;
13326 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13328 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13329 if( qInfo )
13331 uint32 srcitem = qInfo->GetSrcItemId();
13332 if( srcitem > 0 )
13334 uint32 count = qInfo->GetSrcItemCount();
13335 if( count <= 0 )
13336 count = 1;
13338 // exist one case when destroy source quest item not possible:
13339 // non un-equippable item (equipped non-empty bag, for example)
13340 uint8 res = CanUnequipItems(srcitem,count);
13341 if(res != EQUIP_ERR_OK)
13343 if(msg)
13344 SendEquipError( res, NULL, NULL );
13345 return false;
13348 DestroyItemCount(srcitem, count, true, true);
13351 return true;
13354 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13356 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13357 if( qInfo )
13359 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13360 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13361 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13362 && !qInfo->IsRepeatable() )
13363 return itr->second.m_rewarded;
13365 return false;
13367 return false;
13370 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13372 if( quest_id )
13374 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13375 if( itr != mQuestStatus.end() )
13376 return itr->second.m_status;
13378 return QUEST_STATUS_NONE;
13381 bool Player::CanShareQuest(uint32 quest_id) const
13383 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13384 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13386 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13387 if( itr != mQuestStatus.end() )
13388 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13390 return false;
13393 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13395 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13396 if( qInfo )
13398 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13400 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13401 m_timedquests.erase(qInfo->GetQuestId());
13404 QuestStatusData& q_status = mQuestStatus[quest_id];
13406 q_status.m_status = status;
13407 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13410 UpdateForQuestsGO();
13413 // not used in MaNGOS, but used in scripting code
13414 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13416 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13417 if( !qInfo )
13418 return 0;
13420 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13421 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13422 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13424 return 0;
13427 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13429 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13431 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13433 uint32 reqitemcount = pQuest->ReqItemCount[i];
13434 if( reqitemcount != 0 )
13436 uint32 quest_id = pQuest->GetQuestId();
13437 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13439 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13440 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13446 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13448 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13449 if ( GetQuestSlotQuestId(i) == quest_id )
13450 return i;
13452 return MAX_QUEST_LOG_SIZE;
13455 void Player::AreaExploredOrEventHappens( uint32 questId )
13457 if( questId )
13459 uint16 log_slot = FindQuestSlot( questId );
13460 if( log_slot < MAX_QUEST_LOG_SIZE)
13462 QuestStatusData& q_status = mQuestStatus[questId];
13464 if(!q_status.m_explored)
13466 q_status.m_explored = true;
13467 if (q_status.uState != QUEST_NEW)
13468 q_status.uState = QUEST_CHANGED;
13471 if( CanCompleteQuest( questId ) )
13472 CompleteQuest( questId );
13476 //not used in mangosd, function for external script library
13477 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13479 if( Group *pGroup = GetGroup() )
13481 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13483 Player *pGroupGuy = itr->getSource();
13485 // for any leave or dead (with not released body) group member at appropriate distance
13486 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13487 pGroupGuy->AreaExploredOrEventHappens(questId);
13490 else
13491 AreaExploredOrEventHappens(questId);
13494 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13496 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13498 uint32 questid = GetQuestSlotQuestId(i);
13499 if ( questid == 0 )
13500 continue;
13502 QuestStatusData& q_status = mQuestStatus[questid];
13504 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13505 continue;
13507 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13508 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13509 continue;
13511 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13513 uint32 reqitem = qInfo->ReqItemId[j];
13514 if ( reqitem == entry )
13516 uint32 reqitemcount = qInfo->ReqItemCount[j];
13517 uint32 curitemcount = q_status.m_itemcount[j];
13518 if ( curitemcount < reqitemcount )
13520 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13521 q_status.m_itemcount[j] += additemcount;
13522 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13524 SendQuestUpdateAddItem( qInfo, j, additemcount );
13526 if ( CanCompleteQuest( questid ) )
13527 CompleteQuest( questid );
13528 return;
13532 UpdateForQuestsGO();
13533 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
13536 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13538 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13540 uint32 questid = GetQuestSlotQuestId(i);
13541 if(!questid)
13542 continue;
13543 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13544 if ( !qInfo )
13545 continue;
13546 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13547 continue;
13549 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13551 uint32 reqitem = qInfo->ReqItemId[j];
13552 if ( reqitem == entry )
13554 QuestStatusData& q_status = mQuestStatus[questid];
13556 uint32 reqitemcount = qInfo->ReqItemCount[j];
13557 uint32 curitemcount;
13558 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13559 curitemcount = q_status.m_itemcount[j];
13560 else
13561 curitemcount = GetItemCount(entry,true);
13562 if ( curitemcount < reqitemcount + count )
13564 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13565 q_status.m_itemcount[j] = curitemcount - remitemcount;
13566 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13568 IncompleteQuest( questid );
13570 return;
13574 UpdateForQuestsGO();
13577 void Player::KilledMonster( uint32 entry, uint64 guid )
13579 uint32 addkillcount = 1;
13580 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13581 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13583 uint32 questid = GetQuestSlotQuestId(i);
13584 if(!questid)
13585 continue;
13587 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13588 if( !qInfo )
13589 continue;
13590 // just if !ingroup || !noraidgroup || raidgroup
13591 QuestStatusData& q_status = mQuestStatus[questid];
13592 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13594 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13596 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13598 // skip GO activate objective or none
13599 if(qInfo->ReqCreatureOrGOId[j] <=0)
13600 continue;
13602 // skip Cast at creature objective
13603 if(qInfo->ReqSpell[j] !=0 )
13604 continue;
13606 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13608 if ( reqkill == entry )
13610 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13611 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13612 if ( curkillcount < reqkillcount )
13614 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13615 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13617 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13619 if ( CanCompleteQuest( questid ) )
13620 CompleteQuest( questid );
13622 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13623 continue;
13631 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13633 bool isCreature = IS_CREATURE_GUID(guid);
13635 uint32 addCastCount = 1;
13636 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13638 uint32 questid = GetQuestSlotQuestId(i);
13639 if(!questid)
13640 continue;
13642 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13643 if ( !qInfo )
13644 continue;
13646 QuestStatusData& q_status = mQuestStatus[questid];
13648 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13650 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13652 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13654 // skip kill creature objective (0) or wrong spell casts
13655 if(qInfo->ReqSpell[j] != spell_id )
13656 continue;
13658 uint32 reqTarget = 0;
13660 if(isCreature)
13662 // creature activate objectives
13663 if(qInfo->ReqCreatureOrGOId[j] > 0)
13664 // checked at quest_template loading
13665 reqTarget = qInfo->ReqCreatureOrGOId[j];
13667 else
13669 // GO activate objective
13670 if(qInfo->ReqCreatureOrGOId[j] < 0)
13671 // checked at quest_template loading
13672 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13675 // other not this creature/GO related objectives
13676 if( reqTarget != entry )
13677 continue;
13679 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13680 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13681 if ( curCastCount < reqCastCount )
13683 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13684 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13686 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13689 if ( CanCompleteQuest( questid ) )
13690 CompleteQuest( questid );
13692 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13693 break;
13700 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13702 uint32 addTalkCount = 1;
13703 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13705 uint32 questid = GetQuestSlotQuestId(i);
13706 if(!questid)
13707 continue;
13709 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13710 if ( !qInfo )
13711 continue;
13713 QuestStatusData& q_status = mQuestStatus[questid];
13715 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13717 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13719 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13721 // skip spell casts and Gameobject objectives
13722 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13723 continue;
13725 uint32 reqTarget = 0;
13727 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13728 // checked at quest_template loading
13729 reqTarget = qInfo->ReqCreatureOrGOId[j];
13730 else
13731 continue;
13733 if ( reqTarget == entry )
13735 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13736 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13737 if ( curTalkCount < reqTalkCount )
13739 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13740 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13742 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13744 if ( CanCompleteQuest( questid ) )
13745 CompleteQuest( questid );
13747 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13748 continue;
13756 void Player::MoneyChanged( uint32 count )
13758 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13760 uint32 questid = GetQuestSlotQuestId(i);
13761 if (!questid)
13762 continue;
13764 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13765 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13767 QuestStatusData& q_status = mQuestStatus[questid];
13769 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13771 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13773 if ( CanCompleteQuest( questid ) )
13774 CompleteQuest( questid );
13777 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13779 if(int32(count) < -qInfo->GetRewOrReqMoney())
13780 IncompleteQuest( questid );
13786 bool Player::HasQuestForItem( uint32 itemid ) const
13788 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13790 uint32 questid = GetQuestSlotQuestId(i);
13791 if ( questid == 0 )
13792 continue;
13794 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13795 if(qs_itr == mQuestStatus.end())
13796 continue;
13798 QuestStatusData const& q_status = qs_itr->second;
13800 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13802 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13803 if(!qinfo)
13804 continue;
13806 // hide quest if player is in raid-group and quest is no raid quest
13807 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13808 continue;
13810 // There should be no mixed ReqItem/ReqSource drop
13811 // This part for ReqItem drop
13812 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13814 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13815 return true;
13817 // This part - for ReqSource
13818 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13820 // examined item is a source item
13821 if (qinfo->ReqSourceId[j] == itemid)
13823 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13825 // 'unique' item
13826 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13827 return true;
13829 // allows custom amount drop when not 0
13830 if (qinfo->ReqSourceCount[j])
13832 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13833 return true;
13834 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13835 return true;
13840 return false;
13843 void Player::SendQuestComplete( uint32 quest_id )
13845 if( quest_id )
13847 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13848 data << uint32(quest_id);
13849 GetSession()->SendPacket( &data );
13850 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13854 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13856 uint32 questid = pQuest->GetQuestId();
13857 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13858 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13859 data << uint32(questid);
13861 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13863 data << uint32(XP);
13864 data << uint32(pQuest->GetRewOrReqMoney());
13866 else
13868 data << uint32(0);
13869 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13872 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13873 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13874 GetSession()->SendPacket( &data );
13876 if (pQuest->GetQuestCompleteScript() != 0)
13877 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13880 void Player::SendQuestFailed( uint32 quest_id )
13882 if( quest_id )
13884 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13885 data << quest_id;
13886 data << uint32(0); // failed reason (4 for inventory is full)
13887 GetSession()->SendPacket( &data );
13888 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13892 void Player::SendQuestTimerFailed( uint32 quest_id )
13894 if( quest_id )
13896 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13897 data << quest_id;
13898 GetSession()->SendPacket( &data );
13899 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13903 void Player::SendCanTakeQuestResponse( uint32 msg )
13905 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13906 data << uint32(msg);
13907 GetSession()->SendPacket( &data );
13908 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13911 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13913 if( pPlayer )
13915 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13916 data << uint64(pPlayer->GetGUID());
13917 data << uint8(msg); // valid values: 0-8
13918 GetSession()->SendPacket( &data );
13919 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13923 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13925 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13926 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13927 //data << pQuest->ReqItemId[item_idx];
13928 //data << count;
13929 GetSession()->SendPacket( &data );
13932 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13934 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13936 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13937 if (entry < 0)
13938 // client expected gameobject template id in form (id|0x80000000)
13939 entry = (-entry) | 0x80000000;
13941 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13942 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13943 data << uint32(pQuest->GetQuestId());
13944 data << uint32(entry);
13945 data << uint32(old_count + add_count);
13946 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13947 data << uint64(guid);
13948 GetSession()->SendPacket(&data);
13950 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13951 if( log_slot < MAX_QUEST_LOG_SIZE)
13952 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13955 /*********************************************************/
13956 /*** LOAD SYSTEM ***/
13957 /*********************************************************/
13959 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13961 bool delete_result = true;
13962 if(!result)
13964 // 0 1 2 3 4 5 6 7 8 9
13965 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13966 if(!result) return false;
13968 else delete_result = false;
13970 Field *fields = result->Fetch();
13972 if(!LoadValues( fields[1].GetString()))
13974 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13975 if(delete_result) delete result;
13976 return false;
13979 // overwrite possible wrong/corrupted guid
13980 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13982 m_name = fields[2].GetCppString();
13984 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13985 SetMapId(fields[6].GetUInt32());
13986 // the instance id is not needed at character enum
13988 m_Played_time[0] = fields[7].GetUInt32();
13989 m_Played_time[1] = fields[8].GetUInt32();
13991 m_atLoginFlags = fields[9].GetUInt32();
13993 // I don't see these used anywhere ..
13994 /*_LoadGroup();
13996 _LoadBoundInstances();*/
13998 if (delete_result) delete result;
14000 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
14001 m_items[i] = NULL;
14003 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14004 m_deathState = DEAD;
14006 return true;
14009 void Player::_LoadDeclinedNames(QueryResult* result)
14011 if(!result)
14012 return;
14014 if(m_declinedname)
14015 delete m_declinedname;
14017 m_declinedname = new DeclinedName;
14018 Field *fields = result->Fetch();
14019 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
14020 m_declinedname->name[i] = fields[i].GetCppString();
14022 delete result;
14025 void Player::_LoadArenaTeamInfo(QueryResult *result)
14027 // arenateamid, played_week, played_season, personal_rating
14028 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
14029 if (!result)
14030 return;
14034 Field *fields = result->Fetch();
14036 uint32 arenateamid = fields[0].GetUInt32();
14037 uint32 played_week = fields[1].GetUInt32();
14038 uint32 played_season = fields[2].GetUInt32();
14039 uint32 personal_rating = fields[3].GetUInt32();
14041 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
14042 if(!aTeam)
14044 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
14045 continue;
14047 uint8 arenaSlot = aTeam->GetSlot();
14049 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
14050 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
14051 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
14052 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
14053 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
14054 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
14056 }while (result->NextRow());
14057 delete result;
14060 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
14062 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
14063 if(!result)
14064 return false;
14066 Field *fields = result->Fetch();
14068 x = fields[0].GetFloat();
14069 y = fields[1].GetFloat();
14070 z = fields[2].GetFloat();
14071 o = fields[3].GetFloat();
14072 mapid = fields[4].GetUInt32();
14073 in_flight = !fields[5].GetCppString().empty();
14075 delete result;
14076 return true;
14079 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
14081 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
14082 if( !result )
14083 return false;
14085 Field *fields = result->Fetch();
14087 data = StrSplit(fields[0].GetCppString(), " ");
14089 delete result;
14091 return true;
14094 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
14096 if(index >= data.size())
14097 return 0;
14099 return (uint32)atoi(data[index].c_str());
14102 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
14104 float result;
14105 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
14106 memcpy(&result, &temp, sizeof(result));
14108 return result;
14111 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14113 Tokens data;
14114 if(!LoadValuesArrayFromDB(data,guid))
14115 return 0;
14117 return GetUInt32ValueFromArray(data,index);
14120 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14122 float result;
14123 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14124 memcpy(&result, &temp, sizeof(result));
14126 return result;
14129 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14131 //// 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
14132 //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);
14133 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14135 if(!result)
14137 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14138 return false;
14141 Field *fields = result->Fetch();
14143 uint32 dbAccountId = fields[1].GetUInt32();
14145 // check if the character's account in the db and the logged in account match.
14146 // player should be able to load/delete character only with correct account!
14147 if( dbAccountId != GetSession()->GetAccountId() )
14149 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14150 delete result;
14151 return false;
14154 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14156 m_name = fields[3].GetCppString();
14158 // check name limitations
14159 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
14161 delete result;
14162 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14163 return false;
14166 if(!LoadValues( fields[2].GetString()))
14168 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
14169 delete result;
14170 return false;
14173 // overwrite possible wrong/corrupted guid
14174 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14176 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14177 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14179 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
14180 SetVisibleItemSlot(slot,NULL);
14182 if (m_items[slot])
14184 delete m_items[slot];
14185 m_items[slot] = NULL;
14189 // update money limits
14190 if(GetMoney() > MAX_MONEY_AMOUNT)
14191 SetMoney(MAX_MONEY_AMOUNT);
14193 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14194 outDebugValues();
14196 m_race = fields[4].GetUInt8();
14197 //Need to call it to initialize m_team (m_team can be calculated from m_race)
14198 //Other way is to saves m_team into characters table.
14199 setFactionForRace(m_race);
14200 SetCharm(0);
14202 m_class = fields[5].GetUInt8();
14204 // load home bind and check in same time class/race pair, it used later for restore broken positions
14205 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14206 return false;
14208 InitPrimaryProffesions(); // to max set before any spell loaded
14210 // init saved position, and fix it later if problematic
14211 uint32 transGUID = fields[24].GetUInt32();
14212 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
14213 SetMapId(fields[9].GetUInt32());
14214 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
14216 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14218 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14220 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
14221 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
14222 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14224 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14226 // check arena teams integrity
14227 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14229 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14230 if(!arena_team_id)
14231 continue;
14233 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
14234 if(at->HaveMember(GetGUID()))
14235 continue;
14237 // arena team not exist or not member, cleanup fields
14238 for(int j =0; j < 6; ++j)
14239 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
14242 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14244 if(!IsPositionValid())
14246 sLog.outError("ERROR: Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
14247 RelocateToHomebind();
14249 transGUID = 0;
14251 m_movementInfo.t_x = 0.0f;
14252 m_movementInfo.t_y = 0.0f;
14253 m_movementInfo.t_z = 0.0f;
14254 m_movementInfo.t_o = 0.0f;
14257 uint32 bgid = fields[34].GetUInt32();
14258 uint32 bgteam = fields[35].GetUInt32();
14260 if(bgid) //saved in BattleGround
14262 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14264 // check entry point and fix to homebind if need
14265 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
14266 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
14267 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
14269 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid, BATTLEGROUND_TYPE_NONE);
14271 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14273 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14274 uint32 queueSlot = AddBattleGroundQueueId(bgQueueTypeId);
14276 SetBattleGroundId(currentBg->GetInstanceID(), currentBg->GetTypeID());
14277 SetBGTeam(bgteam);
14279 //join player to battleground group
14280 currentBg->PlayerRelogin(this);
14281 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
14283 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14285 else
14287 Relocate(GetBattleGroundEntryPoint());
14288 //RemoveArenaAuras(true);
14291 else
14293 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14294 // if server restart after player save in BG or area
14295 // player can have current coordinates in to BG/Arean map, fix this
14296 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14298 // return to BG master
14299 SetMapId(fields[36].GetUInt32());
14300 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14302 // check entry point and fix to homebind if need
14303 mapEntry = sMapStore.LookupEntry(GetMapId());
14304 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
14305 RelocateToHomebind();
14309 if (transGUID != 0)
14311 m_movementInfo.t_x = fields[20].GetFloat();
14312 m_movementInfo.t_y = fields[21].GetFloat();
14313 m_movementInfo.t_z = fields[22].GetFloat();
14314 m_movementInfo.t_o = fields[23].GetFloat();
14316 if( !MaNGOS::IsValidMapCoord(
14317 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14318 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14319 // transport size limited
14320 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14322 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14323 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14324 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14326 RelocateToHomebind();
14328 m_movementInfo.t_x = 0.0f;
14329 m_movementInfo.t_y = 0.0f;
14330 m_movementInfo.t_z = 0.0f;
14331 m_movementInfo.t_o = 0.0f;
14333 transGUID = 0;
14337 if (transGUID != 0)
14339 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14341 if( (*iter)->GetGUIDLow() == transGUID)
14343 m_transport = *iter;
14344 m_transport->AddPassenger(this);
14345 SetMapId(m_transport->GetMapId());
14346 break;
14350 if(!m_transport)
14352 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
14353 guid,transGUID);
14355 RelocateToHomebind();
14357 m_movementInfo.t_x = 0.0f;
14358 m_movementInfo.t_y = 0.0f;
14359 m_movementInfo.t_z = 0.0f;
14360 m_movementInfo.t_o = 0.0f;
14362 transGUID = 0;
14366 // NOW player must have valid map
14367 // load the player's map here if it's not already loaded
14368 Map *map = GetMap();
14370 // since the player may not be bound to the map yet, make sure subsequent
14371 // getmap calls won't create new maps
14372 SetInstanceId(map->GetInstanceId());
14374 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14375 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14377 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14378 if(at)
14379 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14380 else
14381 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());
14384 SaveRecallPosition();
14386 time_t now = time(NULL);
14387 time_t logoutTime = time_t(fields[16].GetUInt64());
14389 // since last logout (in seconds)
14390 uint64 time_diff = uint64(now - logoutTime);
14392 // set value, including drunk invisibility detection
14393 // calculate sobering. after 15 minutes logged out, the player will be sober again
14394 float soberFactor;
14395 if(time_diff > 15*MINUTE)
14396 soberFactor = 0;
14397 else
14398 soberFactor = 1-time_diff/(15.0f*MINUTE);
14399 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14400 SetDrunkValue(newDrunkenValue);
14402 m_rest_bonus = fields[15].GetFloat();
14403 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14404 float bubble0 = 0.031;
14405 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14406 float bubble1 = 0.125;
14408 if((int32)fields[16].GetUInt32() > 0)
14410 float bubble = fields[17].GetUInt32() > 0
14411 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14412 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14414 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14417 m_cinematic = fields[12].GetUInt32();
14418 m_Played_time[0]= fields[13].GetUInt32();
14419 m_Played_time[1]= fields[14].GetUInt32();
14421 m_resetTalentsCost = fields[18].GetUInt32();
14422 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14424 // reserve some flags
14425 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14427 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14428 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14430 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14432 uint32 extraflags = fields[25].GetUInt32();
14434 m_stableSlots = fields[26].GetUInt32();
14435 if(m_stableSlots > 4)
14437 sLog.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots));
14438 m_stableSlots = 4;
14441 m_atLoginFlags = fields[27].GetUInt32();
14443 // Honor system
14444 // Update Honor kills data
14445 m_lastHonorUpdateTime = logoutTime;
14446 UpdateHonorFields();
14448 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14449 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14450 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14452 std::string taxi_nodes = fields[31].GetCppString();
14454 delete result;
14456 // clear channel spell data (if saved at channel spell casting)
14457 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14458 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14460 // clear charm/summon related fields
14461 SetCharm(NULL);
14462 SetPet(NULL);
14463 SetCharmerGUID(0);
14464 SetOwnerGUID(0);
14465 SetCreatorGUID(0);
14467 // reset some aura modifiers before aura apply
14468 SetFarSightGUID(0);
14469 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14470 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14472 _LoadSkills();
14474 // make sure the unit is considered out of combat for proper loading
14475 ClearInCombat();
14477 // make sure the unit is considered not in duel for proper loading
14478 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14479 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14481 // remember loaded power/health values to restore after stats initialization and modifier applying
14482 uint32 savedHealth = GetHealth();
14483 uint32 savedPower[MAX_POWERS];
14484 for(uint32 i = 0; i < MAX_POWERS; ++i)
14485 savedPower[i] = GetPower(Powers(i));
14487 // reset stats before loading any modifiers
14488 InitStatsForLevel();
14489 InitTaxiNodesForLevel();
14490 InitGlyphsForLevel();
14491 InitRunes();
14493 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14495 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14496 //_LoadMail();
14498 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14499 _LoadGlyphAuras();
14501 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14502 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14503 m_deathState = DEAD;
14505 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14507 // after spell load, learn rewarded spell if need also
14508 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14509 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14511 // after spell and quest load
14512 InitTalentForLevel();
14513 learnDefaultSpells();
14515 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14517 // must be before inventory (some items required reputation check)
14518 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14520 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14522 // update items with duration and realtime
14523 UpdateItemDuration(time_diff, true);
14525 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14527 // unread mails and next delivery time, actual mails not loaded
14528 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14530 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14532 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14533 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14534 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14536 if(!HasTitle(curTitle))
14537 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14540 // Not finish taxi flight path
14541 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14543 // problems with taxi path loading
14544 TaxiNodesEntry const* nodeEntry = NULL;
14545 if(uint32 node_id = m_taxi.GetTaxiSource())
14546 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14548 if(!nodeEntry) // don't know taxi start node, to homebind
14550 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14551 RelocateToHomebind();
14552 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14554 else // have start node, to it
14556 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14557 SetMapId(nodeEntry->map_id);
14558 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14559 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14561 m_taxi.ClearTaxiDestinations();
14563 else if(uint32 node_id = m_taxi.GetTaxiSource())
14565 // save source node as recall coord to prevent recall and fall from sky
14566 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14567 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14568 m_recallMap = nodeEntry->map_id;
14569 m_recallX = nodeEntry->x;
14570 m_recallY = nodeEntry->y;
14571 m_recallZ = nodeEntry->z;
14573 // flight will started later
14576 // has to be called after last Relocate() in Player::LoadFromDB
14577 SetFallInformation(0, GetPositionZ());
14579 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14581 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14582 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14583 if(!isAlive())
14584 RemoveAllAurasOnDeath();
14586 //apply all stat bonuses from items and auras
14587 SetCanModifyStats(true);
14588 UpdateAllStats();
14590 // restore remembered power/health values (but not more max values)
14591 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14592 for(uint32 i = 0; i < MAX_POWERS; ++i)
14593 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14595 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14596 outDebugValues();
14598 // GM state
14599 if(GetSession()->GetSecurity() > SEC_PLAYER)
14601 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14603 default:
14604 case 0: break; // disable
14605 case 1: SetGameMaster(true); break; // enable
14606 case 2: // save state
14607 if(extraflags & PLAYER_EXTRA_GM_ON)
14608 SetGameMaster(true);
14609 break;
14612 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14614 default:
14615 case 0: SetGMVisible(false); break; // invisible
14616 case 1: break; // visible
14617 case 2: // save state
14618 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14619 SetGMVisible(false);
14620 break;
14623 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14625 default:
14626 case 0: break; // disable
14627 case 1: SetAcceptTicket(true); break; // enable
14628 case 2: // save state
14629 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14630 SetAcceptTicket(true);
14631 break;
14634 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14636 default:
14637 case 0: break; // disable
14638 case 1: SetGMChat(true); break; // enable
14639 case 2: // save state
14640 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14641 SetGMChat(true);
14642 break;
14645 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14647 default:
14648 case 0: break; // disable
14649 case 1: SetAcceptWhispers(true); break; // enable
14650 case 2: // save state
14651 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14652 SetAcceptWhispers(true);
14653 break;
14657 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14659 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14660 m_achievementMgr.CheckAllAchievementCriteria();
14661 return true;
14664 bool Player::isAllowedToLoot(Creature* creature)
14666 if(Player* recipient = creature->GetLootRecipient())
14668 if (recipient == this)
14669 return true;
14670 if( Group* otherGroup = recipient->GetGroup())
14672 Group* thisGroup = GetGroup();
14673 if(!thisGroup)
14674 return false;
14675 return thisGroup == otherGroup;
14677 return false;
14679 else
14680 // prevent other players from looting if the recipient got disconnected
14681 return !creature->hasLootRecipient();
14684 void Player::_LoadActions(QueryResult *result)
14686 m_actionButtons.clear();
14688 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14690 if(result)
14694 Field *fields = result->Fetch();
14696 uint8 button = fields[0].GetUInt8();
14698 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
14700 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14702 while( result->NextRow() );
14704 delete result;
14708 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14710 m_Auras.clear();
14711 for (int i = 0; i < TOTAL_AURAS; i++)
14712 m_modAuras[i].clear();
14714 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14716 if(result)
14720 Field *fields = result->Fetch();
14721 uint64 caster_guid = fields[0].GetUInt64();
14722 uint32 spellid = fields[1].GetUInt32();
14723 uint32 effindex = fields[2].GetUInt32();
14724 uint32 stackcount = fields[3].GetUInt32();
14725 int32 damage = (int32)fields[4].GetUInt32();
14726 int32 maxduration = (int32)fields[5].GetUInt32();
14727 int32 remaintime = (int32)fields[6].GetUInt32();
14728 int32 remaincharges = (int32)fields[7].GetUInt32();
14730 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14731 if(!spellproto)
14733 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14734 continue;
14737 if(effindex >= 3)
14739 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14740 continue;
14743 // negative effects should continue counting down after logout
14744 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14746 if(remaintime <= int32(timediff))
14747 continue;
14749 remaintime -= timediff;
14752 // prevent wrong values of remaincharges
14753 if(spellproto->procCharges)
14755 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14756 remaincharges = spellproto->procCharges;
14758 else
14759 remaincharges = 0;
14761 //do not load single target auras (unless they were cast by the player)
14762 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
14763 continue;
14765 for(uint32 i=0; i<stackcount; i++)
14767 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14768 if(!damage)
14769 damage = aura->GetModifier()->m_amount;
14770 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14771 AddAura(aura);
14772 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14775 while( result->NextRow() );
14777 delete result;
14780 if(m_class == CLASS_WARRIOR)
14781 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14784 void Player::_LoadGlyphAuras()
14786 for (uint8 i = 0; i <= MAX_GLYPH_SLOT_INDEX; ++i)
14788 if (uint32 glyph = GetGlyph(i))
14790 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14792 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14794 if(gp->TypeFlags == gs->TypeFlags)
14796 CastSpell(this, gp->SpellId, true);
14797 continue;
14799 else
14800 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14802 else
14803 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14805 else
14806 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14808 // On any error remove glyph
14809 SetGlyph(i, 0);
14814 void Player::LoadCorpse()
14816 if( isAlive() )
14818 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14820 else
14822 if(Corpse *corpse = GetCorpse())
14824 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14826 else
14828 //Prevent Dead Player login without corpse
14829 ResurrectPlayer(0.5f);
14834 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14836 //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());
14837 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14838 //NOTE: the "order by `bag`" is important because it makes sure
14839 //the bagMap is filled before items in the bags are loaded
14840 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14841 //expected to be equipped before offhand items (TODO: fixme)
14843 uint32 zone = GetZoneId();
14845 if (result)
14847 std::list<Item*> problematicItems;
14849 // prevent items from being added to the queue when stored
14850 m_itemUpdateQueueBlocked = true;
14853 Field *fields = result->Fetch();
14854 uint32 bag_guid = fields[1].GetUInt32();
14855 uint8 slot = fields[2].GetUInt8();
14856 uint32 item_guid = fields[3].GetUInt32();
14857 uint32 item_id = fields[4].GetUInt32();
14859 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14861 if(!proto)
14863 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14864 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14865 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14866 continue;
14869 Item *item = NewItemOrBag(proto);
14871 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14873 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14874 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14875 item->FSetState(ITEM_REMOVED);
14876 item->SaveToDB(); // it also deletes item object !
14877 continue;
14880 // not allow have in alive state item limited to another map/zone
14881 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14883 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14884 item->FSetState(ITEM_REMOVED);
14885 item->SaveToDB(); // it also deletes item object !
14886 continue;
14889 // "Conjured items disappear if you are logged out for more than 15 minutes"
14890 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14892 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14893 item->FSetState(ITEM_REMOVED);
14894 item->SaveToDB(); // it also deletes item object !
14895 continue;
14898 bool success = true;
14900 if (!bag_guid)
14902 // the item is not in a bag
14903 item->SetContainer( NULL );
14904 item->SetSlot(slot);
14906 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14908 ItemPosCountVec dest;
14909 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14910 item = StoreItem(dest, item, true);
14911 else
14912 success = false;
14914 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14916 uint16 dest;
14917 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14918 QuickEquipItem(dest, item);
14919 else
14920 success = false;
14922 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14924 ItemPosCountVec dest;
14925 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14926 item = BankItem(dest, item, true);
14927 else
14928 success = false;
14931 if(success)
14933 // store bags that may contain items in them
14934 if(item->IsBag() && IsBagPos(item->GetPos()))
14935 bagMap[item_guid] = (Bag*)item;
14938 else
14940 item->SetSlot(NULL_SLOT);
14941 // the item is in a bag, find the bag
14942 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14943 if(itr != bagMap.end())
14944 itr->second->StoreItem(slot, item, true );
14945 else
14946 success = false;
14949 // item's state may have changed after stored
14950 if (success)
14951 item->SetState(ITEM_UNCHANGED, this);
14952 else
14954 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);
14955 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14956 problematicItems.push_back(item);
14958 } while (result->NextRow());
14960 delete result;
14961 m_itemUpdateQueueBlocked = false;
14963 // send by mail problematic items
14964 while(!problematicItems.empty())
14966 // fill mail
14967 MailItemsInfo mi; // item list preparing
14969 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14971 Item* item = problematicItems.front();
14972 problematicItems.pop_front();
14974 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14977 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14979 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14982 //if(isAlive())
14983 _ApplyAllItemMods();
14986 // load mailed item which should receive current player
14987 void Player::_LoadMailedItems(Mail *mail)
14989 // data needs to be at first place for Item::LoadFromDB
14990 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);
14991 if(!result)
14992 return;
14996 Field *fields = result->Fetch();
14997 uint32 item_guid_low = fields[1].GetUInt32();
14998 uint32 item_template = fields[2].GetUInt32();
15000 mail->AddItem(item_guid_low, item_template);
15002 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
15004 if(!proto)
15006 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);
15007 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15008 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
15009 continue;
15012 Item *item = NewItemOrBag(proto);
15014 if(!item->LoadFromDB(item_guid_low, 0, result))
15016 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
15017 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15018 item->FSetState(ITEM_REMOVED);
15019 item->SaveToDB(); // it also deletes item object !
15020 continue;
15023 AddMItem(item);
15024 } while (result->NextRow());
15026 delete result;
15029 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
15031 //set a count of unread mails
15032 //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);
15033 if (resultUnread)
15035 Field *fieldMail = resultUnread->Fetch();
15036 unReadMails = fieldMail[0].GetUInt8();
15037 delete resultUnread;
15040 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
15041 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
15042 if (resultDelivery)
15044 Field *fieldMail = resultDelivery->Fetch();
15045 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
15046 delete resultDelivery;
15050 void Player::_LoadMail()
15052 m_mail.clear();
15053 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15054 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());
15055 if(result)
15059 Field *fields = result->Fetch();
15060 Mail *m = new Mail;
15061 m->messageID = fields[0].GetUInt32();
15062 m->messageType = fields[1].GetUInt8();
15063 m->sender = fields[2].GetUInt32();
15064 m->receiver = fields[3].GetUInt32();
15065 m->subject = fields[4].GetCppString();
15066 m->itemTextId = fields[5].GetUInt32();
15067 bool has_items = fields[6].GetBool();
15068 m->expire_time = (time_t)fields[7].GetUInt64();
15069 m->deliver_time = (time_t)fields[8].GetUInt64();
15070 m->money = fields[9].GetUInt32();
15071 m->COD = fields[10].GetUInt32();
15072 m->checked = fields[11].GetUInt32();
15073 m->stationery = fields[12].GetUInt8();
15074 m->mailTemplateId = fields[13].GetInt16();
15076 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15078 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15079 m->mailTemplateId = 0;
15082 m->state = MAIL_STATE_UNCHANGED;
15084 if (has_items)
15085 _LoadMailedItems(m);
15087 m_mail.push_back(m);
15088 } while( result->NextRow() );
15089 delete result;
15091 m_mailsLoaded = true;
15094 void Player::LoadPet()
15096 //fixme: the pet should still be loaded if the player is not in world
15097 // just not added to the map
15098 if(IsInWorld())
15100 Pet *pet = new Pet;
15101 if(!pet->LoadPetFromDB(this,0,0,true))
15102 delete pet;
15106 void Player::_LoadQuestStatus(QueryResult *result)
15108 mQuestStatus.clear();
15110 uint32 slot = 0;
15112 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15113 //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());
15115 if(result)
15119 Field *fields = result->Fetch();
15121 uint32 quest_id = fields[0].GetUInt32();
15122 // used to be new, no delete?
15123 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15124 if( pQuest )
15126 // find or create
15127 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15129 uint32 qstatus = fields[1].GetUInt32();
15130 if(qstatus < MAX_QUEST_STATUS)
15131 questStatusData.m_status = QuestStatus(qstatus);
15132 else
15134 questStatusData.m_status = QUEST_STATUS_NONE;
15135 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15138 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15139 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15141 time_t quest_time = time_t(fields[4].GetUInt64());
15143 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15145 AddTimedQuest( quest_id );
15147 if (quest_time <= sWorld.GetGameTime())
15148 questStatusData.m_timer = 1;
15149 else
15150 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
15152 else
15153 quest_time = 0;
15155 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15156 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15157 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15158 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15159 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15160 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15161 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15162 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15164 questStatusData.uState = QUEST_UNCHANGED;
15166 // add to quest log
15167 if( slot < MAX_QUEST_LOG_SIZE &&
15168 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
15169 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
15170 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
15172 SetQuestSlot(slot,quest_id,quest_time);
15174 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
15175 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
15177 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15178 if(questStatusData.m_creatureOrGOcount[idx])
15179 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
15181 ++slot;
15184 if(questStatusData.m_rewarded)
15186 // learn rewarded spell if unknown
15187 learnQuestRewardedSpells(pQuest);
15189 // set rewarded title if any
15190 if(pQuest->GetCharTitleId())
15192 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15193 SetTitle(titleEntry);
15196 if(pQuest->GetBonusTalents())
15197 m_questRewardTalentCount+=pQuest->GetBonusTalents();
15200 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15203 while( result->NextRow() );
15205 delete result;
15208 // clear quest log tail
15209 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15210 SetQuestSlot(i,0);
15213 void Player::_LoadDailyQuestStatus(QueryResult *result)
15215 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15216 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15218 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15220 if(result)
15222 uint32 quest_daily_idx = 0;
15226 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15228 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15229 break;
15232 Field *fields = result->Fetch();
15234 uint32 quest_id = fields[0].GetUInt32();
15236 // save _any_ from daily quest times (it must be after last reset anyway)
15237 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15239 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15240 if( !pQuest )
15241 continue;
15243 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15244 ++quest_daily_idx;
15246 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15248 while( result->NextRow() );
15250 delete result;
15253 m_DailyQuestChanged = false;
15256 void Player::_LoadReputation(QueryResult *result)
15258 m_factions.clear();
15260 // Set initial reputations (so everything is nifty before DB data load)
15261 SetInitialFactions();
15263 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
15265 if(result)
15269 Field *fields = result->Fetch();
15271 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
15272 if( factionEntry && (factionEntry->reputationListID >= 0))
15274 FactionState* faction = &m_factions[factionEntry->reputationListID];
15276 // update standing to current
15277 faction->Standing = int32(fields[1].GetUInt32());
15279 uint32 dbFactionFlags = fields[2].GetUInt32();
15281 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
15282 SetFactionVisible(faction); // have internal checks for forced invisibility
15284 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
15285 SetFactionInactive(faction,true); // have internal checks for visibility requirement
15287 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
15288 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
15289 else // DB not at war
15291 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
15292 if( faction->Flags & FACTION_FLAG_VISIBLE )
15293 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
15296 // set atWar for hostile
15297 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
15298 SetFactionAtWar(faction,true);
15300 // reset changed flag if values similar to saved in DB
15301 if(faction->Flags==dbFactionFlags)
15302 faction->Changed = false;
15305 while( result->NextRow() );
15307 delete result;
15311 void Player::_LoadSpells(QueryResult *result)
15313 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15315 if(result)
15319 Field *fields = result->Fetch();
15321 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
15323 while( result->NextRow() );
15325 delete result;
15329 void Player::_LoadTutorials(QueryResult *result)
15331 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
15333 if(result)
15337 Field *fields = result->Fetch();
15339 for (int iI=0; iI<8; iI++)
15340 m_Tutorials[iI] = fields[iI].GetUInt32();
15342 while( result->NextRow() );
15344 delete result;
15347 m_TutorialsChanged = false;
15350 void Player::_LoadGroup(QueryResult *result)
15352 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15353 if(result)
15355 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15356 delete result;
15357 Group* group = objmgr.GetGroupByLeader(leaderGuid);
15358 if(group)
15360 uint8 subgroup = group->GetMemberGroup(GetGUID());
15361 SetGroup(group, subgroup);
15362 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
15364 // the group leader may change the instance difficulty while the player is offline
15365 SetDifficulty(group->GetDifficulty());
15371 void Player::_LoadBoundInstances(QueryResult *result)
15373 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15374 m_boundInstances[i].clear();
15376 Group *group = GetGroup();
15378 //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));
15379 if(result)
15383 Field *fields = result->Fetch();
15384 bool perm = fields[1].GetBool();
15385 uint32 mapId = fields[2].GetUInt32();
15386 uint32 instanceId = fields[0].GetUInt32();
15387 uint8 difficulty = fields[3].GetUInt8();
15388 time_t resetTime = (time_t)fields[4].GetUInt64();
15389 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15390 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15391 // and in that case it is not used
15393 if(!perm && group)
15395 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);
15396 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15397 continue;
15400 // since non permanent binds are always solo bind, they can always be reset
15401 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15402 if(save) BindToInstance(save, perm, true);
15403 } while(result->NextRow());
15404 delete result;
15408 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15410 // some instances only have one difficulty
15411 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15412 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15414 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15415 if(itr != m_boundInstances[difficulty].end())
15416 return &itr->second;
15417 else
15418 return NULL;
15421 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15423 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15424 UnbindInstance(itr, difficulty, unload);
15427 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15429 if(itr != m_boundInstances[difficulty].end())
15431 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15432 itr->second.save->RemovePlayer(this); // save can become invalid
15433 m_boundInstances[difficulty].erase(itr++);
15437 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15439 if(save)
15441 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15442 if(bind.save)
15444 // update the save when the group kills a boss
15445 if(permanent != bind.perm || save != bind.save)
15446 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());
15448 else
15449 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15451 if(bind.save != save)
15453 if(bind.save) bind.save->RemovePlayer(this);
15454 save->AddPlayer(this);
15457 if(permanent) save->SetCanReset(false);
15459 bind.save = save;
15460 bind.perm = permanent;
15461 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());
15462 return &bind;
15464 else
15465 return NULL;
15468 void Player::SendRaidInfo()
15470 uint32 counter = 0;
15472 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15474 size_t p_counter = data.wpos();
15475 data << uint32(counter); // placeholder
15477 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15479 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15481 if(itr->second.perm)
15483 InstanceSave *save = itr->second.save;
15484 data << uint32(save->GetMapId());
15485 data << uint32(save->GetResetTime() - time(NULL));
15486 data << uint32(save->GetInstanceId());
15487 data << uint32(save->GetDifficulty());
15488 ++counter;
15492 data.put<uint32>(p_counter,counter);
15493 GetSession()->SendPacket(&data);
15497 - called on every successful teleportation to a map
15499 void Player::SendSavedInstances()
15501 bool hasBeenSaved = false;
15502 WorldPacket data;
15504 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15506 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15508 if(itr->second.perm) // only permanent binds are sent
15510 hasBeenSaved = true;
15511 break;
15516 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15517 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15518 data << uint32(hasBeenSaved);
15519 GetSession()->SendPacket(&data);
15521 if(!hasBeenSaved)
15522 return;
15524 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15526 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15528 if(itr->second.perm)
15530 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15531 data << uint32(itr->second.save->GetMapId());
15532 GetSession()->SendPacket(&data);
15538 /// convert the player's binds to the group
15539 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15541 bool has_binds = false;
15542 bool has_solo = false;
15544 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15545 assert(player_guid);
15547 // copy all binds to the group, when changing leader it's assumed the character
15548 // will not have any solo binds
15550 if(player)
15552 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15554 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15556 has_binds = true;
15557 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15558 // permanent binds are not removed
15559 if(!itr->second.perm)
15561 player->UnbindInstance(itr, i, true); // increments itr
15562 has_solo = true;
15564 else
15565 ++itr;
15570 // if the player's not online we don't know what binds it has
15571 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));
15572 // the following should not get executed when changing leaders
15573 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15576 bool Player::_LoadHomeBind(QueryResult *result)
15578 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15579 if(!info)
15581 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15582 return false;
15585 bool ok = false;
15586 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15587 if (result)
15589 Field *fields = result->Fetch();
15590 m_homebindMapId = fields[0].GetUInt32();
15591 m_homebindZoneId = fields[1].GetUInt16();
15592 m_homebindX = fields[2].GetFloat();
15593 m_homebindY = fields[3].GetFloat();
15594 m_homebindZ = fields[4].GetFloat();
15595 delete result;
15597 // accept saved data only for valid position (and non instanceable)
15598 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15599 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
15601 ok = true;
15603 else
15604 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15607 if(!ok)
15609 m_homebindMapId = info->mapId;
15610 m_homebindZoneId = info->zoneId;
15611 m_homebindX = info->positionX;
15612 m_homebindY = info->positionY;
15613 m_homebindZ = info->positionZ;
15615 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);
15618 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15619 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15621 return true;
15624 /*********************************************************/
15625 /*** SAVE SYSTEM ***/
15626 /*********************************************************/
15628 void Player::SaveToDB()
15630 // delay auto save at any saves (manual, in code, or autosave)
15631 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15633 // first save/honor gain after midnight will also update the player's honor fields
15634 UpdateHonorFields();
15636 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15637 //save, far from tavern/city
15638 //save, but in tavern/city
15639 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15640 outDebugValues();
15642 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15643 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15644 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15645 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15646 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15647 uint32 tmp_displayid = GetDisplayId();
15649 // Set player sit state to standing on save, also stealth and shifted form
15650 SetByteValue(UNIT_FIELD_BYTES_1, 0, UNIT_STAND_STATE_STAND);
15651 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15652 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15653 SetDisplayId(GetNativeDisplayId());
15655 bool inworld = IsInWorld();
15657 CharacterDatabase.BeginTransaction();
15659 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15661 std::string sql_name = m_name;
15662 CharacterDatabase.escape_string(sql_name);
15664 std::ostringstream ss;
15665 ss << "INSERT INTO characters (guid,account,name,race,class,"
15666 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15667 "taximask, online, cinematic, "
15668 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15669 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15670 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15671 << GetGUIDLow() << ", "
15672 << GetSession()->GetAccountId() << ", '"
15673 << sql_name << "', "
15674 << m_race << ", "
15675 << m_class << ", ";
15677 if(!IsBeingTeleported())
15679 ss << GetMapId() << ", "
15680 << (uint32)GetDifficulty() << ", "
15681 << finiteAlways(GetPositionX()) << ", "
15682 << finiteAlways(GetPositionY()) << ", "
15683 << finiteAlways(GetPositionZ()) << ", "
15684 << finiteAlways(GetOrientation()) << ", '";
15686 else
15688 ss << GetTeleportDest().mapid << ", "
15689 << (uint32)GetDifficulty() << ", "
15690 << finiteAlways(GetTeleportDest().x) << ", "
15691 << finiteAlways(GetTeleportDest().y) << ", "
15692 << finiteAlways(GetTeleportDest().z) << ", "
15693 << finiteAlways(GetTeleportDest().o) << ", '";
15696 uint16 i;
15697 for( i = 0; i < m_valuesCount; i++ )
15699 ss << GetUInt32Value(i) << " ";
15702 ss << "', ";
15704 ss << m_taxi; // string with TaxiMaskSize numbers
15706 ss << ", ";
15707 ss << (inworld ? 1 : 0);
15709 ss << ", ";
15710 ss << m_cinematic;
15712 ss << ", ";
15713 ss << m_Played_time[0];
15714 ss << ", ";
15715 ss << m_Played_time[1];
15717 ss << ", ";
15718 ss << finiteAlways(m_rest_bonus);
15719 ss << ", ";
15720 ss << (uint64)time(NULL);
15721 ss << ", ";
15722 ss << is_save_resting;
15723 ss << ", ";
15724 ss << m_resetTalentsCost;
15725 ss << ", ";
15726 ss << (uint64)m_resetTalentsTime;
15728 ss << ", ";
15729 ss << finiteAlways(m_movementInfo.t_x);
15730 ss << ", ";
15731 ss << finiteAlways(m_movementInfo.t_y);
15732 ss << ", ";
15733 ss << finiteAlways(m_movementInfo.t_z);
15734 ss << ", ";
15735 ss << finiteAlways(m_movementInfo.t_o);
15736 ss << ", ";
15737 if (m_transport)
15738 ss << m_transport->GetGUIDLow();
15739 else
15740 ss << "0";
15742 ss << ", ";
15743 ss << m_ExtraFlags;
15745 ss << ", ";
15746 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15748 ss << ", ";
15749 ss << uint32(m_atLoginFlags);
15751 ss << ", ";
15752 ss << GetZoneId();
15754 ss << ", ";
15755 ss << (uint64)m_deathExpireTime;
15757 ss << ", '";
15758 ss << m_taxi.SaveTaxiDestinationsToString();
15759 ss << "', '0', ";
15760 ss << GetBattleGroundId();
15761 ss << ", ";
15762 ss << GetBGTeam();
15763 ss << ", ";
15764 ss << m_bgEntryPoint.mapid << ", "
15765 << finiteAlways(m_bgEntryPoint.x) << ", "
15766 << finiteAlways(m_bgEntryPoint.y) << ", "
15767 << finiteAlways(m_bgEntryPoint.z) << ", "
15768 << finiteAlways(m_bgEntryPoint.o);
15769 ss << ")";
15771 CharacterDatabase.Execute( ss.str().c_str() );
15773 if(m_mailsUpdated) //save mails only when needed
15774 _SaveMail();
15776 _SaveInventory();
15777 _SaveQuestStatus();
15778 _SaveDailyQuestStatus();
15779 _SaveTutorials();
15780 _SaveSpells();
15781 _SaveSpellCooldowns();
15782 _SaveActions();
15783 _SaveAuras();
15784 _SaveReputation();
15786 CharacterDatabase.CommitTransaction();
15788 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15789 SetDisplayId(tmp_displayid);
15790 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15791 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15792 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15793 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15795 // save pet (hunter pet level and experience and all type pets health/mana).
15796 if(Pet* pet = GetPet())
15797 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15798 m_achievementMgr.SaveToDB();
15801 // fast save function for item/money cheating preventing - save only inventory and money state
15802 void Player::SaveInventoryAndGoldToDB()
15804 _SaveInventory();
15805 //money is in data field
15806 SaveDataFieldToDB();
15809 void Player::_SaveActions()
15811 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15813 switch (itr->second.uState)
15815 case ACTIONBUTTON_NEW:
15816 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15817 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15818 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15819 ++itr;
15820 break;
15821 case ACTIONBUTTON_CHANGED:
15822 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15823 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15824 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15825 ++itr;
15826 break;
15827 case ACTIONBUTTON_DELETED:
15828 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15829 m_actionButtons.erase(itr++);
15830 break;
15831 default:
15832 ++itr;
15833 break;
15838 void Player::_SaveAuras()
15840 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15842 AuraMap const& auras = GetAuras();
15844 if (auras.empty())
15845 return;
15847 spellEffectPair lastEffectPair = auras.begin()->first;
15848 uint32 stackCounter = 1;
15850 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15852 if(itr == auras.end() || lastEffectPair != itr->first)
15854 AuraMap::const_iterator itr2 = itr;
15855 // save previous spellEffectPair to db
15856 itr2--;
15858 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15860 //skip all auras from spells that are passive or need a shapeshift
15861 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15863 //do not save single target auras (unless they were cast by the player)
15864 if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
15866 uint8 i;
15867 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15868 for (i = 0; i < 3; i++)
15869 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15870 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15871 break;
15873 if (i == 3)
15875 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15876 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15877 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()));
15882 if(itr == auras.end())
15883 break;
15886 if (lastEffectPair == itr->first)
15887 stackCounter++;
15888 else
15890 lastEffectPair = itr->first;
15891 stackCounter = 1;
15896 void Player::_SaveInventory()
15898 // force items in buyback slots to new state
15899 // and remove those that aren't already
15900 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
15902 Item *item = m_items[i];
15903 if (!item || item->GetState() == ITEM_NEW) continue;
15904 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15905 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15906 m_items[i]->FSetState(ITEM_NEW);
15909 // update enchantment durations
15910 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15912 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15915 // if no changes
15916 if (m_itemUpdateQueue.empty()) return;
15918 // do not save if the update queue is corrupt
15919 bool error = false;
15920 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15922 Item *item = m_itemUpdateQueue[i];
15923 if(!item || item->GetState() == ITEM_REMOVED) continue;
15924 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15926 if (test == NULL)
15928 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());
15929 error = true;
15931 else if (test != item)
15933 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());
15934 error = true;
15938 if (error)
15940 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15941 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15942 return;
15945 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15947 Item *item = m_itemUpdateQueue[i];
15948 if(!item) continue;
15950 Bag *container = item->GetContainer();
15951 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15953 switch(item->GetState())
15955 case ITEM_NEW:
15956 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());
15957 break;
15958 case ITEM_CHANGED:
15959 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());
15960 break;
15961 case ITEM_REMOVED:
15962 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15963 break;
15964 case ITEM_UNCHANGED:
15965 break;
15968 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15970 m_itemUpdateQueue.clear();
15973 void Player::_SaveMail()
15975 if (!m_mailsLoaded)
15976 return;
15978 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15980 Mail *m = (*itr);
15981 if (m->state == MAIL_STATE_CHANGED)
15983 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'",
15984 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15985 if(m->removedItems.size())
15987 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15988 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15989 m->removedItems.clear();
15991 m->state = MAIL_STATE_UNCHANGED;
15993 else if (m->state == MAIL_STATE_DELETED)
15995 if (m->HasItems())
15996 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15997 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15998 if (m->itemTextId)
15999 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
16000 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
16001 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
16005 //deallocate deleted mails...
16006 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
16008 if ((*itr)->state == MAIL_STATE_DELETED)
16010 Mail* m = *itr;
16011 m_mail.erase(itr);
16012 delete m;
16013 itr = m_mail.begin();
16015 else
16016 ++itr;
16019 m_mailsUpdated = false;
16022 void Player::_SaveQuestStatus()
16024 // we don't need transactions here.
16025 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
16027 switch (i->second.uState)
16029 case QUEST_NEW :
16030 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
16031 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
16032 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]);
16033 break;
16034 case QUEST_CHANGED :
16035 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' ",
16036 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 );
16037 break;
16038 case QUEST_UNCHANGED:
16039 break;
16041 i->second.uState = QUEST_UNCHANGED;
16045 void Player::_SaveDailyQuestStatus()
16047 if(!m_DailyQuestChanged)
16048 return;
16050 m_DailyQuestChanged = false;
16052 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
16054 // we don't need transactions here.
16055 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
16056 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
16057 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
16058 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
16059 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
16062 void Player::_SaveReputation()
16064 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
16066 if (itr->second.Changed)
16068 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
16069 CharacterDatabase.PExecute("INSERT INTO character_reputation (guid,faction,standing,flags) VALUES ('%u', '%u', '%i', '%u')", GetGUIDLow(), itr->second.ID, itr->second.Standing, itr->second.Flags);
16070 itr->second.Changed = false;
16075 void Player::_SaveSpells()
16077 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
16079 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
16080 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
16082 // add only changed/new not dependent spells
16083 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
16084 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);
16086 if (itr->second->state == PLAYERSPELL_REMOVED)
16088 delete itr->second;
16089 m_spells.erase(itr++);
16091 else
16093 itr->second->state = PLAYERSPELL_UNCHANGED;
16094 ++itr;
16100 void Player::_SaveTutorials()
16102 if(!m_TutorialsChanged)
16103 return;
16105 uint32 Rows=0;
16106 // it's better than rebuilding indexes multiple times
16107 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
16108 if(result)
16110 Rows = result->Fetch()[0].GetUInt32();
16111 delete result;
16114 if (Rows)
16116 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'",
16117 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 );
16119 else
16121 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]);
16124 m_TutorialsChanged = false;
16127 void Player::outDebugValues() const
16129 if(!sLog.IsOutDebug()) // optimize disabled debug output
16130 return;
16132 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
16133 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
16134 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
16135 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
16136 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
16137 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
16138 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
16139 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
16140 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
16141 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
16142 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
16143 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
16146 /*********************************************************/
16147 /*** FLOOD FILTER SYSTEM ***/
16148 /*********************************************************/
16150 void Player::UpdateSpeakTime()
16152 // ignore chat spam protection for GMs in any mode
16153 if(GetSession()->GetSecurity() > SEC_PLAYER)
16154 return;
16156 time_t current = time (NULL);
16157 if(m_speakTime > current)
16159 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
16160 if(!max_count)
16161 return;
16163 ++m_speakCount;
16164 if(m_speakCount >= max_count)
16166 // prevent overwrite mute time, if message send just before mutes set, for example.
16167 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
16168 if(GetSession()->m_muteTime < new_mute)
16169 GetSession()->m_muteTime = new_mute;
16171 m_speakCount = 0;
16174 else
16175 m_speakCount = 0;
16177 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
16180 bool Player::CanSpeak() const
16182 return GetSession()->m_muteTime <= time (NULL);
16185 /*********************************************************/
16186 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16187 /*********************************************************/
16189 void Player::SendAttackSwingNotInRange()
16191 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16192 GetSession()->SendPacket( &data );
16195 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16197 std::ostringstream ss;
16198 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16199 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16200 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16201 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16202 sLog.outDebug(ss.str().c_str());
16203 CharacterDatabase.Execute(ss.str().c_str());
16206 void Player::SaveDataFieldToDB()
16208 std::ostringstream ss;
16209 ss<<"UPDATE characters SET data='";
16211 for(uint16 i = 0; i < m_valuesCount; i++ )
16213 ss << GetUInt32Value(i) << " ";
16215 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16217 CharacterDatabase.Execute(ss.str().c_str());
16220 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16222 std::ostringstream ss2;
16223 ss2<<"UPDATE characters SET data='";
16224 int i=0;
16225 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16227 ss2<<tokens[i]<<" ";
16229 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16231 return CharacterDatabase.Execute(ss2.str().c_str());
16234 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16236 char buf[11];
16237 snprintf(buf,11,"%u",value);
16239 if(index >= tokens.size())
16240 return;
16242 tokens[index] = buf;
16245 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16247 Tokens tokens;
16248 if(!LoadValuesArrayFromDB(tokens,guid))
16249 return;
16251 if(index >= tokens.size())
16252 return;
16254 char buf[11];
16255 snprintf(buf,11,"%u",value);
16256 tokens[index] = buf;
16258 SaveValuesArrayInDB(tokens,guid);
16261 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16263 uint32 temp;
16264 memcpy(&temp, &value, sizeof(value));
16265 Player::SetUInt32ValueInDB(index, temp, guid);
16268 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16270 Tokens tokens;
16271 if(!LoadValuesArrayFromDB(tokens, guid))
16272 return;
16274 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
16275 uint8 race = unit_bytes0 & 0xFF;
16276 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
16278 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
16279 if(!info)
16280 return;
16282 unit_bytes0 &= ~(0xFF << 16);
16283 unit_bytes0 |= (gender << 16);
16284 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
16286 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
16287 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
16289 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
16291 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
16292 player_bytes2 &= ~0xFF;
16293 player_bytes2 |= facialHair;
16294 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
16296 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
16297 player_bytes3 &= ~0xFF;
16298 player_bytes3 |= gender;
16299 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
16301 SaveValuesArrayInDB(tokens, guid);
16304 void Player::SendAttackSwingNotStanding()
16306 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
16307 GetSession()->SendPacket( &data );
16310 void Player::SendAttackSwingDeadTarget()
16312 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16313 GetSession()->SendPacket( &data );
16316 void Player::SendAttackSwingCantAttack()
16318 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16319 GetSession()->SendPacket( &data );
16322 void Player::SendAttackSwingCancelAttack()
16324 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16325 GetSession()->SendPacket( &data );
16328 void Player::SendAttackSwingBadFacingAttack()
16330 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16331 GetSession()->SendPacket( &data );
16334 void Player::SendAutoRepeatCancel()
16336 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
16337 data.append(GetPackGUID()); // may be it's target guid
16338 GetSession()->SendPacket( &data );
16341 void Player::PlaySound(uint32 Sound, bool OnlySelf)
16343 WorldPacket data(SMSG_PLAY_SOUND, 4);
16344 data << Sound;
16345 if (OnlySelf)
16346 GetSession()->SendPacket( &data );
16347 else
16348 SendMessageToSet( &data, true );
16351 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16353 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16354 data << Area;
16355 data << Experience;
16356 GetSession()->SendPacket(&data);
16359 void Player::SendDungeonDifficulty(bool IsInGroup)
16361 uint8 val = 0x00000001;
16362 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16363 data << (uint32)GetDifficulty();
16364 data << uint32(val);
16365 data << uint32(IsInGroup);
16366 GetSession()->SendPacket(&data);
16369 void Player::SendResetFailedNotify(uint32 mapid)
16371 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16372 data << uint32(mapid);
16373 GetSession()->SendPacket(&data);
16376 /// Reset all solo instances and optionally send a message on success for each
16377 void Player::ResetInstances(uint8 method)
16379 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16381 // we assume that when the difficulty changes, all instances that can be reset will be
16382 uint8 dif = GetDifficulty();
16384 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16386 InstanceSave *p = itr->second.save;
16387 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16388 if(!entry || !p->CanReset())
16390 ++itr;
16391 continue;
16394 if(method == INSTANCE_RESET_ALL)
16396 // the "reset all instances" method can only reset normal maps
16397 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16399 ++itr;
16400 continue;
16404 // if the map is loaded, reset it
16405 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16406 if(map && map->IsDungeon())
16407 ((InstanceMap*)map)->Reset(method);
16409 // since this is a solo instance there should not be any players inside
16410 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16411 SendResetInstanceSuccess(p->GetMapId());
16413 p->DeleteFromDB();
16414 m_boundInstances[dif].erase(itr++);
16416 // the following should remove the instance save from the manager and delete it as well
16417 p->RemovePlayer(this);
16421 void Player::SendResetInstanceSuccess(uint32 MapId)
16423 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16424 data << MapId;
16425 GetSession()->SendPacket(&data);
16428 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16430 // TODO: find what other fail reasons there are besides players in the instance
16431 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16432 data << reason;
16433 data << MapId;
16434 GetSession()->SendPacket(&data);
16437 /*********************************************************/
16438 /*** Update timers ***/
16439 /*********************************************************/
16441 ///checks the 15 afk reports per 5 minutes limit
16442 void Player::UpdateAfkReport(time_t currTime)
16444 if(m_bgAfkReportedTimer <= currTime)
16446 m_bgAfkReportedCount = 0;
16447 m_bgAfkReportedTimer = currTime+5*MINUTE;
16451 void Player::UpdateContestedPvP(uint32 diff)
16453 if(!m_contestedPvPTimer||isInCombat())
16454 return;
16455 if(m_contestedPvPTimer <= diff)
16457 ResetContestedPvP();
16459 else
16460 m_contestedPvPTimer -= diff;
16463 void Player::UpdatePvPFlag(time_t currTime)
16465 if(!IsPvP())
16466 return;
16467 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16468 return;
16470 UpdatePvP(false);
16473 void Player::UpdateDuelFlag(time_t currTime)
16475 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16476 return;
16478 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16479 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16481 duel->startTimer = 0;
16482 duel->startTime = currTime;
16483 duel->opponent->duel->startTimer = 0;
16484 duel->opponent->duel->startTime = currTime;
16487 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16489 if(!pet)
16490 pet = GetPet();
16492 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16494 //returning of reagents only for players, so best done here
16495 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16496 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16498 if(spellInfo)
16500 for(uint32 i = 0; i < 7; ++i)
16502 if(spellInfo->Reagent[i] > 0)
16504 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16505 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16506 if( msg == EQUIP_ERR_OK )
16508 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16509 if(IsInWorld())
16510 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16515 m_temporaryUnsummonedPetNumber = 0;
16518 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16519 return;
16521 // only if current pet in slot
16522 switch(pet->getPetType())
16524 case MINI_PET:
16525 m_miniPet = 0;
16526 break;
16527 case GUARDIAN_PET:
16528 m_guardianPets.erase(pet->GetGUID());
16529 break;
16530 default:
16531 if(GetPetGUID() == pet->GetGUID())
16532 SetPet(NULL);
16533 break;
16536 pet->CombatStop();
16538 if(returnreagent)
16540 switch(pet->GetEntry())
16542 //warlock pets except imp are removed(?) when logging out
16543 case 1860:
16544 case 1863:
16545 case 417:
16546 case 17252:
16547 mode = PET_SAVE_NOT_IN_SLOT;
16548 break;
16552 pet->SavePetToDB(mode);
16554 pet->CleanupsBeforeDelete();
16555 pet->AddObjectToRemoveList();
16556 pet->m_removed = true;
16558 if(pet->isControlled())
16560 WorldPacket data(SMSG_PET_SPELLS, 8);
16561 data << uint64(0);
16562 data << uint32(0);
16563 GetSession()->SendPacket(&data);
16565 if(GetGroup())
16566 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16570 void Player::RemoveMiniPet()
16572 if(Pet* pet = GetMiniPet())
16574 pet->Remove(PET_SAVE_AS_DELETED);
16575 m_miniPet = 0;
16579 Pet* Player::GetMiniPet()
16581 if(!m_miniPet)
16582 return NULL;
16583 return ObjectAccessor::GetPet(m_miniPet);
16586 void Player::RemoveGuardians()
16588 while(!m_guardianPets.empty())
16590 uint64 guid = *m_guardianPets.begin();
16591 if(Pet* pet = ObjectAccessor::GetPet(guid))
16592 pet->Remove(PET_SAVE_AS_DELETED);
16594 m_guardianPets.erase(guid);
16598 bool Player::HasGuardianWithEntry(uint32 entry)
16600 // pet guid middle part is entry (and creature also)
16601 // and in guardian list must be guardians with same entry _always_
16602 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16603 if(GUID_ENPART(*itr)==entry)
16604 return true;
16606 return false;
16609 void Player::Uncharm()
16611 Unit* charm = GetCharm();
16612 if(!charm)
16613 return;
16615 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16616 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16619 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16621 *data << (uint8)msgtype;
16622 *data << (uint32)language;
16623 *data << (uint64)GetGUID();
16624 *data << (uint32)language; //language 2.1.0 ?
16625 *data << (uint64)GetGUID();
16626 *data << (uint32)(text.length()+1);
16627 *data << text;
16628 *data << (uint8)chatTag();
16631 void Player::Say(const std::string& text, const uint32 language)
16633 WorldPacket data(SMSG_MESSAGECHAT, 200);
16634 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16635 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16638 void Player::Yell(const std::string& text, const uint32 language)
16640 WorldPacket data(SMSG_MESSAGECHAT, 200);
16641 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16642 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16645 void Player::TextEmote(const std::string& text)
16647 WorldPacket data(SMSG_MESSAGECHAT, 200);
16648 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16649 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16652 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16654 if (language != LANG_ADDON) // if not addon data
16655 language = LANG_UNIVERSAL; // whispers should always be readable
16657 Player *rPlayer = objmgr.GetPlayer(receiver);
16659 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16660 if(!rPlayer->isDND() || isGameMaster())
16662 WorldPacket data(SMSG_MESSAGECHAT, 200);
16663 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16664 rPlayer->GetSession()->SendPacket(&data);
16666 data.Initialize(SMSG_MESSAGECHAT, 200);
16667 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16668 GetSession()->SendPacket(&data);
16670 else
16672 // announce to player that player he is whispering to is dnd and cannot receive his message
16673 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16676 if(!isAcceptWhispers())
16678 SetAcceptWhispers(true);
16679 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16682 // announce to player that player he is whispering to is afk
16683 if(rPlayer->isAFK())
16684 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16686 // if player whisper someone, auto turn of dnd to be able to receive an answer
16687 if(isDND() && !rPlayer->isGameMaster())
16688 ToggleDND();
16691 void Player::PetSpellInitialize()
16693 Pet* pet = GetPet();
16695 if(!pet)
16696 return;
16698 sLog.outDebug("Pet Spells Groups");
16700 CharmInfo *charmInfo = pet->GetCharmInfo();
16702 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16703 data << uint64(pet->GetGUID());
16704 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16705 data << uint32(0);
16706 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16708 // action bar loop
16709 for(uint32 i = 0; i < 10; i++)
16711 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16714 size_t spellsCountPos = data.wpos();
16716 // spells count
16717 uint8 addlist = 0;
16718 data << uint8(addlist); // placeholder
16720 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16722 // spells loop
16723 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16725 if(itr->second->state == PETSPELL_REMOVED)
16726 continue;
16728 data << uint16(itr->first);
16729 data << uint16(itr->second->active); // pet spell active state isn't boolean
16730 ++addlist;
16734 data.put<uint8>(spellsCountPos, addlist);
16736 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16737 data << uint8(cooldownsCount);
16739 time_t curTime = time(NULL);
16741 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16743 time_t cooldown = 0;
16745 if(itr->second > curTime)
16746 cooldown = (itr->second - curTime) * IN_MILISECONDS;
16748 data << uint16(itr->first); // spellid
16749 data << uint16(0); // spell category?
16750 data << uint32(itr->second); // cooldown
16751 data << uint32(0); // category cooldown
16754 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16756 time_t cooldown = 0;
16758 if(itr->second > curTime)
16759 cooldown = (itr->second - curTime) * IN_MILISECONDS;
16761 data << uint16(itr->first); // spellid
16762 data << uint16(0); // spell category?
16763 data << uint32(0); // cooldown
16764 data << uint32(itr->second); // category cooldown
16767 GetSession()->SendPacket(&data);
16770 void Player::PossessSpellInitialize()
16772 Unit* charm = GetCharm();
16774 if(!charm)
16775 return;
16777 CharmInfo *charmInfo = charm->GetCharmInfo();
16779 if(!charmInfo)
16781 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16782 return;
16785 uint8 addlist = 0;
16786 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16788 //16
16789 data << uint64(charm->GetGUID());
16790 data << uint32(0x00000000);
16791 data << uint32(0);
16792 data << uint8(0) << uint8(0) << uint16(0);
16794 for(uint32 i = 0; i < 10; i++) //40
16796 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16799 data << uint8(addlist); //1
16801 uint8 count = 0;
16802 data << uint8(count); // cooldowns count
16804 GetSession()->SendPacket(&data);
16807 void Player::CharmSpellInitialize()
16809 Unit* charm = GetCharm();
16811 if(!charm)
16812 return;
16814 CharmInfo *charmInfo = charm->GetCharmInfo();
16815 if(!charmInfo)
16817 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16818 return;
16821 uint8 addlist = 0;
16823 if(charm->GetTypeId() != TYPEID_PLAYER)
16825 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16827 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16829 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16831 if(charmInfo->GetCharmSpell(i)->spellId)
16832 ++addlist;
16837 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16839 data << uint64(charm->GetGUID());
16840 data << uint32(0x00000000);
16841 data << uint32(0);
16842 if(charm->GetTypeId() != TYPEID_PLAYER)
16843 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16844 else
16845 data << uint8(0) << uint8(0);
16846 data << uint16(0);
16848 for(uint32 i = 0; i < 10; i++) //40
16850 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16853 data << uint8(addlist); //1
16855 if(addlist)
16857 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16859 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16860 if(cspell->spellId)
16862 data << uint16(cspell->spellId);
16863 data << uint16(cspell->active);
16868 uint8 count = 0;
16869 data << uint8(count); // cooldowns count
16871 GetSession()->SendPacket(&data);
16874 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16876 if (!mod || !spellInfo)
16877 return false;
16879 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16881 // prevent apply to any spell except spell that trigger expire
16882 if(spell)
16884 if(mod->lastAffected != spell)
16885 return false;
16887 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16888 return false;
16891 return spellmgr.IsAffectedByMod(spellInfo, mod);
16894 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16896 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16898 for(int eff=0;eff<96;++eff)
16900 uint64 _mask = 0;
16901 uint64 _mask2= 0;
16902 if (eff<64) _mask = uint64(1) << (eff- 0);
16903 else _mask2= uint64(1) << (eff-64);
16904 if ( mod->mask & _mask || mod->mask2 & _mask2)
16906 int32 val = 0;
16907 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16909 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16910 val += (*itr)->value;
16912 val += apply ? mod->value : -(mod->value);
16913 WorldPacket data(Opcode, (1+1+4));
16914 data << uint8(eff);
16915 data << uint8(mod->op);
16916 data << int32(val);
16917 SendDirectMessage(&data);
16921 if (apply)
16922 m_spellMods[mod->op].push_back(mod);
16923 else
16925 if (mod->charges == -1)
16926 --m_SpellModRemoveCount;
16927 m_spellMods[mod->op].remove(mod);
16928 delete mod;
16932 void Player::RemoveSpellMods(Spell const* spell)
16934 if(!spell || (m_SpellModRemoveCount == 0))
16935 return;
16937 for(int i=0;i<MAX_SPELLMOD;++i)
16939 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16941 SpellModifier *mod = *itr;
16942 ++itr;
16944 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16946 RemoveAurasDueToSpell(mod->spellId);
16947 if (m_spellMods[i].empty())
16948 break;
16949 else
16950 itr = m_spellMods[i].begin();
16956 // send Proficiency
16957 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16959 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16960 data << pr1 << pr2;
16961 GetSession()->SendPacket (&data);
16964 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16966 QueryResult *result = NULL;
16967 if(type==10)
16968 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16969 else
16970 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16971 if(result)
16973 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.
16974 { // and SendPetitionQueryOpcode reads data from the DB
16975 Field *fields = result->Fetch();
16976 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16977 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16979 // send update if charter owner in game
16980 Player* owner = objmgr.GetPlayer(ownerguid);
16981 if(owner)
16982 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16984 } while ( result->NextRow() );
16986 delete result;
16988 if(type==10)
16989 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16990 else
16991 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16994 CharacterDatabase.BeginTransaction();
16995 if(type == 10)
16997 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16998 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
17000 else
17002 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17003 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17005 CharacterDatabase.CommitTransaction();
17008 void Player::LeaveAllArenaTeams(uint64 guid)
17010 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));
17011 if(!result)
17012 return;
17016 Field *fields = result->Fetch();
17017 uint32 at_id = fields[0].GetUInt32();
17018 if(at_id != 0)
17020 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
17021 if(at)
17022 at->DelMember(guid);
17024 } while (result->NextRow());
17026 delete result;
17029 void Player::SetRestBonus (float rest_bonus_new)
17031 // Prevent resting on max level
17032 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
17033 rest_bonus_new = 0;
17035 if(rest_bonus_new < 0)
17036 rest_bonus_new = 0;
17038 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
17040 if(rest_bonus_new > rest_bonus_max)
17041 m_rest_bonus = rest_bonus_max;
17042 else
17043 m_rest_bonus = rest_bonus_new;
17045 // update data for client
17046 if(m_rest_bonus>10)
17047 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
17048 else if(m_rest_bonus<=1)
17049 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
17051 //RestTickUpdate
17052 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
17055 void Player::HandleStealthedUnitsDetection()
17057 std::list<Unit*> stealthedUnits;
17059 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17060 Cell cell(p);
17061 cell.data.Part.reserved = ALL_DISTRICT;
17062 cell.SetNoCreate();
17064 MaNGOS::AnyStealthedCheck u_check;
17065 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
17067 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
17068 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
17070 CellLock<GridReadGuard> cell_lock(cell, p);
17071 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
17072 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
17074 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
17076 if((*i)==this)
17078 i = stealthedUnits.erase(i);
17079 continue;
17082 if ((*i)->isVisibleForOrDetect(this,true))
17085 (*i)->SendUpdateToPlayer(this);
17086 m_clientGUIDs.insert((*i)->GetGUID());
17088 #ifdef MANGOS_DEBUG
17089 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17090 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
17091 #endif
17093 // target aura duration for caster show only if target exist at caster client
17094 // send data at target visibility change (adding to client)
17095 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
17096 SendAurasForTarget(*i);
17098 i = stealthedUnits.erase(i);
17099 continue;
17102 ++i;
17106 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
17108 if(nodes.size() < 2)
17109 return false;
17111 // not let cheating with start flight mounted
17112 if(IsMounted())
17114 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17115 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
17116 GetSession()->SendPacket(&data);
17117 return false;
17120 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17122 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17123 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
17124 GetSession()->SendPacket(&data);
17125 return false;
17128 // 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
17129 if(GetSession()->isLogingOut() ||
17130 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
17131 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
17132 IsNonMeleeSpellCasted(false) ||
17133 isInCombat())
17135 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17136 data << uint32(ERR_TAXIPLAYERBUSY);
17137 GetSession()->SendPacket(&data);
17138 return false;
17141 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
17142 return false;
17144 uint32 sourcenode = nodes[0];
17146 // starting node too far away (cheat?)
17147 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
17148 if( !node || node->map_id != GetMapId() ||
17149 (node->x - GetPositionX())*(node->x - GetPositionX())+
17150 (node->y - GetPositionY())*(node->y - GetPositionY())+
17151 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
17152 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
17154 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17155 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17156 GetSession()->SendPacket(&data);
17157 return false;
17160 // Prepare to flight start now
17162 // stop combat at start taxi flight if any
17163 CombatStop();
17165 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17166 TradeCancel(true);
17168 // clean not finished taxi path if any
17169 m_taxi.ClearTaxiDestinations();
17171 // 0 element current node
17172 m_taxi.AddTaxiDestination(sourcenode);
17174 // fill destinations path tail
17175 uint32 sourcepath = 0;
17176 uint32 totalcost = 0;
17178 uint32 prevnode = sourcenode;
17179 uint32 lastnode = 0;
17181 for(uint32 i = 1; i < nodes.size(); ++i)
17183 uint32 path, cost;
17185 lastnode = nodes[i];
17186 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
17188 if(!path)
17190 m_taxi.ClearTaxiDestinations();
17191 return false;
17194 totalcost += cost;
17196 if(prevnode == sourcenode)
17197 sourcepath = path;
17199 m_taxi.AddTaxiDestination(lastnode);
17201 prevnode = lastnode;
17204 if(!mount_id) // if not provide then attempt use default.
17205 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
17207 if (mount_id == 0 || sourcepath == 0)
17209 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17210 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17211 GetSession()->SendPacket(&data);
17212 m_taxi.ClearTaxiDestinations();
17213 return false;
17216 uint32 money = GetMoney();
17218 if(npc)
17220 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17223 if(money < totalcost)
17225 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17226 data << uint32(ERR_TAXINOTENOUGHMONEY);
17227 GetSession()->SendPacket(&data);
17228 m_taxi.ClearTaxiDestinations();
17229 return false;
17232 //Checks and preparations done, DO FLIGHT
17233 ModifyMoney(-(int32)totalcost);
17235 // prevent stealth flight
17236 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17238 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17239 data << uint32(ERR_TAXIOK);
17240 GetSession()->SendPacket(&data);
17242 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17244 GetSession()->SendDoFlight(mount_id, sourcepath);
17246 return true;
17249 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17251 // last check 2.0.10
17252 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17253 data << GetGUID();
17254 data << uint8(0x0); // flags (0x1, 0x2)
17255 time_t curTime = time(NULL);
17256 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17258 if (itr->second->state == PLAYERSPELL_REMOVED)
17259 continue;
17260 uint32 unSpellId = itr->first;
17261 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17262 if (!spellInfo)
17264 ASSERT(spellInfo);
17265 continue;
17268 // Not send cooldown for this spells
17269 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17270 continue;
17272 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17274 data << unSpellId;
17275 data << unTimeMs; // in m.secs
17276 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17279 GetSession()->SendPacket(&data);
17282 void Player::InitDataForForm(bool reapplyMods)
17284 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17285 if(ssEntry && ssEntry->attackSpeed)
17287 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17288 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17289 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17291 else
17292 SetRegularAttackTime();
17294 switch(m_form)
17296 case FORM_CAT:
17298 if(getPowerType()!=POWER_ENERGY)
17299 setPowerType(POWER_ENERGY);
17300 break;
17302 case FORM_BEAR:
17303 case FORM_DIREBEAR:
17305 if(getPowerType()!=POWER_RAGE)
17306 setPowerType(POWER_RAGE);
17307 break;
17309 default: // 0, for example
17311 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17312 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17313 setPowerType(Powers(cEntry->powerType));
17314 break;
17318 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17319 if (!reapplyMods)
17320 UpdateEquipSpellsAtFormChange();
17322 UpdateAttackPowerAndDamage();
17323 UpdateAttackPowerAndDamage(true);
17326 // Return true is the bought item has a max count to force refresh of window by caller
17327 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
17329 // cheating attempt
17330 if(count < 1) count = 1;
17332 if(!isAlive())
17333 return false;
17335 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
17336 if( !pProto )
17338 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17339 return false;
17342 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
17343 if (!pCreature)
17345 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17346 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17347 return false;
17350 VendorItemData const* vItems = pCreature->GetVendorItems();
17351 if(!vItems || vItems->Empty())
17353 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17354 return false;
17357 size_t vendor_slot = vItems->FindItemSlot(item);
17358 if(vendor_slot >= vItems->GetItemCount())
17360 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17361 return false;
17364 VendorItem const* crItem = vItems->m_items[vendor_slot];
17366 // check current item amount if it limited
17367 if( crItem->maxcount != 0 )
17369 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17371 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17372 return false;
17376 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17378 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17379 return false;
17382 if(crItem->ExtendedCost)
17384 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17385 if(!iece)
17387 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17388 return false;
17391 // honor points price
17392 if(GetHonorPoints() < (iece->reqhonorpoints * count))
17394 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17395 return false;
17398 // arena points price
17399 if(GetArenaPoints() < (iece->reqarenapoints * count))
17401 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17402 return false;
17405 // item base price
17406 for (uint8 i = 0; i < 5; ++i)
17408 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17410 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17411 return false;
17415 // check for personal arena rating requirement
17416 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17418 // probably not the proper equip err
17419 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17420 return false;
17424 uint32 price = pProto->BuyPrice * count;
17426 // reputation discount
17427 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17429 if( GetMoney() < price )
17431 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17432 return false;
17435 uint8 bag = 0; // init for case invalid bagGUID
17437 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17439 Bag *pBag;
17440 if( bagguid == GetGUID() )
17442 bag = INVENTORY_SLOT_BAG_0;
17444 else
17446 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
17448 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17449 if( pBag )
17451 if( bagguid == pBag->GetGUID() )
17453 bag = i;
17454 break;
17461 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17463 ItemPosCountVec dest;
17464 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17465 if( msg != EQUIP_ERR_OK )
17467 SendEquipError( msg, NULL, NULL );
17468 return false;
17471 ModifyMoney( -(int32)price );
17472 if(crItem->ExtendedCost) // case for new honor system
17474 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17475 if(iece->reqhonorpoints)
17476 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17477 if(iece->reqarenapoints)
17478 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17479 for (uint8 i = 0; i < 5; ++i)
17481 if(iece->reqitem[i])
17482 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17486 if(Item *it = StoreNewItem( dest, item, true ))
17488 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17490 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17491 data << pCreature->GetGUID();
17492 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17493 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17494 data << (uint32)count;
17495 GetSession()->SendPacket(&data);
17497 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17500 else if( IsEquipmentPos( bag, slot ) )
17502 if(pProto->BuyCount * count != 1)
17504 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17505 return false;
17508 uint16 dest;
17509 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17510 if( msg != EQUIP_ERR_OK )
17512 SendEquipError( msg, NULL, NULL );
17513 return false;
17516 ModifyMoney( -(int32)price );
17517 if(crItem->ExtendedCost) // case for new honor system
17519 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17520 if(iece->reqhonorpoints)
17521 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17522 if(iece->reqarenapoints)
17523 ModifyArenaPoints( - int32(iece->reqarenapoints));
17524 for (uint8 i = 0; i < 5; ++i)
17526 if(iece->reqitem[i])
17527 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17531 if(Item *it = EquipNewItem( dest, item, true ))
17533 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17535 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17536 data << pCreature->GetGUID();
17537 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17538 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17539 data << (uint32)count;
17540 GetSession()->SendPacket(&data);
17542 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17544 AutoUnequipOffhandIfNeed();
17547 else
17549 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17550 return false;
17553 return crItem->maxcount!=0;
17556 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17558 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17559 // the personal rating of the arena team must match the required limit as well
17560 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17561 uint32 max_personal_rating = 0;
17562 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17564 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17566 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17567 uint32 t_rating = at->GetRating();
17568 p_rating = p_rating<t_rating? p_rating : t_rating;
17569 if(max_personal_rating < p_rating)
17570 max_personal_rating = p_rating;
17573 return max_personal_rating;
17576 void Player::UpdateHomebindTime(uint32 time)
17578 // GMs never get homebind timer online
17579 if (m_InstanceValid || isGameMaster())
17581 if(m_HomebindTimer) // instance valid, but timer not reset
17583 // hide reminder
17584 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17585 data << uint32(0);
17586 data << uint32(0);
17587 GetSession()->SendPacket(&data);
17589 // instance is valid, reset homebind timer
17590 m_HomebindTimer = 0;
17592 else if (m_HomebindTimer > 0)
17594 if (time >= m_HomebindTimer)
17596 // teleport to homebind location
17597 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17599 else
17600 m_HomebindTimer -= time;
17602 else
17604 // instance is invalid, start homebind timer
17605 m_HomebindTimer = 60000;
17606 // send message to player
17607 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17608 data << m_HomebindTimer;
17609 data << uint32(1);
17610 GetSession()->SendPacket(&data);
17611 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17615 void Player::UpdatePvP(bool state, bool ovrride)
17617 if(!state || ovrride)
17619 SetPvP(state);
17620 if(Pet* pet = GetPet())
17621 pet->SetPvP(state);
17622 if(Unit* charmed = GetCharm())
17623 charmed->SetPvP(state);
17625 pvpInfo.endTimer = 0;
17627 else
17629 if(pvpInfo.endTimer != 0)
17630 pvpInfo.endTimer = time(NULL);
17631 else
17633 SetPvP(state);
17635 if(Pet* pet = GetPet())
17636 pet->SetPvP(state);
17637 if(Unit* charmed = GetCharm())
17638 charmed->SetPvP(state);
17643 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17645 // init cooldown values
17646 uint32 cat = 0;
17647 int32 rec = -1;
17648 int32 catrec = -1;
17650 // some special item spells without correct cooldown in SpellInfo
17651 // cooldown information stored in item prototype
17652 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17654 if(itemId)
17656 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17658 for(int idx = 0; idx < 5; ++idx)
17660 if(proto->Spells[idx].SpellId == spellInfo->Id)
17662 cat = proto->Spells[idx].SpellCategory;
17663 rec = proto->Spells[idx].SpellCooldown;
17664 catrec = proto->Spells[idx].SpellCategoryCooldown;
17665 break;
17671 // if no cooldown found above then base at DBC data
17672 if(rec < 0 && catrec < 0)
17674 cat = spellInfo->Category;
17675 rec = spellInfo->RecoveryTime;
17676 catrec = spellInfo->CategoryRecoveryTime;
17679 time_t curTime = time(NULL);
17681 time_t catrecTime;
17682 time_t recTime;
17684 // overwrite time for selected category
17685 if(infinityCooldown)
17687 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17688 // but not allow ignore until reset or re-login
17689 catrecTime = catrec > 0 ? curTime+MONTH : 0;
17690 recTime = rec > 0 ? curTime+MONTH : catrecTime;
17692 else
17694 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17695 // prevent 0 cooldowns set by another way
17696 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17697 rec = GetAttackTime(RANGED_ATTACK);
17699 // Now we have cooldown data (if found any), time to apply mods
17700 if(rec > 0)
17701 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17703 if(catrec > 0)
17704 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17706 // replace negative cooldowns by 0
17707 if (rec < 0) rec = 0;
17708 if (catrec < 0) catrec = 0;
17710 // no cooldown after applying spell mods
17711 if( rec == 0 && catrec == 0)
17712 return;
17714 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17715 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17718 // self spell cooldown
17719 if(recTime > 0)
17720 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17722 // category spells
17723 if (cat && catrec > 0)
17725 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17726 if(i_scstore != sSpellCategoryStore.end())
17728 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17730 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17731 continue;
17733 AddSpellCooldown(*i_scset, itemId, catrecTime);
17739 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17741 SpellCooldown sc;
17742 sc.end = end_time;
17743 sc.itemid = itemid;
17744 m_spellCooldowns[spellid] = sc;
17747 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17749 // start cooldowns at server side, if any
17750 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17752 // Send activate cooldown timer (possible 0) at client side
17753 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17754 data << spellInfo->Id;
17755 data << GetGUID();
17756 SendDirectMessage(&data);
17759 void Player::UpdatePotionCooldown(Spell* spell)
17761 // no potion used i combat or still in combat
17762 if(!m_lastPotionId || isInCombat())
17763 return;
17765 // Call not from spell cast, send cooldown event for item spells if no in combat
17766 if(!spell)
17768 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17769 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17770 for(int idx = 0; idx < 5; ++idx)
17771 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17772 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17773 SendCooldownEvent(spellInfo,m_lastPotionId);
17775 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17776 else
17777 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17779 m_lastPotionId = 0;
17782 //slot to be excluded while counting
17783 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17785 if(!enchantmentcondition)
17786 return true;
17788 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17790 if(!Condition)
17791 return true;
17793 uint8 curcount[4] = {0, 0, 0, 0};
17795 //counting current equipped gem colors
17796 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17798 if(i == slot)
17799 continue;
17800 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17801 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17803 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17805 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17806 if(!enchant_id)
17807 continue;
17809 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17810 if(!enchantEntry)
17811 continue;
17813 uint32 gemid = enchantEntry->GemID;
17814 if(!gemid)
17815 continue;
17817 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17818 if(!gemProto)
17819 continue;
17821 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17822 if(!gemProperty)
17823 continue;
17825 uint8 GemColor = gemProperty->color;
17827 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17829 if(tmpcolormask & GemColor)
17830 ++curcount[b];
17836 bool activate = true;
17838 for(int i = 0; i < 5; i++)
17840 if(!Condition->Color[i])
17841 continue;
17843 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17845 // if have <CompareColor> use them as count, else use <value> from Condition
17846 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17848 switch(Condition->Comparator[i])
17850 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17851 activate &= (_cur_gem < _cmp_gem) ? true : false;
17852 break;
17853 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17854 activate &= (_cur_gem > _cmp_gem) ? true : false;
17855 break;
17856 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17857 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17858 break;
17862 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");
17864 return activate;
17867 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17869 //cycle all equipped items
17870 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17872 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17873 if(slot == exceptslot)
17874 continue;
17876 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17878 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17879 continue;
17881 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17883 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17884 if(!enchant_id)
17885 continue;
17887 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17888 if(!enchantEntry)
17889 continue;
17891 uint32 condition = enchantEntry->EnchantmentCondition;
17892 if(condition)
17894 //was enchant active with/without item?
17895 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17896 //should it now be?
17897 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17899 // ignore item gem conditions
17900 //if state changed, (dis)apply enchant
17901 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17908 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17909 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17911 //cycle all equipped items
17912 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17914 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17915 if(slot == exceptslot)
17916 continue;
17918 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17920 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17921 continue;
17923 //cycle all (gem)enchants
17924 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17926 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17927 if(!enchant_id) //if no enchant go to next enchant(slot)
17928 continue;
17930 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17931 if(!enchantEntry)
17932 continue;
17934 //only metagems to be (de)activated, so only enchants with condition
17935 uint32 condition = enchantEntry->EnchantmentCondition;
17936 if(condition)
17937 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17942 void Player::LeaveBattleground(bool teleportToEntryPoint)
17944 if(BattleGround *bg = GetBattleGround())
17946 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
17948 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17950 // call after remove to be sure that player resurrected for correct cast
17951 if(need_debuf)
17952 CastSpell(this, 26013, true); // Deserter
17956 bool Player::CanJoinToBattleground() const
17958 // check Deserter debuff
17959 if(GetDummyAura(26013))
17960 return false;
17962 return true;
17965 bool Player::CanReportAfkDueToLimit()
17967 // a player can complain about 15 people per 5 minutes
17968 if(m_bgAfkReportedCount >= 15)
17969 return false;
17970 ++m_bgAfkReportedCount;
17971 return true;
17974 ///This player has been blamed to be inactive in a battleground
17975 void Player::ReportedAfkBy(Player* reporter)
17977 BattleGround *bg = GetBattleGround();
17978 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17979 return;
17981 // check if player has 'Idle' or 'Inactive' debuff
17982 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17984 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17985 // 3 players have to complain to apply debuff
17986 if(m_bgAfkReporter.size() >= 3)
17988 // cast 'Idle' spell
17989 CastSpell(this, 43680, true);
17990 m_bgAfkReporter.clear();
17995 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17997 // gamemaster in GM mode see all, including ghosts
17998 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17999 return true;
18001 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
18002 if (InBattleGround())
18004 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
18005 return false;
18006 return true;
18009 // Live player see live player or dead player with not realized corpse
18010 if(pl->isAlive() || pl->m_deathTimer > 0)
18012 return isAlive() || m_deathTimer > 0;
18015 // Ghost see other friendly ghosts, that's for sure
18016 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
18017 return true;
18019 // Dead player see live players near own corpse
18020 if(isAlive())
18022 Corpse *corpse = pl->GetCorpse();
18023 if(corpse)
18025 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
18026 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
18027 return true;
18031 // and not see any other
18032 return false;
18035 bool Player::IsVisibleGloballyFor( Player* u ) const
18037 if(!u)
18038 return false;
18040 // Always can see self
18041 if (u==this)
18042 return true;
18044 // Visible units, always are visible for all players
18045 if (GetVisibility() == VISIBILITY_ON)
18046 return true;
18048 // GMs are visible for higher gms (or players are visible for gms)
18049 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
18050 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
18052 // non faction visibility non-breakable for non-GMs
18053 if (GetVisibility() == VISIBILITY_OFF)
18054 return false;
18056 // non-gm stealth/invisibility not hide from global player lists
18057 return true;
18060 void Player::UpdateVisibilityOf(WorldObject* target)
18062 if(HaveAtClient(target))
18064 if(!target->isVisibleForInState(this,true))
18066 target->DestroyForPlayer(this);
18067 m_clientGUIDs.erase(target->GetGUID());
18069 #ifdef MANGOS_DEBUG
18070 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18071 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18072 #endif
18075 else
18077 if(target->isVisibleForInState(this,false))
18079 target->SendUpdateToPlayer(this);
18080 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
18081 m_clientGUIDs.insert(target->GetGUID());
18083 #ifdef MANGOS_DEBUG
18084 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18085 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18086 #endif
18088 // target aura duration for caster show only if target exist at caster client
18089 // send data at target visibility change (adding to client)
18090 if(target!=this && target->isType(TYPEMASK_UNIT))
18091 SendAurasForTarget((Unit*)target);
18093 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
18094 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18099 template<class T>
18100 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
18102 s64.insert(target->GetGUID());
18105 template<>
18106 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
18108 if(!target->IsTransport())
18109 s64.insert(target->GetGUID());
18112 template<class T>
18113 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
18115 if(HaveAtClient(target))
18117 if(!target->isVisibleForInState(this,true))
18119 target->BuildOutOfRangeUpdateBlock(&data);
18120 m_clientGUIDs.erase(target->GetGUID());
18122 #ifdef MANGOS_DEBUG
18123 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18124 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));
18125 #endif
18128 else
18130 if(target->isVisibleForInState(this,false))
18132 visibleNow.insert(target);
18133 target->BuildUpdate(data_updates);
18134 target->BuildCreateUpdateBlockForPlayer(&data, this);
18135 UpdateVisibilityOf_helper(m_clientGUIDs,target);
18137 #ifdef MANGOS_DEBUG
18138 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18139 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));
18140 #endif
18145 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18146 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18147 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18148 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18149 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18151 void Player::InitPrimaryProffesions()
18153 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
18156 void Player::SendComboPoints()
18158 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
18159 if (combotarget)
18161 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
18162 data.append(combotarget->GetPackGUID());
18163 data << uint8(m_comboPoints);
18164 GetSession()->SendPacket(&data);
18168 void Player::AddComboPoints(Unit* target, int8 count)
18170 if(!count)
18171 return;
18173 // without combo points lost (duration checked in aura)
18174 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18176 if(target->GetGUID() == m_comboTarget)
18178 m_comboPoints += count;
18180 else
18182 if(m_comboTarget)
18183 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18184 target->RemoveComboPointHolder(GetGUIDLow());
18186 m_comboTarget = target->GetGUID();
18187 m_comboPoints = count;
18189 target->AddComboPointHolder(GetGUIDLow());
18192 if (m_comboPoints > 5) m_comboPoints = 5;
18193 if (m_comboPoints < 0) m_comboPoints = 0;
18195 SendComboPoints();
18198 void Player::ClearComboPoints()
18200 if(!m_comboTarget)
18201 return;
18203 // without combopoints lost (duration checked in aura)
18204 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18206 m_comboPoints = 0;
18208 SendComboPoints();
18210 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18211 target->RemoveComboPointHolder(GetGUIDLow());
18213 m_comboTarget = 0;
18216 void Player::SetGroup(Group *group, int8 subgroup)
18218 if(group == NULL) m_group.unlink();
18219 else
18221 // never use SetGroup without a subgroup unless you specify NULL for group
18222 assert(subgroup >= 0);
18223 m_group.link(group, this);
18224 m_group.setSubGroup((uint8)subgroup);
18228 void Player::SendInitialPacketsBeforeAddToMap()
18230 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
18231 data << uint32(0); // unknown, may be rest state time or experience
18232 GetSession()->SendPacket(&data);
18234 // Homebind
18235 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
18236 data << m_homebindX << m_homebindY << m_homebindZ;
18237 data << (uint32) m_homebindMapId;
18238 data << (uint32) m_homebindZoneId;
18239 GetSession()->SendPacket(&data);
18241 // SMSG_SET_PROFICIENCY
18242 // SMSG_UPDATE_AURA_DURATION
18244 // tutorial stuff
18245 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
18246 for (int i = 0; i < 8; ++i)
18247 data << uint32( GetTutorialInt(i) );
18248 GetSession()->SendPacket(&data);
18250 SendInitialSpells();
18252 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
18253 data << uint32(0); // count, for(count) uint32;
18254 GetSession()->SendPacket(&data);
18256 SendInitialActionButtons();
18257 SendInitialReputations();
18258 m_achievementMgr.SendAllAchievementData();
18259 UpdateZone(GetZoneId());
18260 SendInitWorldStates();
18262 // SMSG_SET_AURA_SINGLE
18264 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
18265 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18266 data << (float)0.01666667f; // game speed
18267 GetSession()->SendPacket( &data );
18269 data.Initialize(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18270 data << uint32(0x00000000); // on blizz it increments periodically
18271 GetSession()->SendPacket(&data);
18273 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18274 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
18275 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
18277 m_mover = this;
18280 void Player::SendInitialPacketsAfterAddToMap()
18282 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18283 data << uint32(0x00000000); // on blizz it increments periodically
18284 GetSession()->SendPacket(&data);
18286 CastSpell(this, 836, true); // LOGINEFFECT
18288 // set some aura effects that send packet to player client after add player to map
18289 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18290 // same auras state lost at far teleport, send it one more time in this case also
18291 static const AuraType auratypes[] =
18293 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18294 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18295 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18297 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18299 Unit::AuraList const& auraList = GetAurasByType(*itr);
18300 if(!auraList.empty())
18301 auraList.front()->ApplyModifier(true,true);
18304 if(HasAuraType(SPELL_AURA_MOD_STUN))
18305 SetMovement(MOVE_ROOT);
18307 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18308 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18310 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
18311 data.append(GetPackGUID());
18312 data << (uint32)2;
18313 SendMessageToSet(&data,true);
18316 SendAurasForTarget(this);
18317 SendEnchantmentDurations(); // must be after add to map
18318 SendItemDurations(); // must be after add to map
18321 void Player::SendUpdateToOutOfRangeGroupMembers()
18323 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18324 return;
18325 if(Group* group = GetGroup())
18326 group->UpdatePlayerOutOfRange(this);
18328 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18329 m_auraUpdateMask = 0;
18330 if(Pet *pet = GetPet())
18331 pet->ResetAuraUpdateMask();
18334 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18336 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18337 data << uint32(mapid);
18338 data << uint8(reason); // transfer abort reason
18339 switch(reason)
18341 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18342 case TRANSFER_ABORT_DIFFICULTY:
18343 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18344 data << uint8(arg);
18345 break;
18347 GetSession()->SendPacket(&data);
18350 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
18352 // type of warning, based on the time remaining until reset
18353 uint32 type;
18354 if(time > 3600)
18355 type = RAID_INSTANCE_WELCOME;
18356 else if(time > 900 && time <= 3600)
18357 type = RAID_INSTANCE_WARNING_HOURS;
18358 else if(time > 300 && time <= 900)
18359 type = RAID_INSTANCE_WARNING_MIN;
18360 else
18361 type = RAID_INSTANCE_WARNING_MIN_SOON;
18362 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
18363 data << uint32(type);
18364 data << uint32(mapid);
18365 data << uint32(time);
18366 GetSession()->SendPacket(&data);
18369 void Player::ApplyEquipCooldown( Item * pItem )
18371 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
18373 _Spell const& spellData = pItem->GetProto()->Spells[i];
18375 // no spell
18376 if( !spellData.SpellId )
18377 continue;
18379 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18380 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18381 continue;
18383 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18385 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18386 data << pItem->GetGUID();
18387 data << uint32(spellData.SpellId);
18388 GetSession()->SendPacket(&data);
18392 void Player::resetSpells()
18394 // not need after this call
18395 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18397 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
18398 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
18401 // make full copy of map (spells removed and marked as deleted at another spell remove
18402 // and we can't use original map for safe iterative with visit each spell at loop end
18403 PlayerSpellMap smap = GetSpellMap();
18405 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18406 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
18408 learnDefaultSpells();
18409 learnQuestRewardedSpells();
18412 void Player::learnDefaultSpells()
18414 // learn default race/class spells
18415 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18416 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18418 uint32 tspell = *itr;
18419 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18420 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18421 addSpell(tspell,true,true,true,false);
18422 else // but send in normal spell in game learn case
18423 learnSpell(tspell,true);
18427 void Player::learnQuestRewardedSpells(Quest const* quest)
18429 uint32 spell_id = quest->GetRewSpellCast();
18431 // skip quests without rewarded spell
18432 if( !spell_id )
18433 return;
18435 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18436 if(!spellInfo)
18437 return;
18439 // check learned spells state
18440 bool found = false;
18441 for(int i=0; i < 3; ++i)
18443 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18445 found = true;
18446 break;
18450 // skip quests with not teaching spell or already known spell
18451 if(!found)
18452 return;
18454 // prevent learn non first rank unknown profession and second specialization for same profession)
18455 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18456 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18458 // not have first rank learned (unlearned prof?)
18459 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18460 if( !HasSpell(first_spell) )
18461 return;
18463 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18464 if(!learnedInfo)
18465 return;
18467 // specialization
18468 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18470 // search other specialization for same prof
18471 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18473 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18474 continue;
18476 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18477 if(!itrInfo)
18478 return;
18480 // compare only specializations
18481 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18482 continue;
18484 // compare same chain spells
18485 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18486 continue;
18488 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18489 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18490 return;
18495 CastSpell( this, spell_id, true);
18498 void Player::learnQuestRewardedSpells()
18500 // learn spells received from quest completing
18501 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18503 // skip no rewarded quests
18504 if(!itr->second.m_rewarded)
18505 continue;
18507 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18508 if( !quest )
18509 continue;
18511 learnQuestRewardedSpells(quest);
18515 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18517 uint32 raceMask = getRaceMask();
18518 uint32 classMask = getClassMask();
18519 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18521 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18522 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18523 continue;
18524 // Check race if set
18525 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18526 continue;
18527 // Check class if set
18528 if (pAbility->classmask && !(pAbility->classmask & classMask))
18529 continue;
18531 if (sSpellStore.LookupEntry(pAbility->spellId))
18533 // need unlearn spell
18534 if (skill_value < pAbility->req_skill_value)
18535 removeSpell(pAbility->spellId);
18536 // need learn
18537 else if (!IsInWorld())
18538 addSpell(pAbility->spellId,true,true,true,false);
18539 else
18540 learnSpell(pAbility->spellId,true);
18545 void Player::SendAurasForTarget(Unit *target)
18547 if(target->GetVisibleAuras()->empty()) // speedup things
18548 return;
18550 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18551 data.append(target->GetPackGUID());
18553 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18554 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18556 for(uint32 j = 0; j < 3; ++j)
18558 if(Aura *aura = target->GetAura(itr->second, j))
18560 data << uint8(aura->GetAuraSlot());
18561 data << uint32(aura->GetId());
18563 if(aura->GetId())
18565 uint8 auraFlags = aura->GetAuraFlags();
18566 // flags
18567 data << uint8(auraFlags);
18568 // level
18569 data << uint8(aura->GetAuraLevel());
18570 // charges
18571 data << uint8(aura->GetAuraCharges());
18573 if(!(auraFlags & AFLAG_NOT_CASTER))
18575 data << uint8(0); // packed GUID of someone (caster?)
18578 if(auraFlags & AFLAG_DURATION) // include aura duration
18580 data << uint32(aura->GetAuraMaxDuration());
18581 data << uint32(aura->GetAuraDuration());
18584 break;
18589 GetSession()->SendPacket(&data);
18592 void Player::SetDailyQuestStatus( uint32 quest_id )
18594 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18596 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18598 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18599 m_lastDailyQuestTime = time(NULL); // last daily quest time
18600 m_DailyQuestChanged = true;
18601 break;
18606 void Player::ResetDailyQuestStatus()
18608 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18609 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18611 // DB data deleted in caller
18612 m_DailyQuestChanged = false;
18613 m_lastDailyQuestTime = 0;
18616 BattleGround* Player::GetBattleGround() const
18618 if(GetBattleGroundId()==0)
18619 return NULL;
18621 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
18624 bool Player::InArena() const
18626 BattleGround *bg = GetBattleGround();
18627 if(!bg || !bg->isArena())
18628 return false;
18630 return true;
18633 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18635 // get a template bg instead of running one
18636 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18637 if(!bg)
18638 return false;
18640 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18641 return false;
18643 return true;
18646 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18648 //returned to hardcoded version of this function, because there is no way to code it dynamic
18649 uint32 level = getLevel();
18650 if( bgTypeId == BATTLEGROUND_AV )
18651 level--;
18653 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18654 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18656 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18657 return QUEUE_ID_MAX_LEVEL_80;
18659 return BGQueueIdBasedOnLevel(queue_id);
18662 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18664 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18665 if(!vendor_faction)
18666 return 1.0f;
18668 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18669 if(rank <= REP_NEUTRAL)
18670 return 1.0f;
18672 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18675 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18677 uint32 racemask = getRaceMask();
18678 uint32 classmask = getClassMask();
18680 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18681 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18682 if(lower==upper)
18683 return true;
18685 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18687 // skip wrong race skills
18688 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18689 continue;
18691 // skip wrong class skills
18692 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18693 continue;
18695 return true;
18698 return false;
18701 bool Player::HasQuestForGO(int32 GOId) const
18703 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18705 uint32 questid = GetQuestSlotQuestId(i);
18706 if ( questid == 0 )
18707 continue;
18709 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18710 if(qs_itr == mQuestStatus.end())
18711 continue;
18713 QuestStatusData const& qs = qs_itr->second;
18715 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18717 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18718 if(!qinfo)
18719 continue;
18721 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18722 continue;
18724 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
18726 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18727 continue;
18729 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18730 return true;
18734 return false;
18737 void Player::UpdateForQuestsGO()
18739 if(m_clientGUIDs.empty())
18740 return;
18742 UpdateData udata;
18743 WorldPacket packet;
18744 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18746 if(IS_GAMEOBJECT_GUID(*itr))
18748 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18749 if(obj)
18750 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18753 udata.BuildPacket(&packet);
18754 GetSession()->SendPacket(&packet);
18757 void Player::SummonIfPossible(bool agree)
18759 if(!agree)
18761 m_summon_expire = 0;
18762 return;
18765 // expire and auto declined
18766 if(m_summon_expire < time(NULL))
18767 return;
18769 // stop taxi flight at summon
18770 if(isInFlight())
18772 GetMotionMaster()->MovementExpired();
18773 m_taxi.ClearTaxiDestinations();
18776 // drop flag at summon
18777 if(BattleGround *bg = GetBattleGround())
18778 bg->EventPlayerDroppedFlag(this);
18780 m_summon_expire = 0;
18782 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18785 void Player::RemoveItemDurations( Item *item )
18787 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18789 if(*itr==item)
18791 m_itemDuration.erase(itr);
18792 break;
18797 void Player::AddItemDurations( Item *item )
18799 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18801 m_itemDuration.push_back(item);
18802 item->SendTimeUpdate(this);
18806 void Player::AutoUnequipOffhandIfNeed()
18808 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18809 if(!offItem)
18810 return;
18812 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18813 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18814 return;
18816 ItemPosCountVec off_dest;
18817 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18818 if( off_msg == EQUIP_ERR_OK )
18820 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18821 StoreItem( off_dest, offItem, true );
18823 else
18825 MailItemsInfo mi;
18826 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18827 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18828 CharacterDatabase.BeginTransaction();
18829 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18830 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18831 CharacterDatabase.CommitTransaction();
18833 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18834 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18838 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18840 if(spellInfo->EquippedItemClass < 0)
18841 return true;
18843 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18844 // for optimize check 2 used cases only
18845 switch(spellInfo->EquippedItemClass)
18847 case ITEM_CLASS_WEAPON:
18849 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18850 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18851 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18852 return true;
18853 break;
18855 case ITEM_CLASS_ARMOR:
18857 // tabard not have dependent spells
18858 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18859 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18860 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18861 return true;
18863 // shields can be equipped to offhand slot
18864 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18865 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18866 return true;
18868 // ranged slot can have some armor subclasses
18869 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18870 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18871 return true;
18873 break;
18875 default:
18876 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18877 break;
18880 return false;
18883 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18885 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18886 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18887 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18888 return true;
18890 // Check no reagent use mask
18891 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18892 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18893 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18894 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18895 return true;
18897 return false;
18900 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18902 AuraMap& auras = GetAuras();
18903 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
18905 Aura* aura = itr->second;
18907 // skip passive (passive item dependent spells work in another way) and not self applied auras
18908 SpellEntry const* spellInfo = aura->GetSpellProto();
18909 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18911 ++itr;
18912 continue;
18915 // skip if not item dependent or have alternative item
18916 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18918 ++itr;
18919 continue;
18922 // no alt item, remove aura, restart check
18923 RemoveAurasDueToSpell(aura->GetId());
18924 itr = auras.begin();
18927 // currently casted spells can be dependent from item
18928 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
18930 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18931 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18932 InterruptSpell(i);
18936 uint32 Player::GetResurrectionSpellId()
18938 // search priceless resurrection possibilities
18939 uint32 prio = 0;
18940 uint32 spell_id = 0;
18941 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18942 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18944 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18945 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18947 switch((*itr)->GetId())
18949 case 20707: spell_id = 3026; break; // rank 1
18950 case 20762: spell_id = 20758; break; // rank 2
18951 case 20763: spell_id = 20759; break; // rank 3
18952 case 20764: spell_id = 20760; break; // rank 4
18953 case 20765: spell_id = 20761; break; // rank 5
18954 case 27239: spell_id = 27240; break; // rank 6
18955 case 47883: spell_id = 47882; break; // rank 7
18956 default:
18957 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
18958 continue;
18961 prio = 3;
18963 // Twisting Nether // prio: 2 (max)
18964 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18966 prio = 2;
18967 spell_id = 23700;
18971 // Reincarnation (passive spell) // prio: 1
18972 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18973 spell_id = 21169;
18975 return spell_id;
18978 // Used in triggers for check "Only to targets that grant experience or honor" req
18979 bool Player::isHonorOrXPTarget(Unit* pVictim)
18981 uint32 v_level = pVictim->getLevel();
18982 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18984 // Victim level less gray level
18985 if(v_level<=k_grey)
18986 return false;
18988 if(pVictim->GetTypeId() == TYPEID_UNIT)
18990 if (((Creature*)pVictim)->isTotem() ||
18991 ((Creature*)pVictim)->isPet() ||
18992 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18993 return false;
18995 return true;
18998 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
19000 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
19002 // prepare data for near group iteration (PvP and !PvP cases)
19003 uint32 xp = 0;
19004 bool honored_kill = false;
19006 if(Group *pGroup = GetGroup())
19008 uint32 count = 0;
19009 uint32 sum_level = 0;
19010 Player* member_with_max_level = NULL;
19011 Player* not_gray_member_with_max_level = NULL;
19013 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
19015 if(member_with_max_level)
19017 /// not get Xp in PvP or no not gray players in group
19018 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
19020 /// skip in check PvP case (for speed, not used)
19021 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
19022 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
19023 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
19025 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19027 Player* pGroupGuy = itr->getSource();
19028 if(!pGroupGuy)
19029 continue;
19031 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
19032 continue; // member (alive or dead) or his corpse at req. distance
19034 // honor can be in PvP and !PvP (racial leader) cases (for alive)
19035 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
19036 honored_kill = true;
19038 // xp and reputation only in !PvP case
19039 if(!PvP)
19041 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
19043 // if is in dungeon then all receive full reputation at kill
19044 // rewarded any alive/dead/near_corpse group member
19045 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
19047 // XP updated only for alive group member
19048 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
19049 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
19051 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
19053 pGroupGuy->GiveXP(itr_xp, pVictim);
19054 if(Pet* pet = pGroupGuy->GetPet())
19055 pet->GivePetXP(itr_xp/2);
19058 // quest objectives updated only for alive group member or dead but with not released body
19059 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19061 // normal creature (not pet/etc) can be only in !PvP case
19062 if(pVictim->GetTypeId()==TYPEID_UNIT)
19063 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
19069 else // if (!pGroup)
19071 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
19073 // honor can be in PvP and !PvP (racial leader) cases
19074 if(RewardHonor(pVictim,1))
19075 honored_kill = true;
19077 // xp and reputation only in !PvP case
19078 if(!PvP)
19080 RewardReputation(pVictim,1);
19081 GiveXP(xp, pVictim);
19083 if(Pet* pet = GetPet())
19084 pet->GivePetXP(xp);
19086 // normal creature (not pet/etc) can be only in !PvP case
19087 if(pVictim->GetTypeId()==TYPEID_UNIT)
19088 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
19091 return xp || honored_kill;
19094 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
19096 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
19097 return true;
19099 if(isAlive())
19100 return false;
19102 Corpse* corpse = GetCorpse();
19103 if(!corpse)
19104 return false;
19106 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
19109 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
19111 Item* item = GetWeaponForAttack(attType,true);
19113 // unarmed only with base attack
19114 if(attType != BASE_ATTACK && !item)
19115 return 0;
19117 // weapon skill or (unarmed for base attack)
19118 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
19119 return GetBaseSkillValue(skill);
19122 void Player::ResurectUsingRequestData()
19124 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
19125 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
19127 ResurrectPlayer(0.0f,false);
19129 if(GetMaxHealth() > m_resurrectHealth)
19130 SetHealth( m_resurrectHealth );
19131 else
19132 SetHealth( GetMaxHealth() );
19134 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
19135 SetPower(POWER_MANA, m_resurrectMana );
19136 else
19137 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
19139 SetPower(POWER_RAGE, 0 );
19141 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
19143 SpawnCorpseBones();
19146 void Player::SetClientControl(Unit* target, uint8 allowMove)
19148 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
19149 data.append(target->GetPackGUID());
19150 data << uint8(allowMove);
19151 GetSession()->SendPacket(&data);
19154 void Player::UpdateZoneDependentAuras( uint32 newZone )
19156 // remove new continent flight forms
19157 if( !IsAllowUseFlyMountsHere() )
19159 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
19160 RemoveSpellsCausingAura(SPELL_AURA_FLY);
19163 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19164 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
19165 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19166 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
19167 if( !HasAura(itr->second->spellId,0) )
19168 CastSpell(this,itr->second->spellId,true);
19171 void Player::UpdateAreaDependentAuras( uint32 newArea )
19173 // remove auras from spells with area limitations
19174 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
19176 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19177 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this)!=0)
19178 RemoveAura(iter);
19179 else
19180 ++iter;
19183 // some auras applied at subzone enter
19184 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
19185 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19186 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
19187 if( !HasAura(itr->second->spellId,0) )
19188 CastSpell(this,itr->second->spellId,true);
19191 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
19193 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19194 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19196 return copseReclaimDelay[0];
19199 time_t now = time(NULL);
19200 // 0..2 full period
19201 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
19202 return copseReclaimDelay[count];
19205 void Player::UpdateCorpseReclaimDelay()
19207 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
19209 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19210 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19211 return;
19213 time_t now = time(NULL);
19214 if(now < m_deathExpireTime)
19216 // full and partly periods 1..3
19217 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
19218 if(count < MAX_DEATH_COUNT)
19219 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19220 else
19221 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19223 else
19224 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19227 void Player::SendCorpseReclaimDelay(bool load)
19229 Corpse* corpse = GetCorpse();
19230 if(!corpse)
19231 return;
19233 uint32 delay;
19234 if(load)
19236 if(corpse->GetGhostTime() > m_deathExpireTime)
19237 return;
19239 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19241 uint32 count;
19242 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19243 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19245 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19246 if(count>=MAX_DEATH_COUNT)
19247 count = MAX_DEATH_COUNT-1;
19249 else
19250 count=0;
19252 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19254 time_t now = time(NULL);
19255 if(now >= expected_time)
19256 return;
19258 delay = expected_time-now;
19260 else
19261 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19263 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19264 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19265 data << uint32(delay*IN_MILISECONDS);
19266 GetSession()->SendPacket( &data );
19269 Player* Player::GetNextRandomRaidMember(float radius)
19271 Group *pGroup = GetGroup();
19272 if(!pGroup)
19273 return NULL;
19275 std::vector<Player*> nearMembers;
19276 nearMembers.reserve(pGroup->GetMembersCount());
19278 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19280 Player* Target = itr->getSource();
19282 // IsHostileTo check duel and controlled by enemy
19283 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19284 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19285 nearMembers.push_back(Target);
19288 if (nearMembers.empty())
19289 return NULL;
19291 uint32 randTarget = urand(0,nearMembers.size()-1);
19292 return nearMembers[randTarget];
19295 PartyResult Player::CanUninviteFromGroup() const
19297 const Group* grp = GetGroup();
19298 if(!grp)
19299 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19301 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19302 return PARTY_RESULT_YOU_NOT_LEADER;
19304 if(InBattleGround())
19305 return PARTY_RESULT_INVITE_RESTRICTED;
19307 return PARTY_RESULT_OK;
19310 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19312 float water_z = m->GetWaterLevel(x,y);
19313 float terrain_z = m->GetHeight(x,y,z, false); // use .map base surface height
19314 uint8 flag1 = m->GetTerrainType(x,y);
19316 //!Underwater check, not in water if underground or above water level - take UC royal quater for example
19317 if (terrain_z <= INVALID_HEIGHT || z < (terrain_z-2) || z > (water_z - 2) )
19318 m_isunderwater &= ~UNDERWATER_INWATER;
19319 else if ((z < (water_z - 2)) && (flag1 & 0x01))
19320 m_isunderwater |= UNDERWATER_INWATER;
19322 //!in lava check, anywhere under lava level
19323 if ((terrain_z <= INVALID_HEIGHT || z < (terrain_z - 0)) && (flag1 == 0x00) && IsInWater())
19324 m_isunderwater |= UNDERWATER_INLAVA;
19325 else
19326 m_isunderwater &= ~UNDERWATER_INLAVA;
19329 void Player::SetCanParry( bool value )
19331 if(m_canParry==value)
19332 return;
19334 m_canParry = value;
19335 UpdateParryPercentage();
19338 void Player::SetCanBlock( bool value )
19340 if(m_canBlock==value)
19341 return;
19343 m_canBlock = value;
19344 UpdateBlockPercentage();
19347 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19349 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19350 if(itr->pos == pos)
19351 return true;
19353 return false;
19356 bool Player::isAllowUseBattleGroundObject()
19358 return ( //InBattleGround() && // in battleground - not need, check in other cases
19359 !IsMounted() && // not mounted
19360 !HasStealthAura() && // not stealthed
19361 !HasInvisibilityAura() && // not invisible
19362 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19363 isAlive() // live player
19367 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19369 uint32 level = getLevel();
19371 if(level > GT_MAX_LEVEL)
19372 level = GT_MAX_LEVEL; // max level in this dbc
19374 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19375 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19376 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19378 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19379 return 0;
19381 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19383 if(!bsc) // shouldn't happen
19384 return 0xFFFFFFFF;
19386 float cost = 0;
19388 if(hairstyle != newhairstyle)
19389 cost += bsc->cost; // full price
19391 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19392 cost += bsc->cost * 0.5f; // +1/2 of price
19394 if(facialhair != newfacialhair)
19395 cost += bsc->cost * 0.75f; // +3/4 of price
19397 return uint32(cost);
19400 void Player::InitGlyphsForLevel()
19402 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19403 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19404 if(gs->Order)
19405 SetGlyphSlot(gs->Order - 1, gs->Id);
19407 uint32 level = getLevel();
19408 uint32 value = 0;
19410 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19411 if(level >= 15)
19412 value |= (0x01 | 0x02);
19413 if(level >= 30)
19414 value |= 0x08;
19415 if(level >= 50)
19416 value |= 0x04;
19417 if(level >= 70)
19418 value |= 0x10;
19419 if(level >= 80)
19420 value |= 0x20;
19422 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19425 void Player::EnterVehicle(Vehicle *vehicle)
19427 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19428 if(!ve)
19429 return;
19431 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19432 if(!veSeat)
19433 return;
19435 vehicle->SetCharmerGUID(GetGUID());
19436 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19437 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19438 vehicle->setFaction(getFaction());
19440 SetCharm(vehicle); // charm
19441 SetFarSightGUID(vehicle->GetGUID()); // set view
19443 SetClientControl(vehicle, 1); // redirect controls to vehicle
19445 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19446 GetSession()->SendPacket(&data);
19448 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19449 data.append(GetPackGUID());
19450 data << uint32(0); // counter?
19451 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19452 data << uint16(0); // special flags
19453 data << uint32(getMSTime()); // time
19454 data << vehicle->GetPositionX(); // x
19455 data << vehicle->GetPositionY(); // y
19456 data << vehicle->GetPositionZ(); // z
19457 data << vehicle->GetOrientation(); // o
19458 // transport part, TODO: load/calculate seat offsets
19459 data << uint64(vehicle->GetGUID()); // transport guid
19460 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19461 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19462 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19463 data << float(0); // transport orientation
19464 data << uint32(getMSTime()); // transport time
19465 data << uint8(0); // seat
19466 // end of transport part
19467 data << uint32(0); // fall time
19468 GetSession()->SendPacket(&data);
19470 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
19471 data << uint64(vehicle->GetGUID());
19472 data << uint32(0x00000000);
19473 data << uint32(0x00000000);
19474 data << uint32(0x00000101);
19476 for(uint32 i = 0; i < 10; ++i)
19477 data << uint16(0) << uint8(0) << uint8(i+8);
19479 data << uint8(0);
19480 data << uint8(0);
19481 GetSession()->SendPacket(&data);
19484 void Player::ExitVehicle(Vehicle *vehicle)
19486 vehicle->SetCharmerGUID(0);
19487 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19488 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19489 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19491 SetCharm(NULL);
19492 SetFarSightGUID(0);
19494 SetClientControl(vehicle, 0);
19496 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19497 data.append(GetPackGUID());
19498 data << uint32(0); // counter?
19499 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19500 data << uint16(0x40); // special flags
19501 data << uint32(getMSTime()); // time
19502 data << vehicle->GetPositionX(); // x
19503 data << vehicle->GetPositionY(); // y
19504 data << vehicle->GetPositionZ(); // z
19505 data << vehicle->GetOrientation(); // o
19506 data << uint32(0); // fall time
19507 GetSession()->SendPacket(&data);
19509 data.Initialize(SMSG_PET_SPELLS, 8+4);
19510 data << uint64(0);
19511 data << uint32(0);
19512 GetSession()->SendPacket(&data);
19514 // only for flyable vehicles?
19515 CastSpell(this, 45472, true); // Parachute
19518 bool Player::HasTitle(uint32 bitIndex)
19520 if (bitIndex > 128)
19521 return false;
19523 uint32 fieldIndexOffset = bitIndex/32;
19524 uint32 flag = 1 << (bitIndex%32);
19525 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19528 void Player::SetTitle(CharTitlesEntry const* title)
19530 uint32 fieldIndexOffset = title->bit_index/32;
19531 uint32 flag = 1 << (title->bit_index%32);
19532 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19535 void Player::ConvertRune(uint8 index, uint8 newType)
19537 SetCurrentRune(index, newType);
19539 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19540 data << uint8(index);
19541 data << uint8(newType);
19542 GetSession()->SendPacket(&data);
19545 void Player::ResyncRunes(uint8 count)
19547 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19548 for(uint32 i = 0; i < count; ++i)
19550 data << uint8(GetCurrentRune(i)); // rune type
19551 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19553 GetSession()->SendPacket(&data);
19556 void Player::AddRunePower(uint8 index)
19558 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19559 data << uint32(1 << index); // mask (0x00-0x3F probably)
19560 GetSession()->SendPacket(&data);
19563 void Player::InitRunes()
19565 if(getClass() != CLASS_DEATH_KNIGHT)
19566 return;
19568 m_runes = new Runes;
19570 m_runes->runeState = 0;
19572 for(uint32 i = 0; i < MAX_RUNES; ++i)
19574 SetBaseRune(i, i / 2); // init base types
19575 SetCurrentRune(i, i / 2); // init current types
19576 SetRuneCooldown(i, 0); // reset cooldowns
19577 m_runes->SetRuneState(i);
19580 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19581 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19584 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19586 Loot loot;
19587 loot.FillLoot (loot_id,store,this,true);
19589 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19590 for(uint32 i = 0; i < max_slot; ++i)
19592 LootItem* lootItem = loot.LootItemInSlot(i,this);
19594 ItemPosCountVec dest;
19595 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19596 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19597 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19598 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19599 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19600 if(msg != EQUIP_ERR_OK)
19602 SendEquipError( msg, NULL, NULL );
19603 continue;
19606 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19607 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19611 uint32 Player::CalculateTalentsPoints() const
19613 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19615 if(getClass() != CLASS_DEATH_KNIGHT)
19616 return base_talent;
19618 uint32 talentPointsForLevel =
19619 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19620 + m_questRewardTalentCount;
19622 if(talentPointsForLevel > base_talent)
19623 talentPointsForLevel = base_talent;
19625 return talentPointsForLevel;
19628 bool Player::IsAllowUseFlyMountsHere() const
19630 if (isGameMaster())
19631 return true;
19633 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19634 return v_map == 530 || v_map == 571 && HasSpell(54197);
19637 void Player::learnSpellHighRank(uint32 spellid)
19639 learnSpell(spellid,false);
19641 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19642 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19643 learnSpellHighRank(itr->second);
19646 void Player::_LoadSkills()
19648 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19650 // reset skill modifiers and set correct unlearn flags
19651 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
19653 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19655 // set correct unlearn bit
19656 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19657 if(!id) continue;
19659 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19660 if(!pSkill) continue;
19662 // enable unlearn button for primary professions only
19663 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19664 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19665 else
19666 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19668 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19670 learnSkillRewardedSpells(id, vskill);
19673 // special settings
19674 if(getClass()==CLASS_DEATH_KNIGHT)
19676 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19677 if(base_level < 1)
19678 base_level = 1;
19679 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19680 if(base_skill < 1)
19681 base_skill = 1; // skill mast be known and then > 0 in any case
19683 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19684 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19685 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19686 SetSkill(SKILL_AXES, base_skill,base_skill);
19687 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19688 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19689 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19690 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19691 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19692 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19693 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19694 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19695 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19696 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19697 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19698 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19702 uint32 Player::GetPhaseMaskForSpawn() const
19704 uint32 phase = PHASEMASK_NORMAL;
19705 if(!isGameMaster())
19706 phase = GetPhaseMask();
19707 else
19709 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19710 if(!phases.empty())
19711 phase = phases.front()->GetMiscValue();
19714 // some aura phases include 1 normal map in addition to phase itself
19715 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19716 return n_phase;
19718 return PHASEMASK_NORMAL;
19721 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19723 ItemPrototype const* pProto = pItem->GetProto();
19725 // proto based limitations
19726 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19727 return res;
19729 // check unique-equipped on gems
19730 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19732 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19733 if(!enchant_id)
19734 continue;
19735 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19736 if(!enchantEntry)
19737 continue;
19739 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19740 if(!pGem)
19741 continue;
19743 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19744 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19745 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19747 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19748 return res;
19751 return EQUIP_ERR_OK;
19754 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19756 // check unique-equipped on item
19757 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19759 // there is an equip limit on this item
19760 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19761 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19764 // check unique-equipped limit
19765 if (itemProto->ItemLimitCategory)
19767 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19768 if(!limitEntry)
19769 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19771 if(limit_count > limitEntry->maxCount)
19772 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19774 // there is an equip limit on this item
19775 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19776 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19779 return EQUIP_ERR_OK;