[8023] Move guardian list at Unit level and unsummon guardians at owner-creature...
[getmangos.git] / src / game / Player.cpp
blobd5416d874f7eb58d28a4fa9ef118a8fae0351321
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "SpellMgr.h"
25 #include "World.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #include "UpdateMask.h"
29 #include "Player.h"
30 #include "Vehicle.h"
31 #include "SkillDiscovery.h"
32 #include "QuestDef.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
35 #include "Channel.h"
36 #include "ChannelMgr.h"
37 #include "MapManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "GridNotifiers.h"
41 #include "GridNotifiersImpl.h"
42 #include "CellImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "CreatureAI.h"
46 #include "Formulas.h"
47 #include "Group.h"
48 #include "Guild.h"
49 #include "Pet.h"
50 #include "Util.h"
51 #include "Transports.h"
52 #include "Weather.h"
53 #include "BattleGround.h"
54 #include "BattleGroundMgr.h"
55 #include "ArenaTeam.h"
56 #include "Chat.h"
57 #include "Database/DatabaseImpl.h"
58 #include "Spell.h"
59 #include "SocialMgr.h"
60 #include "AchievementMgr.h"
62 #include <cmath>
64 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
78 enum CharacterFlags
80 CHARACTER_FLAG_NONE = 0x00000000,
81 CHARACTER_FLAG_UNK1 = 0x00000001,
82 CHARACTER_FLAG_UNK2 = 0x00000002,
83 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
84 CHARACTER_FLAG_UNK4 = 0x00000008,
85 CHARACTER_FLAG_UNK5 = 0x00000010,
86 CHARACTER_FLAG_UNK6 = 0x00000020,
87 CHARACTER_FLAG_UNK7 = 0x00000040,
88 CHARACTER_FLAG_UNK8 = 0x00000080,
89 CHARACTER_FLAG_UNK9 = 0x00000100,
90 CHARACTER_FLAG_UNK10 = 0x00000200,
91 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
92 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
93 CHARACTER_FLAG_UNK13 = 0x00001000,
94 CHARACTER_FLAG_GHOST = 0x00002000,
95 CHARACTER_FLAG_RENAME = 0x00004000,
96 CHARACTER_FLAG_UNK16 = 0x00008000,
97 CHARACTER_FLAG_UNK17 = 0x00010000,
98 CHARACTER_FLAG_UNK18 = 0x00020000,
99 CHARACTER_FLAG_UNK19 = 0x00040000,
100 CHARACTER_FLAG_UNK20 = 0x00080000,
101 CHARACTER_FLAG_UNK21 = 0x00100000,
102 CHARACTER_FLAG_UNK22 = 0x00200000,
103 CHARACTER_FLAG_UNK23 = 0x00400000,
104 CHARACTER_FLAG_UNK24 = 0x00800000,
105 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
106 CHARACTER_FLAG_DECLINED = 0x02000000,
107 CHARACTER_FLAG_UNK27 = 0x04000000,
108 CHARACTER_FLAG_UNK28 = 0x08000000,
109 CHARACTER_FLAG_UNK29 = 0x10000000,
110 CHARACTER_FLAG_UNK30 = 0x20000000,
111 CHARACTER_FLAG_UNK31 = 0x40000000,
112 CHARACTER_FLAG_UNK32 = 0x80000000
115 // corpse reclaim times
116 #define DEATH_EXPIRE_STEP (5*MINUTE)
117 #define MAX_DEATH_COUNT 3
119 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
121 //== PlayerTaxi ================================================
123 PlayerTaxi::PlayerTaxi()
125 // Taxi nodes
126 memset(m_taximask, 0, sizeof(m_taximask));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
131 // class specific initial known nodes
132 switch(chrClass)
134 case CLASS_DEATH_KNIGHT:
136 for(int i = 0; i < TaxiMaskSize; ++i)
137 m_taximask[i] |= sOldContinentsNodesMask[i];
138 break;
142 // race specific initial known nodes: capital and taxi hub masks
143 switch(race)
145 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
146 case RACE_ORC: SetTaximaskNode(23); break; // Orc
147 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
148 case RACE_NIGHTELF: SetTaximaskNode(26);
149 SetTaximaskNode(27); break; // Night Elf
150 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
151 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
152 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
153 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
154 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
155 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
158 // new continent starting masks (It will be accessible only at new map)
159 switch(Player::TeamForRace(race))
161 case ALLIANCE: SetTaximaskNode(100); break;
162 case HORDE: SetTaximaskNode(99); break;
164 // level dependent taxi hubs
165 if(level>=68)
166 SetTaximaskNode(213); //Shattered Sun Staging Area
169 void PlayerTaxi::LoadTaxiMask(const char* data)
171 Tokens tokens = StrSplit(data, " ");
173 int index;
174 Tokens::iterator iter;
175 for (iter = tokens.begin(), index = 0;
176 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
178 // load and set bits only for existed taxi nodes
179 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
183 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
185 if(all)
187 for (uint8 i=0; i<TaxiMaskSize; ++i)
188 data << uint32(sTaxiNodesMask[i]); // all existed nodes
190 else
192 for (uint8 i=0; i<TaxiMaskSize; ++i)
193 data << uint32(m_taximask[i]); // known nodes
197 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
199 ClearTaxiDestinations();
201 Tokens tokens = StrSplit(values," ");
203 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
205 uint32 node = uint32(atol(iter->c_str()));
206 AddTaxiDestination(node);
209 if(m_TaxiDestinations.empty())
210 return true;
212 // Check integrity
213 if(m_TaxiDestinations.size() < 2)
214 return false;
216 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
218 uint32 cost;
219 uint32 path;
220 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
221 if(!path)
222 return false;
225 // can't load taxi path without mount set (quest taxi path?)
226 if(!objmgr.GetTaxiMountDisplayId(GetTaxiSource(),team,true))
227 return false;
229 return true;
232 std::string PlayerTaxi::SaveTaxiDestinationsToString()
234 if(m_TaxiDestinations.empty())
235 return "";
237 std::ostringstream ss;
239 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
240 ss << m_TaxiDestinations[i] << " ";
242 return ss.str();
245 uint32 PlayerTaxi::GetCurrentTaxiPath() const
247 if(m_TaxiDestinations.size() < 2)
248 return 0;
250 uint32 path;
251 uint32 cost;
253 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
255 return path;
258 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
260 ss << "'";
261 for(int i = 0; i < TaxiMaskSize; ++i)
262 ss << taxi.m_taximask[i] << " ";
263 ss << "'";
264 return ss;
267 //== Player ====================================================
269 UpdateMask Player::updateVisualBits;
271 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
273 m_transport = 0;
275 m_speakTime = 0;
276 m_speakCount = 0;
278 m_objectType |= TYPEMASK_PLAYER;
279 m_objectTypeId = TYPEID_PLAYER;
281 m_valuesCount = PLAYER_END;
283 m_session = session;
285 m_divider = 0;
287 m_ExtraFlags = 0;
288 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
289 SetAcceptTicket(true);
291 // players always accept
292 if(GetSession()->GetSecurity() == SEC_PLAYER)
293 SetAcceptWhispers(true);
295 m_curSelection = 0;
296 m_lootGuid = 0;
298 m_comboTarget = 0;
299 m_comboPoints = 0;
301 m_usedTalentCount = 0;
302 m_questRewardTalentCount = 0;
304 m_regenTimer = 0;
305 m_weaponChangeTimer = 0;
307 m_zoneUpdateId = 0;
308 m_zoneUpdateTimer = 0;
310 m_areaUpdateId = 0;
312 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
314 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
315 // this must help in case next save after mass player load after server startup
316 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
318 clearResurrectRequestData();
320 m_SpellModRemoveCount = 0;
322 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
324 m_social = NULL;
326 // group is initialized in the reference constructor
327 SetGroupInvite(NULL);
328 m_groupUpdateMask = 0;
329 m_auraUpdateMask = 0;
331 duel = NULL;
333 m_GuildIdInvited = 0;
334 m_ArenaTeamIdInvited = 0;
336 m_atLoginFlags = AT_LOGIN_NONE;
338 mSemaphoreTeleport_Near = false;
339 mSemaphoreTeleport_Far = false;
341 pTrader = 0;
342 ClearTrade();
344 m_cinematic = 0;
346 PlayerTalkClass = new PlayerMenu( GetSession() );
347 m_currentBuybackSlot = BUYBACK_SLOT_START;
349 m_DailyQuestChanged = false;
350 m_lastDailyQuestTime = 0;
352 for (int i=0; i<MAX_TIMERS; ++i)
353 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
355 m_MirrorTimerFlags = UNDERWATER_NONE;
356 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
357 m_isInWater = false;
358 m_drunkTimer = 0;
359 m_drunk = 0;
360 m_restTime = 0;
361 m_deathTimer = 0;
362 m_deathExpireTime = 0;
364 m_swingErrorMsg = 0;
366 m_DetectInvTimer = 1*IN_MILISECONDS;
368 m_bgBattleGroundID = 0;
369 m_bgTypeID = BATTLEGROUND_TYPE_NONE;
370 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
372 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
373 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
375 m_bgTeam = 0;
377 m_logintime = time(NULL);
378 m_Last_tick = m_logintime;
379 m_WeaponProficiency = 0;
380 m_ArmorProficiency = 0;
381 m_canParry = false;
382 m_canBlock = false;
383 m_canDualWield = false;
384 m_canTitanGrip = false;
385 m_ammoDPS = 0.0f;
387 m_temporaryUnsummonedPetNumber = 0;
388 //cache for UNIT_CREATED_BY_SPELL to allow
389 //returning reagents for temporarily removed pets
390 //when dying/logging out
391 m_oldpetspell = 0;
393 ////////////////////Rest System/////////////////////
394 time_inn_enter=0;
395 inn_pos_mapid=0;
396 inn_pos_x=0;
397 inn_pos_y=0;
398 inn_pos_z=0;
399 m_rest_bonus=0;
400 rest_type=REST_TYPE_NO;
401 ////////////////////Rest System/////////////////////
403 m_mailsLoaded = false;
404 m_mailsUpdated = false;
405 unReadMails = 0;
406 m_nextMailDelivereTime = 0;
408 m_resetTalentsCost = 0;
409 m_resetTalentsTime = 0;
410 m_itemUpdateQueueBlocked = false;
412 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
413 m_forced_speed_changes[i] = 0;
415 m_stableSlots = 0;
417 /////////////////// Instance System /////////////////////
419 m_HomebindTimer = 0;
420 m_InstanceValid = true;
421 m_dungeonDifficulty = DIFFICULTY_NORMAL;
423 m_lastPotionId = 0;
425 m_activeSpec = 0;
426 m_specsCount = 0;
428 for (int i = 0; i < BASEMOD_END; ++i)
430 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
431 m_auraBaseMod[i][PCT_MOD] = 1.0f;
434 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
435 m_baseRatingValue[i] = 0;
437 m_baseSpellDamage = 0;
438 m_baseSpellHealing = 0;
439 m_baseFeralAP = 0;
440 m_baseManaRegen = 0;
442 // Honor System
443 m_lastHonorUpdateTime = time(NULL);
445 // Player summoning
446 m_summon_expire = 0;
447 m_summon_mapid = 0;
448 m_summon_x = 0.0f;
449 m_summon_y = 0.0f;
450 m_summon_z = 0.0f;
452 //Default movement to run mode
453 m_unit_movement_flags = 0;
455 m_mover = this;
457 m_miniPet = 0;
458 m_bgAfkReportedTimer = 0;
459 m_contestedPvPTimer = 0;
461 m_declinedname = NULL;
462 m_runes = NULL;
464 m_lastFallTime = 0;
465 m_lastFallZ = 0;
468 Player::~Player ()
470 CleanupsBeforeDelete();
472 // it must be unloaded already in PlayerLogout and accessed only for loggined player
473 //m_social = NULL;
475 // Note: buy back item already deleted from DB when player was saved
476 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
478 if(m_items[i])
479 delete m_items[i];
481 CleanupChannels();
483 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
484 delete itr->second;
486 //all mailed items should be deleted, also all mail should be deallocated
487 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
488 delete *itr;
490 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
491 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
493 delete PlayerTalkClass;
495 if (m_transport)
497 m_transport->RemovePassenger(this);
500 for(size_t x = 0; x < ItemSetEff.size(); x++)
501 if(ItemSetEff[x])
502 delete ItemSetEff[x];
504 // clean up player-instance binds, may unload some instance saves
505 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
506 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
507 itr->second.save->RemovePlayer(this);
509 delete m_declinedname;
510 delete m_runes;
513 void Player::CleanupsBeforeDelete()
515 if(m_uint32Values) // only for fully created Object
517 TradeCancel(false);
518 DuelComplete(DUEL_INTERUPTED);
520 Unit::CleanupsBeforeDelete();
523 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 )
525 //FIXME: outfitId not used in player creating
527 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
529 m_name = name;
531 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
532 if(!info)
534 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
535 return false;
538 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
539 m_items[i] = NULL;
541 m_race = race;
542 m_class = class_;
544 SetMapId(info->mapId);
545 Relocate(info->positionX,info->positionY,info->positionZ);
547 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
548 if(!cEntry)
550 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
551 return false;
554 uint8 powertype = cEntry->powerType;
556 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
557 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
559 switch(gender)
561 case GENDER_FEMALE:
562 SetDisplayId(info->displayId_f );
563 SetNativeDisplayId(info->displayId_f );
564 break;
565 case GENDER_MALE:
566 SetDisplayId(info->displayId_m );
567 SetNativeDisplayId(info->displayId_m );
568 break;
569 default:
570 sLog.outError("Invalid gender %u for player",gender);
571 return false;
572 break;
575 setFactionForRace(m_race);
577 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
579 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
580 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
581 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
582 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
583 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
584 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
586 // -1 is default value
587 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
589 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
590 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
591 SetByteValue(PLAYER_BYTES_3, 0, gender);
593 SetUInt32Value( PLAYER_GUILDID, 0 );
594 SetUInt32Value( PLAYER_GUILDRANK, 0 );
595 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
597 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
598 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
599 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 0 ); // 0=disabled
600 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
601 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
602 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
603 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
604 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
606 // set starting level
607 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
608 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
609 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
611 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
613 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
614 if(gm_level > start_level)
615 start_level = gm_level;
618 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
620 InitRunes();
622 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
623 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
624 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
626 // Played time
627 m_Last_tick = time(NULL);
628 m_Played_time[0] = 0;
629 m_Played_time[1] = 0;
631 // base stats and related field values
632 InitStatsForLevel();
633 InitTaxiNodesForLevel();
634 InitGlyphsForLevel();
635 InitTalentForLevel();
636 InitPrimaryProfessions(); // to max set before any spell added
638 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
639 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
640 SetHealth(GetMaxHealth());
641 if (getPowerType()==POWER_MANA)
643 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
644 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
647 if(getPowerType() == POWER_RUNIC_POWER)
649 SetPower(POWER_RUNE, 8);
650 SetMaxPower(POWER_RUNE, 8);
651 SetPower(POWER_RUNIC_POWER, 0);
652 SetMaxPower(POWER_RUNIC_POWER, 1000);
655 // original spells
656 learnDefaultSpells();
658 // original action bar
659 std::list<uint16>::const_iterator action_itr[4];
660 for(int i=0; i<4; ++i)
661 action_itr[i] = info->action[i].begin();
663 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
665 uint16 taction[4];
666 for(int i=0; i<4 ;++i)
667 taction[i] = (*action_itr[i]);
669 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
671 for(int i=0; i<4 ;++i)
672 ++action_itr[i];
675 // original items
676 CharStartOutfitEntry const* oEntry = NULL;
677 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
679 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
681 if(entry->RaceClassGender == RaceClassGender)
683 oEntry = entry;
684 break;
689 if(oEntry)
691 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
693 if(oEntry->ItemId[j] <= 0)
694 continue;
696 uint32 item_id = oEntry->ItemId[j];
699 // Hack for not existed item id in dbc 3.0.3
700 if(item_id==40582)
701 continue;
703 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
704 if(!iProto)
706 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
707 continue;
710 // max stack by default (mostly 1), 1 for infinity stackable
711 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
713 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
715 switch(iProto->Spells[0].SpellCategory)
717 case 11: // food
718 if(iProto->Stackable > 4)
719 count = 4;
720 break;
721 case 59: // drink
722 if(iProto->Stackable > 2)
723 count = 2;
724 break;
728 StoreNewItemInBestSlots(item_id, count);
732 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
733 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
735 // bags and main-hand weapon must equipped at this moment
736 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
737 // or ammo not equipped in special bag
738 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
740 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
742 uint16 eDest;
743 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
744 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
745 if( msg == EQUIP_ERR_OK )
747 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
748 EquipItem( eDest, pItem, true);
750 // move other items to more appropriate slots (ammo not equipped in special bag)
751 else
753 ItemPosCountVec sDest;
754 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
755 if( msg == EQUIP_ERR_OK )
757 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
758 pItem = StoreItem( sDest, pItem, true);
761 // if this is ammo then use it
762 msg = CanUseAmmo( pItem->GetEntry() );
763 if( msg == EQUIP_ERR_OK )
764 SetAmmo( pItem->GetEntry() );
768 // all item positions resolved
770 return true;
773 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
775 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
777 // attempt equip by one
778 while(titem_amount > 0)
780 uint16 eDest;
781 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
782 if( msg != EQUIP_ERR_OK )
783 break;
785 EquipNewItem( eDest, titem_id, true);
786 AutoUnequipOffhandIfNeed();
787 --titem_amount;
790 if(titem_amount == 0)
791 return true; // equipped
793 // attempt store
794 ItemPosCountVec sDest;
795 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
796 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
797 if( msg == EQUIP_ERR_OK )
799 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
800 return true; // stored
803 // item can't be added
804 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
805 return false;
808 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
810 if (MaxValue == DISABLED_MIRROR_TIMER)
812 if (CurrentValue!=DISABLED_MIRROR_TIMER)
813 StopMirrorTimer(Type);
814 return;
816 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
817 data << (uint32)Type;
818 data << CurrentValue;
819 data << MaxValue;
820 data << Regen;
821 data << (uint8)0;
822 data << (uint32)0; // spell id
823 GetSession()->SendPacket( &data );
826 void Player::StopMirrorTimer(MirrorTimerType Type)
828 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
829 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
830 data << (uint32)Type;
831 GetSession()->SendPacket( &data );
834 void Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
836 if(!isAlive() || isGameMaster())
837 return;
839 // Absorb, resist some environmental damage type
840 uint32 absorb = 0;
841 uint32 resist = 0;
842 if (type == DAMAGE_LAVA)
843 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
844 else if (type == DAMAGE_SLIME)
845 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
847 damage-=absorb+resist;
849 DealDamageMods(this,damage,&absorb);
851 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
852 data << uint64(GetGUID());
853 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
854 data << uint32(damage);
855 data << uint32(absorb);
856 data << uint32(resist);
857 SendMessageToSet(&data, true);
859 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
861 if(!isAlive())
863 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
865 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
866 DurabilityLossAll(0.10f,false);
867 // durability lost message
868 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
869 GetSession()->SendPacket(&data2);
872 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
876 int32 Player::getMaxTimer(MirrorTimerType timer)
878 switch (timer)
880 case FATIGUE_TIMER:
881 return MINUTE*IN_MILISECONDS;
882 case BREATH_TIMER:
884 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
885 return DISABLED_MIRROR_TIMER;
886 int32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS;
887 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
888 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
889 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
890 return UnderWaterTime;
892 case FIRE_TIMER:
894 if (!isAlive())
895 return DISABLED_MIRROR_TIMER;
896 return 1*IN_MILISECONDS;
898 default:
899 return 0;
901 return 0;
904 void Player::UpdateMirrorTimers()
906 // Desync flags for update on next HandleDrowning
907 if (m_MirrorTimerFlags)
908 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
911 void Player::HandleDrowning(uint32 time_diff)
913 if (!m_MirrorTimerFlags)
914 return;
916 // In water
917 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
919 // Breath timer not activated - activate it
920 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
922 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
923 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
925 else // If activated - do tick
927 m_MirrorTimer[BREATH_TIMER]-=time_diff;
928 // Timer limit - need deal damage
929 if (m_MirrorTimer[BREATH_TIMER] < 0)
931 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
932 // Calculate and deal damage
933 // TODO: Check this formula
934 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
935 EnvironmentalDamage(DAMAGE_DROWNING, damage);
937 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
938 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
941 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
943 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
944 // Need breath regen
945 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
946 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
947 StopMirrorTimer(BREATH_TIMER);
948 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
949 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
952 // In dark water
953 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
955 // Fatigue timer not activated - activate it
956 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
958 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
959 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
961 else
963 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
964 // Timer limit - need deal damage or teleport ghost to graveyard
965 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
967 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
968 if (isAlive()) // Calculate and deal damage
970 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
971 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
973 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
974 RepopAtGraveyard();
976 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
977 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
980 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
982 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
983 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
984 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
985 StopMirrorTimer(FATIGUE_TIMER);
986 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
987 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
990 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
992 // Breath timer not activated - activate it
993 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
994 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
995 else
997 m_MirrorTimer[FIRE_TIMER]-=time_diff;
998 if (m_MirrorTimer[FIRE_TIMER] < 0)
1000 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
1001 // Calculate and deal damage
1002 // TODO: Check this formula
1003 uint32 damage = urand(600, 700);
1004 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
1005 EnvironmentalDamage(DAMAGE_LAVA, damage);
1006 else
1007 EnvironmentalDamage(DAMAGE_SLIME, damage);
1011 else
1012 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
1014 // Recheck timers flag
1015 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1016 for (int i = 0; i< MAX_TIMERS; ++i)
1017 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1019 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1020 break;
1022 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1025 ///The player sobers by 256 every 10 seconds
1026 void Player::HandleSobering()
1028 m_drunkTimer = 0;
1030 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1031 SetDrunkValue(drunk);
1034 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1036 if(value >= 23000)
1037 return DRUNKEN_SMASHED;
1038 if(value >= 12800)
1039 return DRUNKEN_DRUNK;
1040 if(value & 0xFFFE)
1041 return DRUNKEN_TIPSY;
1042 return DRUNKEN_SOBER;
1045 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1047 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1049 m_drunk = newDrunkenValue;
1050 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1052 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1054 // special drunk invisibility detection
1055 if(newDrunkenState >= DRUNKEN_DRUNK)
1056 m_detectInvisibilityMask |= (1<<6);
1057 else
1058 m_detectInvisibilityMask &= ~(1<<6);
1060 if(newDrunkenState == oldDrunkenState)
1061 return;
1063 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1064 data << uint64(GetGUID());
1065 data << uint32(newDrunkenState);
1066 data << uint32(itemId);
1068 SendMessageToSet(&data, true);
1071 void Player::Update( uint32 p_time )
1073 if(!IsInWorld())
1074 return;
1076 // undelivered mail
1077 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1079 SendNewMail();
1080 ++unReadMails;
1082 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1083 m_nextMailDelivereTime = 0;
1086 Unit::Update( p_time );
1088 // update player only attacks
1089 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1091 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1094 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1096 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1099 time_t now = time (NULL);
1101 UpdatePvPFlag(now);
1103 UpdateContestedPvP(p_time);
1105 UpdateDuelFlag(now);
1107 CheckDuelDistance(now);
1109 UpdateAfkReport(now);
1111 // Update items that have just a limited lifetime
1112 if (now>m_Last_tick)
1113 UpdateItemDuration(uint32(now- m_Last_tick));
1115 if (!m_timedquests.empty())
1117 std::set<uint32>::iterator iter = m_timedquests.begin();
1118 while (iter != m_timedquests.end())
1120 QuestStatusData& q_status = mQuestStatus[*iter];
1121 if( q_status.m_timer <= p_time )
1123 uint32 quest_id = *iter;
1124 ++iter; // current iter will be removed in FailTimedQuest
1125 FailTimedQuest( quest_id );
1127 else
1129 q_status.m_timer -= p_time;
1130 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1131 ++iter;
1136 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1138 Unit *pVictim = getVictim();
1139 if (pVictim && !IsNonMeleeSpellCasted(false))
1141 // default combat reach 10
1142 // TODO add weapon,skill check
1144 float pldistance = ATTACK_DISTANCE;
1146 if (isAttackReady(BASE_ATTACK))
1148 if(!IsWithinDistInMap(pVictim, pldistance))
1150 setAttackTimer(BASE_ATTACK,100);
1151 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1153 SendAttackSwingNotInRange();
1154 m_swingErrorMsg = 1;
1157 //120 degrees of radiant range
1158 else if( !HasInArc( 2*M_PI/3, pVictim ))
1160 setAttackTimer(BASE_ATTACK,100);
1161 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1163 SendAttackSwingBadFacingAttack();
1164 m_swingErrorMsg = 2;
1167 else
1169 m_swingErrorMsg = 0; // reset swing error state
1171 // prevent base and off attack in same time, delay attack at 0.2 sec
1172 if(haveOffhandWeapon())
1174 uint32 off_att = getAttackTimer(OFF_ATTACK);
1175 if(off_att < ATTACK_DISPLAY_DELAY)
1176 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1178 AttackerStateUpdate(pVictim, BASE_ATTACK);
1179 resetAttackTimer(BASE_ATTACK);
1183 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1185 if(!IsWithinDistInMap(pVictim, pldistance))
1187 setAttackTimer(OFF_ATTACK,100);
1189 else if( !HasInArc( 2*M_PI/3, pVictim ))
1191 setAttackTimer(OFF_ATTACK,100);
1193 else
1195 // prevent base and off attack in same time, delay attack at 0.2 sec
1196 uint32 base_att = getAttackTimer(BASE_ATTACK);
1197 if(base_att < ATTACK_DISPLAY_DELAY)
1198 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1199 // do attack
1200 AttackerStateUpdate(pVictim, OFF_ATTACK);
1201 resetAttackTimer(OFF_ATTACK);
1205 Unit *owner = pVictim->GetOwner();
1206 Unit *u = owner ? owner : pVictim;
1207 if(u->IsPvP() && (!duel || duel->opponent != u))
1209 UpdatePvP(true);
1210 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1215 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1217 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1219 int time_inn = time(NULL)-GetTimeInnEnter();
1220 if (time_inn >= 10) //freeze update
1222 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1223 //speed collect rest bonus (section/in hour)
1224 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1225 UpdateInnerTime(time(NULL));
1230 if(m_regenTimer > 0)
1232 if(p_time >= m_regenTimer)
1233 m_regenTimer = 0;
1234 else
1235 m_regenTimer -= p_time;
1238 if (m_weaponChangeTimer > 0)
1240 if(p_time >= m_weaponChangeTimer)
1241 m_weaponChangeTimer = 0;
1242 else
1243 m_weaponChangeTimer -= p_time;
1246 if (m_zoneUpdateTimer > 0)
1248 if(p_time >= m_zoneUpdateTimer)
1250 uint32 newzone, newarea;
1251 GetZoneAndAreaId(newzone,newarea);
1253 if( m_zoneUpdateId != newzone )
1254 UpdateZone(newzone,newarea); // also update area
1255 else
1257 // use area updates as well
1258 // needed for free far all arenas for example
1259 if( m_areaUpdateId != newarea )
1260 UpdateArea(newarea);
1262 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1265 else
1266 m_zoneUpdateTimer -= p_time;
1269 if (isAlive())
1271 RegenerateAll();
1274 if (m_deathState == JUST_DIED)
1276 KillPlayer();
1279 if(m_nextSave > 0)
1281 if(p_time >= m_nextSave)
1283 // m_nextSave reseted in SaveToDB call
1284 SaveToDB();
1285 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1287 else
1289 m_nextSave -= p_time;
1293 //Handle Water/drowning
1294 HandleDrowning(p_time);
1296 //Handle detect stealth players
1297 if (m_DetectInvTimer > 0)
1299 if (p_time >= m_DetectInvTimer)
1301 m_DetectInvTimer = 3000;
1302 HandleStealthedUnitsDetection();
1304 else
1305 m_DetectInvTimer -= p_time;
1308 // Played time
1309 if (now > m_Last_tick)
1311 uint32 elapsed = uint32(now - m_Last_tick);
1312 m_Played_time[0] += elapsed; // Total played time
1313 m_Played_time[1] += elapsed; // Level played time
1314 m_Last_tick = now;
1317 if (m_drunk)
1319 m_drunkTimer += p_time;
1321 if (m_drunkTimer > 10*IN_MILISECONDS)
1322 HandleSobering();
1325 // not auto-free ghost from body in instances
1326 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1328 if(p_time >= m_deathTimer)
1330 m_deathTimer = 0;
1331 BuildPlayerRepop();
1332 RepopAtGraveyard();
1334 else
1335 m_deathTimer -= p_time;
1338 UpdateEnchantTime(p_time);
1339 UpdateHomebindTime(p_time);
1341 // group update
1342 SendUpdateToOutOfRangeGroupMembers();
1344 Pet* pet = GetPet();
1345 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1347 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1348 return;
1352 void Player::setDeathState(DeathState s)
1354 uint32 ressSpellId = 0;
1356 bool cur = isAlive();
1358 if(s == JUST_DIED && cur)
1360 // drunken state is cleared on death
1361 SetDrunkValue(0);
1362 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1363 ClearComboPoints();
1365 clearResurrectRequestData();
1367 // remove form before other mods to prevent incorrect stats calculation
1368 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1370 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1371 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1373 // remove uncontrolled pets
1374 RemoveMiniPet();
1376 // save value before aura remove in Unit::setDeathState
1377 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1379 // passive spell
1380 if(!ressSpellId)
1381 ressSpellId = GetResurrectionSpellId();
1382 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1383 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1384 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1386 Unit::setDeathState(s);
1388 // restore resurrection spell id for player after aura remove
1389 if(s == JUST_DIED && cur && ressSpellId)
1390 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1392 if(isAlive() && !cur)
1394 //clear aura case after resurrection by another way (spells will be applied before next death)
1395 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1397 // restore default warrior stance
1398 if(getClass()== CLASS_WARRIOR)
1399 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1403 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1405 Field *fields = result->Fetch();
1407 *p_data << uint64(GetGUID());
1408 *p_data << m_name;
1410 *p_data << uint8(getRace());
1411 uint8 pClass = getClass();
1412 *p_data << uint8(pClass);
1413 *p_data << uint8(getGender());
1415 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1416 *p_data << uint8(bytes);
1417 *p_data << uint8(bytes >> 8);
1418 *p_data << uint8(bytes >> 16);
1419 *p_data << uint8(bytes >> 24);
1421 bytes = GetUInt32Value(PLAYER_BYTES_2);
1422 *p_data << uint8(bytes);
1424 *p_data << uint8(getLevel()); // player level
1425 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1426 uint32 zoneId = fields[10].GetUInt32();
1427 sLog.outDebug("Player::BuildEnumData: map:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1428 *p_data << uint32(zoneId);
1429 *p_data << uint32(GetMapId());
1431 *p_data << GetPositionX();
1432 *p_data << GetPositionY();
1433 *p_data << GetPositionZ();
1435 // guild id
1436 *p_data << uint32(fields[14].GetUInt32());
1438 uint32 char_flags = 0;
1439 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1440 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1441 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1442 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1443 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1444 char_flags |= CHARACTER_FLAG_GHOST;
1445 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1446 char_flags |= CHARACTER_FLAG_RENAME;
1447 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
1449 if(!fields[15].GetCppString().empty())
1450 char_flags |= CHARACTER_FLAG_DECLINED;
1452 else
1453 char_flags |= CHARACTER_FLAG_DECLINED;
1455 *p_data << uint32(char_flags); // character flags
1456 // character customize (flags?)
1457 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1458 *p_data << uint8(1); // unknown
1460 // Pets info
1462 uint32 petDisplayId = 0;
1463 uint32 petLevel = 0;
1464 uint32 petFamily = 0;
1466 // show pet at selection character in character list only for non-ghost character
1467 if (result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1469 uint32 entry = fields[11].GetUInt32();
1470 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1471 if(cInfo)
1473 petDisplayId = fields[12].GetUInt32();
1474 petLevel = fields[13].GetUInt32();
1475 petFamily = cInfo->family;
1479 *p_data << uint32(petDisplayId);
1480 *p_data << uint32(petLevel);
1481 *p_data << uint32(petFamily);
1484 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1486 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1487 uint32 item_id = GetUInt32Value(visualbase);
1488 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1489 SpellItemEnchantmentEntry const *enchant = NULL;
1491 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1493 uint32 enchantId = GetUInt16Value(visualbase + 1, enchantSlot);
1494 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1495 break;
1498 if (proto != NULL)
1500 *p_data << uint32(proto->DisplayInfoID);
1501 *p_data << uint8(proto->InventoryType);
1502 *p_data << uint32(enchant ? enchant->aura_id : 0);
1504 else
1506 *p_data << uint32(0);
1507 *p_data << uint8(0);
1508 *p_data << uint32(0); // enchant?
1511 *p_data << uint32(0); // first bag display id
1512 *p_data << uint8(0); // first bag inventory type
1513 *p_data << uint32(0); // enchant?
1516 bool Player::ToggleAFK()
1518 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1520 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1522 // afk player not allowed in battleground
1523 if(state && InBattleGround())
1524 LeaveBattleground();
1526 return state;
1529 bool Player::ToggleDND()
1531 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1533 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1536 uint8 Player::chatTag() const
1538 // it's bitmask
1539 // 0x8 - ??
1540 // 0x4 - gm
1541 // 0x2 - dnd
1542 // 0x1 - afk
1543 if(isGMChat())
1544 return 4;
1545 else if(isDND())
1546 return 3;
1547 if(isAFK())
1548 return 1;
1549 else
1550 return 0;
1553 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1555 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1557 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1558 return false;
1561 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1562 Pet* pet = GetPet();
1564 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1566 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1567 // don't let gm level > 1 either
1568 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1569 return false;
1571 // client without expansion support
1572 if(GetSession()->Expansion() < mEntry->Expansion())
1574 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1576 if(GetTransport())
1577 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1579 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1581 return false; // normal client can't teleport to this map...
1583 else
1585 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1588 // if we were on a transport, leave
1589 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1591 m_transport->RemovePassenger(this);
1592 m_transport = NULL;
1593 m_movementInfo.t_x = 0.0f;
1594 m_movementInfo.t_y = 0.0f;
1595 m_movementInfo.t_z = 0.0f;
1596 m_movementInfo.t_o = 0.0f;
1597 m_movementInfo.t_time = 0;
1600 // The player was ported to another map and looses the duel immediately.
1601 // We have to perform this check before the teleport, otherwise the
1602 // ObjectAccessor won't find the flag.
1603 if (duel && GetMapId()!=mapid)
1605 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1606 if (obj)
1607 DuelComplete(DUEL_FLED);
1610 // reset movement flags at teleport, because player will continue move with these flags after teleport
1611 m_movementInfo.flags = 0;
1613 if ((GetMapId() == mapid) && (!m_transport))
1615 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1617 //same map, only remove pet if out of range for new position
1618 if(pet && !pet->IsWithinDist3d(x,y,z, OWNER_MAX_DISTANCE))
1619 UnsummonPetTemporaryIfAny();
1622 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1623 CombatStop();
1625 // this will be used instead of the current location in SaveToDB
1626 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1627 SetFallInformation(0, z);
1629 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1630 // at client packet MSG_MOVE_TELEPORT_ACK
1631 SetSemaphoreTeleportNear(true);
1632 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1633 if(!GetSession()->PlayerLogout())
1635 WorldPacket data;
1636 BuildTeleportAckMsg(&data, x, y, z, orientation);
1637 GetSession()->SendPacket(&data);
1640 else
1642 // far teleport to another map
1643 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1644 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1646 // Check enter rights before map getting to avoid creating instance copy for player
1647 // this check not dependent from map instance copy and same for all instance copies of selected map
1648 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1649 return false;
1651 // If the map is not created, assume it is possible to enter it.
1652 // It will be created in the WorldPortAck.
1653 Map *map = MapManager::Instance().FindMap(mapid);
1654 if (!map || map->CanEnter(this))
1656 SetSelection(0);
1658 CombatStop();
1660 ResetContestedPvP();
1662 // remove player from battleground on far teleport (when changing maps)
1663 if(BattleGround const* bg = GetBattleGround())
1665 // Note: at battleground join battleground id set before teleport
1666 // and we already will found "current" battleground
1667 // just need check that this is targeted map or leave
1668 if(bg->GetMapId() != mapid)
1669 LeaveBattleground(false); // don't teleport to entry point
1672 // remove pet on map change
1673 if (pet)
1674 UnsummonPetTemporaryIfAny();
1676 // remove all dyn objects
1677 RemoveAllDynObjects();
1679 // stop spellcasting
1680 // not attempt interrupt teleportation spell at caster teleport
1681 if(!(options & TELE_TO_SPELL))
1682 if(IsNonMeleeSpellCasted(true))
1683 InterruptNonMeleeSpells(true);
1685 if(!GetSession()->PlayerLogout())
1687 // send transfer packets
1688 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1689 data << uint32(mapid);
1690 if (m_transport)
1692 data << m_transport->GetEntry() << GetMapId();
1694 GetSession()->SendPacket(&data);
1696 data.Initialize(SMSG_NEW_WORLD, (20));
1697 if (m_transport)
1699 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1701 else
1703 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1705 GetSession()->SendPacket( &data );
1706 SendSavedInstances();
1708 // remove from old map now
1709 if(oldmap) oldmap->Remove(this, false);
1712 // new final coordinates
1713 float final_x = x;
1714 float final_y = y;
1715 float final_z = z;
1716 float final_o = orientation;
1718 if(m_transport)
1720 final_x += m_movementInfo.t_x;
1721 final_y += m_movementInfo.t_y;
1722 final_z += m_movementInfo.t_z;
1723 final_o += m_movementInfo.t_o;
1726 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1727 SetFallInformation(0, final_z);
1728 // if the player is saved before worldportack (at logout for example)
1729 // this will be used instead of the current location in SaveToDB
1731 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1733 // move packet sent by client always after far teleport
1734 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1735 SetSemaphoreTeleportFar(true);
1737 else
1738 return false;
1740 return true;
1743 void Player::AddToWorld()
1745 ///- Do not add/remove the player from the object storage
1746 ///- It will crash when updating the ObjectAccessor
1747 ///- The player should only be added when logging in
1748 Unit::AddToWorld();
1750 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1752 if(m_items[i])
1753 m_items[i]->AddToWorld();
1757 void Player::RemoveFromWorld()
1759 // cleanup
1760 if(IsInWorld())
1762 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1763 Uncharm();
1764 UnsummonAllTotems();
1765 RemoveMiniPet();
1768 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1770 if(m_items[i])
1771 m_items[i]->RemoveFromWorld();
1774 ///- Do not add/remove the player from the object storage
1775 ///- It will crash when updating the ObjectAccessor
1776 ///- The player should only be removed when logging out
1777 Unit::RemoveFromWorld();
1780 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1782 float addRage;
1784 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1786 if(attacker)
1788 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1790 // talent who gave more rage on attack
1791 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1793 else
1795 addRage = damage/rageconversion*2.5;
1797 // Berserker Rage effect
1798 if(HasAura(18499,0))
1799 addRage *= 1.3;
1802 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1804 ModifyPower(POWER_RAGE, uint32(addRage*10));
1807 void Player::RegenerateAll()
1809 if (m_regenTimer != 0)
1810 return;
1811 uint32 regenDelay = 2000;
1813 // Not in combat or they have regeneration
1814 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1815 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1817 RegenerateHealth();
1818 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1820 Regenerate(POWER_RAGE);
1821 if(getClass() == CLASS_DEATH_KNIGHT)
1822 Regenerate(POWER_RUNIC_POWER);
1826 Regenerate( POWER_ENERGY );
1828 Regenerate( POWER_MANA );
1830 if(getClass() == CLASS_DEATH_KNIGHT)
1831 Regenerate( POWER_RUNE );
1833 m_regenTimer = regenDelay;
1836 void Player::Regenerate(Powers power)
1838 uint32 curValue = GetPower(power);
1839 uint32 maxValue = GetMaxPower(power);
1841 float addvalue = 0.0f;
1843 switch (power)
1845 case POWER_MANA:
1847 bool recentCast = IsUnderLastManaUseEffect();
1848 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1849 if (recentCast)
1851 // Mangos Updates Mana in intervals of 2s, which is correct
1852 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1854 else
1856 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1858 } break;
1859 case POWER_RAGE: // Regenerate rage
1861 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1862 addvalue = 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
1863 } break;
1864 case POWER_ENERGY: // Regenerate energy (rogue)
1865 addvalue = 20;
1866 break;
1867 case POWER_RUNIC_POWER:
1869 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1870 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1871 } break;
1872 case POWER_RUNE:
1874 for(uint32 i = 0; i < MAX_RUNES; ++i)
1875 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1876 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1877 } break;
1878 case POWER_FOCUS:
1879 case POWER_HAPPINESS:
1880 case POWER_HEALTH:
1881 break;
1884 // Mana regen calculated in Player::UpdateManaRegen()
1885 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1886 if(power != POWER_MANA)
1888 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1889 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1890 if ((*i)->GetModifier()->m_miscvalue == power)
1891 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1894 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1896 curValue += uint32(addvalue);
1897 if (curValue > maxValue)
1898 curValue = maxValue;
1900 else
1902 if(curValue <= uint32(addvalue))
1903 curValue = 0;
1904 else
1905 curValue -= uint32(addvalue);
1907 SetPower(power, curValue);
1910 void Player::RegenerateHealth()
1912 uint32 curValue = GetHealth();
1913 uint32 maxValue = GetMaxHealth();
1915 if (curValue >= maxValue) return;
1917 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1919 float addvalue = 0.0f;
1921 // polymorphed case
1922 if ( IsPolymorphed() )
1923 addvalue = GetMaxHealth()/3;
1924 // normal regen case (maybe partly in combat case)
1925 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1927 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1928 if (!isInCombat())
1930 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1931 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1932 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1934 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1935 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1937 if(!IsStandState())
1938 addvalue *= 1.5;
1941 // always regeneration bonus (including combat)
1942 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1944 if(addvalue < 0)
1945 addvalue = 0;
1947 ModifyHealth(int32(addvalue));
1950 bool Player::CanInteractWithNPCs(bool alive) const
1952 if(alive && !isAlive())
1953 return false;
1954 if(isInFlight())
1955 return false;
1957 return true;
1960 Creature*
1961 Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
1963 // unit checks
1964 if (!guid)
1965 return NULL;
1967 if(!IsInWorld())
1968 return NULL;
1970 // exist (we need look pets also for some interaction (quest/etc)
1971 Creature *unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
1972 if (!unit)
1973 return NULL;
1975 // player check
1976 if(!CanInteractWithNPCs(!unit->isSpiritService()))
1977 return NULL;
1979 // appropriate npc type
1980 if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
1981 return NULL;
1983 // alive or spirit healer
1984 if(!unit->isAlive() && (!unit->isSpiritService() || isAlive() ))
1985 return NULL;
1987 // not allow interaction under control, but allow with own pets
1988 if(unit->GetCharmerGUID())
1989 return NULL;
1991 // not enemy
1992 if( unit->IsHostileTo(this))
1993 return NULL;
1995 // not unfriendly
1996 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
1997 if(factionTemplate->faction)
1998 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
1999 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
2000 return NULL;
2002 // not too far
2003 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
2004 return NULL;
2006 return unit;
2009 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
2011 if(GameObject *go = GetMap()->GetGameObject(guid))
2013 if(go->GetGoType() == type)
2015 float maxdist;
2016 switch(type)
2018 // TODO: find out how the client calculates the maximal usage distance to spellless working
2019 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2020 case GAMEOBJECT_TYPE_GUILD_BANK:
2021 case GAMEOBJECT_TYPE_MAILBOX:
2022 maxdist = 10.0f;
2023 break;
2024 case GAMEOBJECT_TYPE_FISHINGHOLE:
2025 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2026 break;
2027 default:
2028 maxdist = INTERACTION_DISTANCE;
2029 break;
2032 if (go->IsWithinDistInMap(this, maxdist))
2033 return go;
2035 sLog.outError("IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go->GetGOInfo()->name,
2036 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2039 return NULL;
2042 bool Player::IsUnderWater() const
2044 return IsInWater() &&
2045 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2048 void Player::SetInWater(bool apply)
2050 if(m_isInWater==apply)
2051 return;
2053 //define player in water by opcodes
2054 //move player's guid into HateOfflineList of those mobs
2055 //which can't swim and move guid back into ThreatList when
2056 //on surface.
2057 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2058 m_isInWater = apply;
2060 // remove auras that need water/land
2061 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2063 getHostilRefManager().updateThreatTables();
2066 void Player::SetGameMaster(bool on)
2068 if(on)
2070 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2071 setFaction(35);
2072 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2074 if (Pet* pet = GetPet())
2076 pet->setFaction(35);
2077 pet->getHostilRefManager().setOnlineOfflineState(false);
2080 for (int8 i = 0; i < MAX_TOTEM; ++i)
2081 if(m_TotemSlot[i])
2082 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2083 totem->setFaction(35);
2085 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2086 ResetContestedPvP();
2088 getHostilRefManager().setOnlineOfflineState(false);
2089 CombatStopWithPets();
2091 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2093 else
2095 // restore phase
2096 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2097 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2099 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2100 setFactionForRace(getRace());
2101 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2103 if (Pet* pet = GetPet())
2105 pet->setFaction(getFaction());
2106 pet->getHostilRefManager().setOnlineOfflineState(true);
2109 for (int8 i = 0; i < MAX_TOTEM; ++i)
2110 if(m_TotemSlot[i])
2111 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2112 totem->setFaction(getFaction());
2114 // restore FFA PvP Server state
2115 if(sWorld.IsFFAPvPRealm())
2116 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2118 // restore FFA PvP area state, remove not allowed for GM mounts
2119 UpdateArea(m_areaUpdateId);
2121 getHostilRefManager().setOnlineOfflineState(true);
2124 ObjectAccessor::UpdateVisibilityForPlayer(this);
2127 void Player::SetGMVisible(bool on)
2129 if(on)
2131 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2133 // Reapply stealth/invisibility if active or show if not any
2134 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2135 SetVisibility(VISIBILITY_GROUP_STEALTH);
2136 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2137 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2138 else
2139 SetVisibility(VISIBILITY_ON);
2141 else
2143 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2145 SetAcceptWhispers(false);
2146 SetGameMaster(true);
2148 SetVisibility(VISIBILITY_OFF);
2152 bool Player::IsGroupVisibleFor(Player* p) const
2154 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2156 default: return IsInSameGroupWith(p);
2157 case 1: return IsInSameRaidWith(p);
2158 case 2: return GetTeam()==p->GetTeam();
2162 bool Player::IsInSameGroupWith(Player const* p) const
2164 return p==this || GetGroup() != NULL &&
2165 GetGroup() == p->GetGroup() &&
2166 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2169 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2170 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2171 void Player::UninviteFromGroup()
2173 Group* group = GetGroupInvite();
2174 if(!group)
2175 return;
2177 group->RemoveInvite(this);
2179 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2181 if(group->IsCreated())
2183 group->Disband(true);
2184 objmgr.RemoveGroup(group);
2186 else
2187 group->RemoveAllInvites();
2189 delete group;
2193 void Player::RemoveFromGroup(Group* group, uint64 guid)
2195 if(group)
2197 if (group->RemoveMember(guid, 0) <= 1)
2199 // group->Disband(); already disbanded in RemoveMember
2200 objmgr.RemoveGroup(group);
2201 delete group;
2202 // removemember sets the player's group pointer to NULL
2207 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2209 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2210 data << uint64(victim ? victim->GetGUID() : 0); // guid
2211 data << uint32(GivenXP+RestXP); // given experience
2212 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2213 if(victim)
2215 data << uint32(GivenXP); // experience without rested bonus
2216 data << float(1); // 1 - none 0 - 100% group bonus output
2218 data << uint8(0); // new 2.4.0
2219 GetSession()->SendPacket(&data);
2222 void Player::GiveXP(uint32 xp, Unit* victim)
2224 if ( xp < 1 )
2225 return;
2227 if(!isAlive())
2228 return;
2230 uint32 level = getLevel();
2232 // XP to money conversion processed in Player::RewardQuest
2233 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2234 return;
2236 // handle SPELL_AURA_MOD_XP_PCT auras
2237 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2238 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2239 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2241 // XP resting bonus for kill
2242 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2244 SendLogXPGain(xp,victim,rested_bonus_xp);
2246 uint32 curXP = GetUInt32Value(PLAYER_XP);
2247 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2248 uint32 newXP = curXP + xp + rested_bonus_xp;
2250 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2252 newXP -= nextLvlXP;
2254 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2255 GiveLevel(level + 1);
2257 level = getLevel();
2258 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2261 SetUInt32Value(PLAYER_XP, newXP);
2264 // Update player to next level
2265 // Current player experience not update (must be update by caller)
2266 void Player::GiveLevel(uint32 level)
2268 if ( level == getLevel() )
2269 return;
2271 PlayerLevelInfo info;
2272 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2274 PlayerClassLevelInfo classInfo;
2275 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2277 // send levelup info to client
2278 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2279 data << uint32(level);
2280 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2281 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2282 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2283 data << uint32(0);
2284 data << uint32(0);
2285 data << uint32(0);
2286 data << uint32(0);
2287 data << uint32(0);
2288 data << uint32(0);
2289 // end for
2290 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2291 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2293 GetSession()->SendPacket(&data);
2295 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2297 //update level, max level of skills
2298 if(getLevel()!= level)
2299 m_Played_time[1] = 0; // Level Played Time reset
2300 SetLevel(level);
2301 UpdateSkillsForLevel ();
2303 // save base values (bonuses already included in stored stats
2304 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2305 SetCreateStat(Stats(i), info.stats[i]);
2307 SetCreateHealth(classInfo.basehealth);
2308 SetCreateMana(classInfo.basemana);
2310 InitTalentForLevel();
2311 InitTaxiNodesForLevel();
2312 InitGlyphsForLevel();
2314 UpdateAllStats();
2316 // set current level health and mana/energy to maximum after applying all mods.
2317 SetHealth(GetMaxHealth());
2318 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2319 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2320 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2321 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2322 SetPower(POWER_FOCUS, 0);
2323 SetPower(POWER_HAPPINESS, 0);
2325 // update level to hunter/summon pet
2326 if (Pet* pet = GetPet())
2327 pet->SynchronizeLevelWithOwner();
2329 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2332 void Player::InitTalentForLevel()
2334 uint32 level = getLevel();
2335 // talents base at level diff ( talents = level - 9 but some can be used already)
2336 if(level < 10)
2338 // Remove all talent points
2339 if(m_usedTalentCount > 0) // Free any used talents
2341 resetTalents(true);
2342 SetFreeTalentPoints(0);
2345 else
2347 uint32 talentPointsForLevel = CalculateTalentsPoints();
2349 // if used more that have then reset
2350 if(m_usedTalentCount > talentPointsForLevel)
2352 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2353 resetTalents(true);
2354 else
2355 SetFreeTalentPoints(0);
2357 // else update amount of free points
2358 else
2359 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2362 SendTalentsInfoData(false); // update at client
2365 void Player::InitStatsForLevel(bool reapplyMods)
2367 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2368 _RemoveAllStatBonuses();
2370 PlayerClassLevelInfo classInfo;
2371 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2373 PlayerLevelInfo info;
2374 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2376 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2377 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2379 UpdateSkillsForLevel ();
2381 // set default cast time multiplier
2382 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2384 // reset size before reapply auras
2385 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2387 // save base values (bonuses already included in stored stats
2388 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2389 SetCreateStat(Stats(i), info.stats[i]);
2391 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2392 SetStat(Stats(i), info.stats[i]);
2394 SetCreateHealth(classInfo.basehealth);
2396 //set create powers
2397 SetCreateMana(classInfo.basemana);
2399 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2401 InitStatBuffMods();
2403 //reset rating fields values
2404 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2405 SetUInt32Value(index, 0);
2407 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2408 for (int i = 0; i < 7; ++i)
2410 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2411 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2412 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2415 //reset attack power, damage and attack speed fields
2416 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2417 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2418 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2420 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2421 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2422 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2423 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2424 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2425 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2427 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2428 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2429 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2430 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2431 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2432 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2434 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2435 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2436 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2437 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2439 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2440 for (uint8 i = 0; i < 7; ++i)
2441 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2443 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2444 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2445 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2447 // Dodge percentage
2448 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2450 // set armor (resistance 0) to original value (create_agility*2)
2451 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2452 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2453 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2454 // set other resistance to original value (0)
2455 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2457 SetResistance(SpellSchools(i), 0);
2458 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2459 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2462 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2463 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2464 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2466 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2467 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2469 // Reset no reagent cost field
2470 for(int i = 0; i < 3; ++i)
2471 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2472 // Init data for form but skip reapply item mods for form
2473 InitDataForForm(reapplyMods);
2475 // save new stats
2476 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2477 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2479 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2481 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2482 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2484 // cleanup unit flags (will be re-applied if need at aura load).
2485 RemoveFlag( UNIT_FIELD_FLAGS,
2486 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2487 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2488 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2489 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2490 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2491 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2493 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2495 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2496 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2498 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2499 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2501 // restore if need some important flags
2502 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2504 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2505 _ApplyAllStatBonuses();
2507 // set current level health and mana/energy to maximum after applying all mods.
2508 SetHealth(GetMaxHealth());
2509 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2510 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2511 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2512 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2513 SetPower(POWER_FOCUS, 0);
2514 SetPower(POWER_HAPPINESS, 0);
2515 SetPower(POWER_RUNIC_POWER, 0);
2517 // update level to hunter/summon pet
2518 if (Pet* pet = GetPet())
2519 pet->SynchronizeLevelWithOwner();
2522 void Player::SendInitialSpells()
2524 time_t curTime = time(NULL);
2525 time_t infTime = curTime + MONTH/2;
2527 uint16 spellCount = 0;
2529 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2530 data << uint8(0);
2532 size_t countPos = data.wpos();
2533 data << uint16(spellCount); // spell count placeholder
2535 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2537 if(itr->second->state == PLAYERSPELL_REMOVED)
2538 continue;
2540 if(!itr->second->active || itr->second->disabled)
2541 continue;
2543 data << uint32(itr->first);
2544 data << uint16(0); // it's not slot id
2546 spellCount +=1;
2549 data.put<uint16>(countPos,spellCount); // write real count value
2551 uint16 spellCooldowns = m_spellCooldowns.size();
2552 data << uint16(spellCooldowns);
2553 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2555 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2556 if(!sEntry)
2557 continue;
2559 // not send infinity cooldown
2560 if(itr->second.end > infTime)
2561 continue;
2563 data << uint32(itr->first);
2565 time_t cooldown = 0;
2566 if(itr->second.end > curTime)
2567 cooldown = (itr->second.end-curTime)*IN_MILISECONDS;
2569 data << uint16(itr->second.itemid); // cast item id
2570 data << uint16(sEntry->Category); // spell category
2571 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2573 data << uint32(0); // cooldown
2574 data << uint32(cooldown); // category cooldown
2576 else
2578 data << uint32(cooldown); // cooldown
2579 data << uint32(0); // category cooldown
2583 GetSession()->SendPacket(&data);
2585 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2588 void Player::RemoveMail(uint32 id)
2590 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2592 if ((*itr)->messageID == id)
2594 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2595 m_mail.erase(itr);
2596 return;
2601 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2603 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2604 data << (uint32) mailId;
2605 data << (uint32) mailAction;
2606 data << (uint32) mailError;
2607 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2608 data << (uint32) equipError;
2609 else if( mailAction == MAIL_ITEM_TAKEN )
2611 data << (uint32) item_guid; // item guid low?
2612 data << (uint32) item_count; // item count?
2614 GetSession()->SendPacket(&data);
2617 void Player::SendNewMail()
2619 // deliver undelivered mail
2620 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2621 data << (uint32) 0;
2622 GetSession()->SendPacket(&data);
2625 void Player::UpdateNextMailTimeAndUnreads()
2627 // calculate next delivery time (min. from non-delivered mails
2628 // and recalculate unReadMail
2629 time_t cTime = time(NULL);
2630 m_nextMailDelivereTime = 0;
2631 unReadMails = 0;
2632 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2634 if((*itr)->deliver_time > cTime)
2636 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2637 m_nextMailDelivereTime = (*itr)->deliver_time;
2639 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2640 ++unReadMails;
2644 void Player::AddNewMailDeliverTime(time_t deliver_time)
2646 if(deliver_time <= time(NULL)) // ready now
2648 ++unReadMails;
2649 SendNewMail();
2651 else // not ready and no have ready mails
2653 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2654 m_nextMailDelivereTime = deliver_time;
2658 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2660 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2661 if (!spellInfo)
2663 // do character spell book cleanup (all characters)
2664 if(!IsInWorld() && !learning) // spell load case
2666 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2667 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2669 else
2670 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2672 return false;
2675 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2677 // do character spell book cleanup (all characters)
2678 if(!IsInWorld() && !learning) // spell load case
2680 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2681 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2683 else
2684 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2686 return false;
2689 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2691 bool dependent_set = false;
2692 bool disabled_case = false;
2693 bool superceded_old = false;
2695 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2696 if (itr != m_spells.end())
2698 uint32 next_active_spell_id = 0;
2699 // fix activate state for non-stackable low rank (and find next spell for !active case)
2700 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2702 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2703 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2705 if(HasSpell(next_itr->second))
2707 // high rank already known so this must !active
2708 active = false;
2709 next_active_spell_id = next_itr->second;
2710 break;
2715 // not do anything if already known in expected state
2716 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2717 itr->second->dependent == dependent && itr->second->disabled == disabled)
2719 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2720 itr->second->state = PLAYERSPELL_UNCHANGED;
2722 return false;
2725 // dependent spell known as not dependent, overwrite state
2726 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2728 itr->second->dependent = dependent;
2729 if (itr->second->state != PLAYERSPELL_NEW)
2730 itr->second->state = PLAYERSPELL_CHANGED;
2731 dependent_set = true;
2734 // update active state for known spell
2735 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2737 itr->second->active = active;
2739 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2740 itr->second->state = PLAYERSPELL_UNCHANGED;
2741 else if(itr->second->state != PLAYERSPELL_NEW)
2742 itr->second->state = PLAYERSPELL_CHANGED;
2744 if(active)
2746 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2747 CastSpell (this,spell_id,true);
2749 else if(IsInWorld())
2751 if(next_active_spell_id)
2753 // update spell ranks in spellbook and action bar
2754 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2755 data << uint32(spell_id);
2756 data << uint32(next_active_spell_id);
2757 GetSession()->SendPacket( &data );
2759 else
2761 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2762 data << uint32(spell_id);
2763 GetSession()->SendPacket(&data);
2767 return active; // learn (show in spell book if active now)
2770 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2772 if(itr->second->state != PLAYERSPELL_NEW)
2773 itr->second->state = PLAYERSPELL_CHANGED;
2774 itr->second->disabled = disabled;
2776 if(disabled)
2777 return false;
2779 disabled_case = true;
2781 else switch(itr->second->state)
2783 case PLAYERSPELL_UNCHANGED: // known saved spell
2784 return false;
2785 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2787 delete itr->second;
2788 m_spells.erase(itr);
2789 state = PLAYERSPELL_CHANGED;
2790 break; // need re-add
2792 default: // known not saved yet spell (new or modified)
2794 // can be in case spell loading but learned at some previous spell loading
2795 if(!IsInWorld() && !learning && !dependent_set)
2796 itr->second->state = PLAYERSPELL_UNCHANGED;
2798 return false;
2803 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2805 // talent: unlearn all other talent ranks (high and low)
2806 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2808 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2810 for(int i=0; i < MAX_TALENT_RANK; ++i)
2812 // skip learning spell and no rank spell case
2813 uint32 rankSpellId = talentInfo->RankID[i];
2814 if(!rankSpellId || rankSpellId==spell_id)
2815 continue;
2817 removeSpell(rankSpellId);
2821 // non talent spell: learn low ranks (recursive call)
2822 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2824 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2825 addSpell(prev_spell,active,true,true,disabled);
2826 else // at normal learning
2827 learnSpell(prev_spell,true);
2830 PlayerSpell *newspell = new PlayerSpell;
2831 newspell->state = state;
2832 newspell->active = active;
2833 newspell->dependent = dependent;
2834 newspell->disabled = disabled;
2836 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2837 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2839 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
2841 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
2842 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
2843 if(!i_spellInfo) continue;
2845 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
2847 if(itr2->second->active)
2849 if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
2851 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2853 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2854 data << uint32(itr2->first);
2855 data << uint32(spell_id);
2856 GetSession()->SendPacket( &data );
2859 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2860 itr2->second->active = false;
2861 if(itr2->second->state != PLAYERSPELL_NEW)
2862 itr2->second->state = PLAYERSPELL_CHANGED;
2863 superceded_old = true; // new spell replace old in action bars and spell book.
2865 else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
2867 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2869 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2870 data << uint32(spell_id);
2871 data << uint32(itr2->first);
2872 GetSession()->SendPacket( &data );
2875 // mark new spell as disable (not learned yet for client and will not learned)
2876 newspell->active = false;
2877 if(newspell->state != PLAYERSPELL_NEW)
2878 newspell->state = PLAYERSPELL_CHANGED;
2885 m_spells[spell_id] = newspell;
2887 // return false if spell disabled
2888 if (newspell->disabled)
2889 return false;
2892 uint32 talentCost = GetTalentSpellCost(spell_id);
2894 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2895 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2896 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2898 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2899 CastSpell(this, spell_id, true);
2901 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2902 else if (IsPassiveSpell(spell_id))
2904 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2905 CastSpell(this, spell_id, true);
2907 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2909 CastSpell(this, spell_id, true);
2910 return false;
2913 // update used talent points count
2914 m_usedTalentCount += talentCost;
2916 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2917 if(uint32 freeProfs = GetFreePrimaryProfessionPoints())
2919 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2920 SetFreePrimaryProfessions(freeProfs-1);
2923 // add dependent skills
2924 uint16 maxskill = GetMaxSkillValueForLevel();
2926 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2928 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2929 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2931 if(spellLearnSkill)
2933 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2934 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2936 if(skill_value < spellLearnSkill->value)
2937 skill_value = spellLearnSkill->value;
2939 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2941 if(skill_max_value < new_skill_max_value)
2942 skill_max_value = new_skill_max_value;
2944 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2946 else
2948 // not ranked skills
2949 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2951 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2952 if(!pSkill)
2953 continue;
2955 if(HasSkill(pSkill->id))
2956 continue;
2958 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2959 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2960 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
2962 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2964 case SKILL_RANGE_LANGUAGE:
2965 SetSkill(pSkill->id, 300, 300 );
2966 break;
2967 case SKILL_RANGE_LEVEL:
2968 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2969 break;
2970 case SKILL_RANGE_MONO:
2971 SetSkill(pSkill->id, 1, 1 );
2972 break;
2973 default:
2974 break;
2980 // learn dependent spells
2981 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2982 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2984 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2986 if(!itr2->second.autoLearned)
2988 if(!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
2989 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
2990 else // at normal learning
2991 learnSpell(itr2->second.spell,true);
2995 if(!GetSession()->PlayerLoading())
2997 // not ranked skills
2998 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3000 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3001 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3004 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3007 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3008 return active && !disabled && !superceded_old;
3011 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3013 bool need_cast = false;
3015 switch(spellInfo->Id)
3017 // some spells not have stance data expected cast at form change or present
3018 case 5420: need_cast = (m_form == FORM_TREE); break;
3019 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
3020 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
3021 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
3022 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
3023 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
3024 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
3025 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
3026 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
3027 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
3028 // another spells have proper stance data
3029 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
3032 //Check CasterAuraStates
3033 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3036 void Player::learnSpell(uint32 spell_id, bool dependent)
3038 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3040 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3041 bool active = disabled ? itr->second->active : true;
3043 bool learning = addSpell(spell_id,active,true,dependent,false);
3045 // learn all disabled higher ranks (recursive)
3046 if(disabled)
3048 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3049 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3051 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3052 if (iter != m_spells.end() && iter->second->disabled)
3053 learnSpell(i->second,false);
3057 // prevent duplicated entires in spell book, also not send if not in world (loading)
3058 if(!learning || !IsInWorld ())
3059 return;
3061 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3062 data << uint32(spell_id);
3063 GetSession()->SendPacket(&data);
3066 void Player::removeSpell(uint32 spell_id, bool disabled, bool update_action_bar_for_low_rank)
3068 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3069 if (itr == m_spells.end())
3070 return;
3072 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
3073 return;
3075 // unlearn non talent higher ranks (recursive)
3076 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3077 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3078 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3079 removeSpell(itr2->second,disabled);
3081 // re-search, it can be corrupted in prev loop
3082 itr = m_spells.find(spell_id);
3083 if (itr == m_spells.end())
3084 return; // already unleared
3086 bool cur_active = itr->second->active;
3087 bool cur_dependent = itr->second->dependent;
3089 if (disabled)
3091 itr->second->disabled = disabled;
3092 if(itr->second->state != PLAYERSPELL_NEW)
3093 itr->second->state = PLAYERSPELL_CHANGED;
3095 else
3097 if(itr->second->state == PLAYERSPELL_NEW)
3099 delete itr->second;
3100 m_spells.erase(itr);
3102 else
3103 itr->second->state = PLAYERSPELL_REMOVED;
3106 RemoveAurasDueToSpell(spell_id);
3108 // remove pet auras
3109 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
3110 RemovePetAura(petSpell);
3112 // free talent points
3113 uint32 talentCosts = GetTalentSpellCost(spell_id);
3114 if(talentCosts > 0)
3116 if(talentCosts < m_usedTalentCount)
3117 m_usedTalentCount -= talentCosts;
3118 else
3119 m_usedTalentCount = 0;
3122 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3123 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3125 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3126 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3127 SetFreePrimaryProfessions(freeProfs);
3130 // remove dependent skill
3131 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3132 if(spellLearnSkill)
3134 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3135 if(!prev_spell) // first rank, remove skill
3136 SetSkill(spellLearnSkill->skill,0,0);
3137 else
3139 // search prev. skill setting by spell ranks chain
3140 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3141 while(!prevSkill && prev_spell)
3143 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3144 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3147 if(!prevSkill) // not found prev skill setting, remove skill
3148 SetSkill(spellLearnSkill->skill,0,0);
3149 else // set to prev. skill setting values
3151 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3152 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3154 if(skill_value > prevSkill->value)
3155 skill_value = prevSkill->value;
3157 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3159 if(skill_max_value > new_skill_max_value)
3160 skill_max_value = new_skill_max_value;
3162 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3167 else
3169 // not ranked skills
3170 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3171 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3173 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3175 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3176 if(!pSkill)
3177 continue;
3179 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3180 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3181 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
3183 // not reset skills for professions and racial abilities
3184 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3185 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3186 continue;
3188 SetSkill(pSkill->id, 0, 0 );
3193 // remove dependent spells
3194 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3195 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3197 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3198 removeSpell(itr2->second.spell, disabled);
3200 // activate lesser rank in spellbook/action bar, and cast it if need
3201 bool prev_activate = false;
3203 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3205 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3207 // if talent then lesser rank also talent and need learn
3208 if(talentCosts)
3209 learnSpell (prev_id,false);
3210 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3211 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3213 // need manually update dependence state (learn spell ignore like attempts)
3214 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3215 if (prev_itr != m_spells.end())
3217 if(prev_itr->second->dependent != cur_dependent)
3219 prev_itr->second->dependent = cur_dependent;
3220 if(prev_itr->second->state != PLAYERSPELL_NEW)
3221 prev_itr->second->state = PLAYERSPELL_CHANGED;
3224 // now re-learn if need re-activate
3225 if(cur_active && !prev_itr->second->active)
3227 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3229 if(update_action_bar_for_low_rank)
3231 // downgrade spell ranks in spellbook and action bar
3232 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3233 data << uint32(spell_id);
3234 data << uint32(prev_id);
3235 GetSession()->SendPacket( &data );
3236 prev_activate = true;
3244 // remove from spell book if not replaced by lesser rank
3245 if(!prev_activate)
3247 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3248 data << uint32(spell_id);
3249 GetSession()->SendPacket(&data);
3254 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3256 m_spellCooldowns.erase(spell_id);
3258 if(update)
3260 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
3261 data << uint32(spell_id);
3262 data << uint64(GetGUID());
3263 SendDirectMessage(&data);
3267 void Player::RemoveArenaSpellCooldowns()
3269 // remove cooldowns on spells that has < 15 min CD
3270 SpellCooldowns::iterator itr, next;
3271 // iterate spell cooldowns
3272 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3274 next = itr;
3275 ++next;
3276 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3277 // check if spellentry is present and if the cooldown is less than 15 mins
3278 if( entry &&
3279 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3280 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3282 // notify player
3283 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
3284 data << uint32(itr->first);
3285 data << uint64(GetGUID());
3286 GetSession()->SendPacket(&data);
3287 // remove cooldown
3288 m_spellCooldowns.erase(itr);
3293 void Player::RemoveAllSpellCooldown()
3295 if(!m_spellCooldowns.empty())
3297 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3299 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
3300 data << uint32(itr->first);
3301 data << uint64(GetGUID());
3302 GetSession()->SendPacket(&data);
3304 m_spellCooldowns.clear();
3308 void Player::_LoadSpellCooldowns(QueryResult *result)
3310 // some cooldowns can be already set at aura loading...
3312 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3314 if(result)
3316 time_t curTime = time(NULL);
3320 Field *fields = result->Fetch();
3322 uint32 spell_id = fields[0].GetUInt32();
3323 uint32 item_id = fields[1].GetUInt32();
3324 time_t db_time = (time_t)fields[2].GetUInt64();
3326 if(!sSpellStore.LookupEntry(spell_id))
3328 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3329 continue;
3332 // skip outdated cooldown
3333 if(db_time <= curTime)
3334 continue;
3336 AddSpellCooldown(spell_id, item_id, db_time);
3338 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3340 while( result->NextRow() );
3342 delete result;
3346 void Player::_SaveSpellCooldowns()
3348 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3350 time_t curTime = time(NULL);
3351 time_t infTime = curTime + MONTH/2;
3353 // remove outdated and save active
3354 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3356 if(itr->second.end <= curTime)
3357 m_spellCooldowns.erase(itr++);
3358 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3360 CharacterDatabase.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" UI64FMTD "')", GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
3361 ++itr;
3363 else
3364 ++itr;
3368 uint32 Player::resetTalentsCost() const
3370 // The first time reset costs 1 gold
3371 if(m_resetTalentsCost < 1*GOLD)
3372 return 1*GOLD;
3373 // then 5 gold
3374 else if(m_resetTalentsCost < 5*GOLD)
3375 return 5*GOLD;
3376 // After that it increases in increments of 5 gold
3377 else if(m_resetTalentsCost < 10*GOLD)
3378 return 10*GOLD;
3379 else
3381 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3382 if(months > 0)
3384 // This cost will be reduced by a rate of 5 gold per month
3385 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3386 // to a minimum of 10 gold.
3387 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3389 else
3391 // After that it increases in increments of 5 gold
3392 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3393 // until it hits a cap of 50 gold.
3394 if(new_cost > 50*GOLD)
3395 new_cost = 50*GOLD;
3396 return new_cost;
3401 bool Player::resetTalents(bool no_cost)
3403 // not need after this call
3404 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3406 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3407 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3410 uint32 talentPointsForLevel = CalculateTalentsPoints();
3412 if (m_usedTalentCount == 0)
3414 SetFreeTalentPoints(talentPointsForLevel);
3415 return false;
3418 uint32 cost = 0;
3420 if(!no_cost)
3422 cost = resetTalentsCost();
3424 if (GetMoney() < cost)
3426 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3427 return false;
3431 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3433 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3435 if (!talentInfo) continue;
3437 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3439 if(!talentTabInfo)
3440 continue;
3442 // unlearn only talents for character class
3443 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3444 // to prevent unexpected lost normal learned spell skip another class talents
3445 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3446 continue;
3448 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3450 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3452 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3454 ++itr;
3455 continue;
3458 // remove learned spells (all ranks)
3459 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3461 // unlearn if first rank is talent or learned by talent
3462 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3464 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3465 itr = GetSpellMap().begin();
3466 continue;
3468 else
3469 ++itr;
3474 SetFreeTalentPoints(talentPointsForLevel);
3476 if(!no_cost)
3478 ModifyMoney(-(int32)cost);
3479 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3480 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3482 m_resetTalentsCost = cost;
3483 m_resetTalentsTime = time(NULL);
3486 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3487 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3488 /* when prev line will dropped use next line
3489 if(Pet* pet = GetPet())
3491 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3492 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3497 if(m_canTitanGrip)
3499 m_canTitanGrip = false;
3500 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3501 AutoUnequipOffhandIfNeed();
3504 return true;
3507 Mail* Player::GetMail(uint32 id)
3509 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3511 if ((*itr)->messageID == id)
3513 return (*itr);
3516 return NULL;
3519 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3521 if(target == this)
3523 Object::_SetCreateBits(updateMask, target);
3525 else
3527 for(uint16 index = 0; index < m_valuesCount; index++)
3529 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3530 updateMask->SetBit(index);
3535 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3537 if(target == this)
3539 Object::_SetUpdateBits(updateMask, target);
3541 else
3543 Object::_SetUpdateBits(updateMask, target);
3544 *updateMask &= updateVisualBits;
3548 void Player::InitVisibleBits()
3550 updateVisualBits.SetCount(PLAYER_END);
3552 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3553 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3554 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3555 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3556 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3557 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3558 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3559 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3560 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3561 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3562 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3563 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3564 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3565 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3566 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3567 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3568 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3569 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3570 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3571 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3572 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3573 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3574 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3575 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3576 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3577 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3578 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3579 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3580 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3581 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3582 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3583 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3584 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3585 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3586 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3587 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3588 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3589 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3590 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3591 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3592 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3593 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3594 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3595 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3596 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3597 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3598 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3599 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3600 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3601 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3602 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3603 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3604 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3605 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3606 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3608 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3609 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3610 updateVisualBits.SetBit(PLAYER_FLAGS);
3611 updateVisualBits.SetBit(PLAYER_GUILDID);
3612 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3613 updateVisualBits.SetBit(PLAYER_BYTES);
3614 updateVisualBits.SetBit(PLAYER_BYTES_2);
3615 updateVisualBits.SetBit(PLAYER_BYTES_3);
3616 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3617 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3619 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3620 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3621 updateVisualBits.SetBit(i);
3623 // Players visible items are not inventory stuff
3624 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3626 uint32 offset = i * 2;
3628 // item entry
3629 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3630 // enchant
3631 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3634 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3637 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3639 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3641 if(m_items[i] == NULL)
3642 continue;
3644 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3647 if(target == this)
3649 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3651 if(m_items[i] == NULL)
3652 continue;
3654 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3656 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3658 if(m_items[i] == NULL)
3659 continue;
3661 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3665 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3668 void Player::DestroyForPlayer( Player *target ) const
3670 Unit::DestroyForPlayer( target );
3672 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3674 if(m_items[i] == NULL)
3675 continue;
3677 m_items[i]->DestroyForPlayer( target );
3680 if(target == this)
3682 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3684 if(m_items[i] == NULL)
3685 continue;
3687 m_items[i]->DestroyForPlayer( target );
3689 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3691 if(m_items[i] == NULL)
3692 continue;
3694 m_items[i]->DestroyForPlayer( target );
3699 bool Player::HasSpell(uint32 spell) const
3701 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3702 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3703 !itr->second->disabled);
3706 bool Player::HasActiveSpell(uint32 spell) const
3708 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3709 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3710 itr->second->active && !itr->second->disabled);
3713 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3715 if (!trainer_spell)
3716 return TRAINER_SPELL_RED;
3718 if (!trainer_spell->learnedSpell)
3719 return TRAINER_SPELL_RED;
3721 // known spell
3722 if(HasSpell(trainer_spell->learnedSpell))
3723 return TRAINER_SPELL_GRAY;
3725 // check race/class requirement
3726 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3727 return TRAINER_SPELL_RED;
3729 // check level requirement
3730 if(getLevel() < trainer_spell->reqLevel)
3731 return TRAINER_SPELL_RED;
3733 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3735 // check prev.rank requirement
3736 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3737 return TRAINER_SPELL_RED;
3739 // check additional spell requirement
3740 if(spell_chain->req && !HasSpell(spell_chain->req))
3741 return TRAINER_SPELL_RED;
3744 // check skill requirement
3745 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3746 return TRAINER_SPELL_RED;
3748 // exist, already checked at loading
3749 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3751 // secondary prof. or not prof. spell
3752 uint32 skill = spell->EffectMiscValue[1];
3754 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3755 return TRAINER_SPELL_GREEN;
3757 // check primary prof. limit
3758 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
3759 return TRAINER_SPELL_GREEN_DISABLED;
3761 return TRAINER_SPELL_GREEN;
3764 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3766 uint32 guid = GUID_LOPART(playerguid);
3768 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3769 // bones will be deleted by corpse/bones deleting thread shortly
3770 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3772 // remove from guild
3773 uint32 guildId = GetGuildIdFromDB(playerguid);
3774 if(guildId != 0)
3776 Guild* guild = objmgr.GetGuildById(guildId);
3777 if(guild)
3778 guild->DelMember(guid);
3781 // remove from arena teams
3782 LeaveAllArenaTeams(playerguid);
3784 // the player was uninvited already on logout so just remove from group
3785 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3786 if(resultGroup)
3788 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3789 delete resultGroup;
3790 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3791 if(group)
3793 RemoveFromGroup(group, playerguid);
3797 // remove signs from petitions (also remove petitions if owner);
3798 RemovePetitionsAndSigns(playerguid, 10);
3800 // return back all mails with COD and Item 0 1 2 3 4 5 6
3801 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);
3802 if(resultMail)
3806 Field *fields = resultMail->Fetch();
3808 uint32 mail_id = fields[0].GetUInt32();
3809 uint16 mailTemplateId= fields[1].GetUInt16();
3810 uint32 sender = fields[2].GetUInt32();
3811 std::string subject = fields[3].GetCppString();
3812 uint32 itemTextId = fields[4].GetUInt32();
3813 uint32 money = fields[5].GetUInt32();
3814 bool has_items = fields[6].GetBool();
3816 //we can return mail now
3817 //so firstly delete the old one
3818 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3820 MailItemsInfo mi;
3821 if(has_items)
3823 // data needs to be at first place for Item::LoadFromDB
3824 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);
3825 if(resultItems)
3829 Field *fields2 = resultItems->Fetch();
3831 uint32 item_guidlow = fields2[1].GetUInt32();
3832 uint32 item_template = fields2[2].GetUInt32();
3834 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3835 if(!itemProto)
3837 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3838 continue;
3841 Item *pItem = NewItemOrBag(itemProto);
3842 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3844 pItem->FSetState(ITEM_REMOVED);
3845 pItem->SaveToDB(); // it also deletes item object !
3846 continue;
3849 mi.AddItem(item_guidlow, item_template, pItem);
3851 while (resultItems->NextRow());
3853 delete resultItems;
3857 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3859 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3861 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3863 while (resultMail->NextRow());
3865 delete resultMail;
3868 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3869 // Get guids of character's pets, will deleted in transaction
3870 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3872 // NOW we can finally clear other DB data related to character
3873 CharacterDatabase.BeginTransaction();
3874 if (resultPets)
3878 Field *fields3 = resultPets->Fetch();
3879 uint32 petguidlow = fields3[0].GetUInt32();
3880 Pet::DeleteFromDB(petguidlow);
3881 } while (resultPets->NextRow());
3882 delete resultPets;
3885 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3886 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3887 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3888 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3889 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3890 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3891 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3892 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3893 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3894 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3895 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3896 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3897 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3898 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3899 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3900 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3901 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3902 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3903 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3904 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3905 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3906 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3907 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
3908 CharacterDatabase.CommitTransaction();
3910 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3911 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3914 void Player::SetMovement(PlayerMovementType pType)
3916 WorldPacket data;
3917 switch(pType)
3919 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3920 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3921 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3922 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3923 default:
3924 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3925 return;
3927 data.append(GetPackGUID());
3928 data << uint32(0);
3929 GetSession()->SendPacket( &data );
3932 /* Preconditions:
3933 - a resurrectable corpse must not be loaded for the player (only bones)
3934 - the player must be in world
3936 void Player::BuildPlayerRepop()
3938 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3939 data.append(GetPackGUID());
3940 GetSession()->SendPacket(&data);
3942 if(getRace() == RACE_NIGHTELF)
3943 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)
3944 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3946 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3947 // there must be SMSG.STOP_MIRROR_TIMER
3948 // there we must send 888 opcode
3950 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3951 if(GetCorpse())
3953 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3954 assert(false);
3957 // create a corpse and place it at the player's location
3958 CreateCorpse();
3959 Corpse *corpse = GetCorpse();
3960 if(!corpse)
3962 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3963 return;
3965 GetMap()->Add(corpse);
3967 // convert player body to ghost
3968 SetHealth( 1 );
3970 SetMovement(MOVE_WATER_WALK);
3971 if(!GetSession()->isLogingOut())
3972 SetMovement(MOVE_UNROOT);
3974 // BG - remove insignia related
3975 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3977 SendCorpseReclaimDelay();
3979 // to prevent cheating
3980 corpse->ResetGhostTime();
3982 StopMirrorTimers(); //disable timers(bars)
3984 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3986 // set and clear other
3987 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
3990 void Player::SendDelayResponse(const uint32 ml_seconds)
3992 //FIXME: is this delay time arg really need? 50msec by default in code
3993 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3994 data << (uint32)time(NULL);
3995 data << (uint32)0;
3996 GetSession()->SendPacket( &data );
3999 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
4001 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
4002 data << uint32(-1);
4003 data << float(0);
4004 data << float(0);
4005 data << float(0);
4006 GetSession()->SendPacket(&data);
4008 // speed change, land walk
4010 // remove death flag + set aura
4011 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4012 if(getRace() == RACE_NIGHTELF)
4013 RemoveAurasDueToSpell(20584); // speed bonuses
4014 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4016 setDeathState(ALIVE);
4018 SetMovement(MOVE_LAND_WALK);
4019 SetMovement(MOVE_UNROOT);
4021 m_deathTimer = 0;
4023 // set health/powers (0- will be set in caller)
4024 if(restore_percent>0.0f)
4026 SetHealth(uint32(GetMaxHealth()*restore_percent));
4027 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4028 SetPower(POWER_RAGE, 0);
4029 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4032 // trigger update zone for alive state zone updates
4033 uint32 newzone, newarea;
4034 GetZoneAndAreaId(newzone,newarea);
4035 UpdateZone(newzone,newarea);
4037 // update visibility
4038 ObjectAccessor::UpdateVisibilityForPlayer(this);
4040 if(!applySickness)
4041 return;
4043 //Characters from level 1-10 are not affected by resurrection sickness.
4044 //Characters from level 11-19 will suffer from one minute of sickness
4045 //for each level they are above 10.
4046 //Characters level 20 and up suffer from ten minutes of sickness.
4047 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
4049 if(int32(getLevel()) >= startLevel)
4051 // set resurrection sickness
4052 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4054 // not full duration
4055 if(int32(getLevel()) < startLevel+9)
4057 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4059 for(int i =0; i < 3; ++i)
4061 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4063 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4064 Aur->SendAuraUpdate(false);
4071 void Player::KillPlayer()
4073 SetMovement(MOVE_ROOT);
4075 StopMirrorTimers(); //disable timers(bars)
4077 setDeathState(CORPSE);
4078 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4080 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4081 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4083 // 6 minutes until repop at graveyard
4084 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4086 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4088 // don't create corpse at this moment, player might be falling
4090 // update visibility
4091 ObjectAccessor::UpdateObjectVisibility(this);
4094 void Player::CreateCorpse()
4096 // prevent existence 2 corpse for player
4097 SpawnCorpseBones();
4099 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4101 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4102 SetPvPDeath(false);
4104 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4106 delete corpse;
4107 return;
4110 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4111 _pb = GetUInt32Value(PLAYER_BYTES);
4112 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4114 uint8 race = (uint8)(_uf);
4115 uint8 skin = (uint8)(_pb);
4116 uint8 face = (uint8)(_pb >> 8);
4117 uint8 hairstyle = (uint8)(_pb >> 16);
4118 uint8 haircolor = (uint8)(_pb >> 24);
4119 uint8 facialhair = (uint8)(_pb2);
4121 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4122 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4124 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4125 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4127 uint32 flags = CORPSE_FLAG_UNK2;
4128 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4129 flags |= CORPSE_FLAG_HIDE_HELM;
4130 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4131 flags |= CORPSE_FLAG_HIDE_CLOAK;
4132 if(InBattleGround() && !InArena())
4133 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4134 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4136 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4138 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4140 uint32 iDisplayID;
4141 uint16 iIventoryType;
4142 uint32 _cfi;
4143 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4145 if(m_items[i])
4147 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4148 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4150 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4151 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4155 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4156 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4157 assert(entry);
4158 if(entry->map_type != MAP_BATTLEGROUND)
4159 corpse->SaveToDB();
4161 // register for player, but not show
4162 ObjectAccessor::Instance().AddCorpse(corpse);
4165 void Player::SpawnCorpseBones()
4167 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4168 SaveToDB(); // prevent loading as ghost without corpse
4171 Corpse* Player::GetCorpse() const
4173 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4176 void Player::DurabilityLossAll(double percent, bool inventory)
4178 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4179 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4180 DurabilityLoss(pItem,percent);
4182 if(inventory)
4184 // bags not have durability
4185 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4187 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4188 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4189 DurabilityLoss(pItem,percent);
4191 // keys not have durability
4192 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4194 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4195 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4196 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4197 if(Item* pItem = GetItemByPos( i, j ))
4198 DurabilityLoss(pItem,percent);
4202 void Player::DurabilityLoss(Item* item, double percent)
4204 if(!item )
4205 return;
4207 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4209 if(!pMaxDurability)
4210 return;
4212 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4214 if(pDurabilityLoss < 1 )
4215 pDurabilityLoss = 1;
4217 DurabilityPointsLoss(item,pDurabilityLoss);
4220 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4222 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4223 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4224 DurabilityPointsLoss(pItem,points);
4226 if(inventory)
4228 // bags not have durability
4229 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4231 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4232 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4233 DurabilityPointsLoss(pItem,points);
4235 // keys not have durability
4236 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4238 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4239 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4240 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4241 if(Item* pItem = GetItemByPos( i, j ))
4242 DurabilityPointsLoss(pItem,points);
4246 void Player::DurabilityPointsLoss(Item* item, int32 points)
4248 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4249 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4250 int32 pNewDurability = pOldDurability - points;
4252 if (pNewDurability < 0)
4253 pNewDurability = 0;
4254 else if (pNewDurability > pMaxDurability)
4255 pNewDurability = pMaxDurability;
4257 if (pOldDurability != pNewDurability)
4259 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4260 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4261 _ApplyItemMods(item,item->GetSlot(), false);
4263 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4265 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4266 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4267 _ApplyItemMods(item,item->GetSlot(), true);
4269 item->SetState(ITEM_CHANGED, this);
4273 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4275 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4276 DurabilityPointsLoss(pItem,1);
4279 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4281 uint32 TotalCost = 0;
4282 // equipped, backpack, bags itself
4283 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4284 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4286 // bank, buyback and keys not repaired
4288 // items in inventory bags
4289 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4290 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4291 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4292 return TotalCost;
4295 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4297 Item* item = GetItemByPos(pos);
4299 uint32 TotalCost = 0;
4300 if(!item)
4301 return TotalCost;
4303 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4304 if(!maxDurability)
4305 return TotalCost;
4307 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4309 if(cost)
4311 uint32 LostDurability = maxDurability - curDurability;
4312 if(LostDurability>0)
4314 ItemPrototype const *ditemProto = item->GetProto();
4316 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4317 if(!dcost)
4319 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4320 return TotalCost;
4323 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4324 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4325 if(!dQualitymodEntry)
4327 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4328 return TotalCost;
4331 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4332 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4334 costs = uint32(costs * discountMod);
4336 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4337 costs = 1;
4339 if (guildBank)
4341 if (GetGuildId()==0)
4343 DEBUG_LOG("You are not member of a guild");
4344 return TotalCost;
4347 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4348 if (!pGuild)
4349 return TotalCost;
4351 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4353 DEBUG_LOG("You do not have rights to withdraw for repairs");
4354 return TotalCost;
4357 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4359 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4360 return TotalCost;
4363 if (pGuild->GetGuildBankMoney() < costs)
4365 DEBUG_LOG("There is not enough money in bank");
4366 return TotalCost;
4369 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4370 TotalCost = costs;
4372 else if (GetMoney() < costs)
4374 DEBUG_LOG("You do not have enough money");
4375 return TotalCost;
4377 else
4378 ModifyMoney( -int32(costs) );
4382 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4383 item->SetState(ITEM_CHANGED, this);
4385 // reapply mods for total broken and repaired item if equipped
4386 if(IsEquipmentPos(pos) && !curDurability)
4387 _ApplyItemMods(item,pos & 255, true);
4388 return TotalCost;
4391 void Player::RepopAtGraveyard()
4393 // note: this can be called also when the player is alive
4394 // for example from WorldSession::HandleMovementOpcodes
4396 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4398 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4399 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4401 ResurrectPlayer(0.5f);
4402 SpawnCorpseBones();
4405 WorldSafeLocsEntry const *ClosestGrave = NULL;
4407 // Special handle for battleground maps
4408 if( BattleGround *bg = GetBattleGround() )
4409 ClosestGrave = bg->GetClosestGraveYard(this);
4410 else
4411 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4413 // stop countdown until repop
4414 m_deathTimer = 0;
4416 // if no grave found, stay at the current location
4417 // and don't show spirit healer location
4418 if(ClosestGrave)
4420 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4421 if(isDead()) // not send if alive, because it used in TeleportTo()
4423 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4424 data << ClosestGrave->map_id;
4425 data << ClosestGrave->x;
4426 data << ClosestGrave->y;
4427 data << ClosestGrave->z;
4428 GetSession()->SendPacket(&data);
4433 void Player::JoinedChannel(Channel *c)
4435 m_channels.push_back(c);
4438 void Player::LeftChannel(Channel *c)
4440 m_channels.remove(c);
4443 void Player::CleanupChannels()
4445 while(!m_channels.empty())
4447 Channel* ch = *m_channels.begin();
4448 m_channels.erase(m_channels.begin()); // remove from player's channel list
4449 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4450 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4451 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4454 sLog.outDebug("Player: channels cleaned up!");
4457 void Player::UpdateLocalChannels(uint32 newZone )
4459 if(m_channels.empty())
4460 return;
4462 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4463 if(!current_zone)
4464 return;
4466 ChannelMgr* cMgr = channelMgr(GetTeam());
4467 if(!cMgr)
4468 return;
4470 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4472 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4474 next = i; ++next;
4476 // skip non built-in channels
4477 if(!(*i)->IsConstant())
4478 continue;
4480 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4481 if(!ch)
4482 continue;
4484 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4485 continue;
4487 // new channel
4488 char new_channel_name_buf[100];
4489 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4490 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4492 if((*i)!=new_channel)
4494 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4496 // leave old channel
4497 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4498 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4499 LeftChannel(*i); // remove from player's channel list
4500 cMgr->LeftChannel(name); // delete if empty
4503 sLog.outDebug("Player: channels cleaned up!");
4506 void Player::LeaveLFGChannel()
4508 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4510 if((*i)->IsLFG())
4512 (*i)->Leave(GetGUID());
4513 break;
4518 void Player::UpdateDefense()
4520 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4522 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4524 // update dependent from defense skill part
4525 UpdateDefenseBonusesMod();
4529 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4531 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4533 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4534 return;
4537 float val = 1.0f;
4539 switch(modType)
4541 case FLAT_MOD:
4542 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4543 break;
4544 case PCT_MOD:
4545 if(amount <= -100.0f)
4546 amount = -200.0f;
4548 val = (100.0f + amount) / 100.0f;
4549 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4550 break;
4553 if(!CanModifyStats())
4554 return;
4556 switch(modGroup)
4558 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4559 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4560 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4561 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4562 default: break;
4566 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4568 if(modGroup >= BASEMOD_END || modType > MOD_END)
4570 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4571 return 0.0f;
4574 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4575 return 0.0f;
4577 return m_auraBaseMod[modGroup][modType];
4580 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4582 if(modGroup >= BASEMOD_END)
4584 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4585 return 0.0f;
4588 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4589 return 0.0f;
4591 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4594 uint32 Player::GetShieldBlockValue() const
4596 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4598 value = (value < 0) ? 0 : value;
4600 return uint32(value);
4603 float Player::GetMeleeCritFromAgility()
4605 uint32 level = getLevel();
4606 uint32 pclass = getClass();
4608 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4610 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4611 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4612 if (critBase==NULL || critRatio==NULL)
4613 return 0.0f;
4615 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4616 return crit*100.0f;
4619 float Player::GetDodgeFromAgility()
4621 // Table for base dodge values
4622 float dodge_base[MAX_CLASSES] = {
4623 0.0075f, // Warrior
4624 0.00652f, // Paladin
4625 -0.0545f, // Hunter
4626 -0.0059f, // Rogue
4627 0.03183f, // Priest
4628 0.0114f, // DK
4629 0.0167f, // Shaman
4630 0.034575f, // Mage
4631 0.02011f, // Warlock
4632 0.0f, // ??
4633 -0.0187f // Druid
4635 // Crit/agility to dodge/agility coefficient multipliers
4636 float crit_to_dodge[MAX_CLASSES] = {
4637 1.1f, // Warrior
4638 1.0f, // Paladin
4639 1.6f, // Hunter
4640 2.0f, // Rogue
4641 1.0f, // Priest
4642 1.0f, // DK?
4643 1.0f, // Shaman
4644 1.0f, // Mage
4645 1.0f, // Warlock
4646 0.0f, // ??
4647 1.7f // Druid
4650 uint32 level = getLevel();
4651 uint32 pclass = getClass();
4653 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4655 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4656 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4657 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4658 return 0.0f;
4660 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4661 return dodge*100.0f;
4664 float Player::GetSpellCritFromIntellect()
4666 uint32 level = getLevel();
4667 uint32 pclass = getClass();
4669 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4671 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4672 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4673 if (critBase==NULL || critRatio==NULL)
4674 return 0.0f;
4676 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4677 return crit*100.0f;
4680 float Player::GetRatingCoefficient(CombatRating cr) const
4682 uint32 level = getLevel();
4684 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4686 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4687 if (Rating == NULL)
4688 return 1.0f; // By default use minimum coefficient (not must be called)
4690 return Rating->ratio;
4693 float Player::GetRatingBonusValue(CombatRating cr) const
4695 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4698 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4700 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f;
4701 if (melee>33.0f) melee = 33.0f;
4702 return uint32 (melee * damage /100.0f);
4705 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4707 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f;
4708 if (ranged>33.0f) ranged=33.0f;
4709 return uint32 (ranged * damage /100.0f);
4712 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4714 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f;
4715 // In wow script resilience limited to 33%
4716 if (spell>33.0f)
4717 spell = 33.0f;
4718 return uint32 (spell * damage / 100.0f);
4721 uint32 Player::GetDotDamageReduction(uint32 damage) const
4723 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4724 // Dot resilience not limited (limit it by 100%)
4725 if (spellDot > 100.0f)
4726 spellDot = 100.0f;
4727 return uint32 (spellDot * damage / 100.0f);
4730 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4732 switch (attType)
4734 case BASE_ATTACK:
4735 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4736 case OFF_ATTACK:
4737 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4738 default:
4739 break;
4741 return 0.0f;
4744 float Player::OCTRegenHPPerSpirit()
4746 uint32 level = getLevel();
4747 uint32 pclass = getClass();
4749 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4751 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4752 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4753 if (baseRatio==NULL || moreRatio==NULL)
4754 return 0.0f;
4756 // Formula from PaperDollFrame script
4757 float spirit = GetStat(STAT_SPIRIT);
4758 float baseSpirit = spirit;
4759 if (baseSpirit>50) baseSpirit = 50;
4760 float moreSpirit = spirit - baseSpirit;
4761 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4762 return regen;
4765 float Player::OCTRegenMPPerSpirit()
4767 uint32 level = getLevel();
4768 uint32 pclass = getClass();
4770 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4772 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4773 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4774 if (moreRatio==NULL)
4775 return 0.0f;
4777 // Formula get from PaperDollFrame script
4778 float spirit = GetStat(STAT_SPIRIT);
4779 float regen = spirit * moreRatio->ratio;
4780 return regen;
4783 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4785 m_baseRatingValue[cr]+=(apply ? value : -value);
4787 int32 amount = uint32(m_baseRatingValue[cr]);
4788 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4789 // stat used stored in miscValueB for this aura
4790 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4791 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4792 if ((*i)->GetMiscValue() & (1<<cr))
4793 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4794 if (amount < 0)
4795 amount = 0;
4796 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4798 float RatingCoeffecient = GetRatingCoefficient(cr);
4799 float RatingChange = 0.0f;
4801 bool affectStats = CanModifyStats();
4803 switch (cr)
4805 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4806 case CR_DEFENSE_SKILL:
4807 UpdateDefenseBonusesMod();
4808 break;
4809 case CR_DODGE:
4810 UpdateDodgePercentage();
4811 break;
4812 case CR_PARRY:
4813 UpdateParryPercentage();
4814 break;
4815 case CR_BLOCK:
4816 UpdateBlockPercentage();
4817 break;
4818 case CR_HIT_MELEE:
4819 UpdateMeleeHitChances();
4820 break;
4821 case CR_HIT_RANGED:
4822 UpdateRangedHitChances();
4823 break;
4824 case CR_HIT_SPELL:
4825 UpdateSpellHitChances();
4826 break;
4827 case CR_CRIT_MELEE:
4828 if(affectStats)
4830 UpdateCritPercentage(BASE_ATTACK);
4831 UpdateCritPercentage(OFF_ATTACK);
4833 break;
4834 case CR_CRIT_RANGED:
4835 if(affectStats)
4836 UpdateCritPercentage(RANGED_ATTACK);
4837 break;
4838 case CR_CRIT_SPELL:
4839 if(affectStats)
4840 UpdateAllSpellCritChances();
4841 break;
4842 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4843 case CR_HIT_TAKEN_RANGED:
4844 break;
4845 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4846 break;
4847 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4848 case CR_CRIT_TAKEN_RANGED:
4849 break;
4850 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4851 break;
4852 case CR_HASTE_MELEE:
4853 RatingChange = value / RatingCoeffecient;
4854 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4855 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4856 break;
4857 case CR_HASTE_RANGED:
4858 RatingChange = value / RatingCoeffecient;
4859 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4860 break;
4861 case CR_HASTE_SPELL:
4862 RatingChange = value / RatingCoeffecient;
4863 ApplyCastTimePercentMod(RatingChange,apply);
4864 break;
4865 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4866 case CR_WEAPON_SKILL_OFFHAND:
4867 case CR_WEAPON_SKILL_RANGED:
4868 break;
4869 case CR_EXPERTISE:
4870 if(affectStats)
4872 UpdateExpertise(BASE_ATTACK);
4873 UpdateExpertise(OFF_ATTACK);
4875 break;
4876 case CR_ARMOR_PENETRATION:
4877 break;
4881 void Player::SetRegularAttackTime()
4883 for(int i = 0; i < MAX_ATTACK; ++i)
4885 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4886 if(tmpitem && !tmpitem->IsBroken())
4888 ItemPrototype const *proto = tmpitem->GetProto();
4889 if(proto->Delay)
4890 SetAttackTime(WeaponAttackType(i), proto->Delay);
4891 else
4892 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4897 //skill+step, checking for max value
4898 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4900 if(!skill_id)
4901 return false;
4903 uint16 i=0;
4904 for (; i < PLAYER_MAX_SKILLS; ++i)
4905 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4906 break;
4908 if(i>=PLAYER_MAX_SKILLS)
4909 return false;
4911 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4912 uint32 value = SKILL_VALUE(data);
4913 uint32 max = SKILL_MAX(data);
4915 if ((!max) || (!value) || (value >= max))
4916 return false;
4918 if (value*512 < max*urand(0,512))
4920 uint32 new_value = value+step;
4921 if(new_value > max)
4922 new_value = max;
4924 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4925 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
4926 return true;
4929 return false;
4932 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4934 if ( SkillValue >= GrayLevel )
4935 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4936 if ( SkillValue >= GreenLevel )
4937 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4938 if ( SkillValue >= YellowLevel )
4939 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4940 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4943 bool Player::UpdateCraftSkill(uint32 spellid)
4945 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4947 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4948 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4950 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4952 if(_spell_idx->second->skillId)
4954 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4956 // Alchemy Discoveries here
4957 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4958 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4960 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4961 learnSpell(discoveredSpell,false);
4964 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4966 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4967 _spell_idx->second->max_value,
4968 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4969 _spell_idx->second->min_value),
4970 craft_skill_gain);
4973 return false;
4976 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4978 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4980 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4982 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4983 switch (SkillId)
4985 case SKILL_HERBALISM:
4986 case SKILL_LOCKPICKING:
4987 case SKILL_JEWELCRAFTING:
4988 case SKILL_INSCRIPTION:
4989 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4990 case SKILL_SKINNING:
4991 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4992 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4993 else
4994 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4995 case SKILL_MINING:
4996 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4997 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4998 else
4999 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
5001 return false;
5004 bool Player::UpdateFishingSkill()
5006 sLog.outDebug("UpdateFishingSkill");
5008 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5010 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5012 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5014 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5017 // levels sync. with spell requirement for skill levels to learn
5018 // bonus abilities in sSkillLineAbilityStore
5019 // Used only to avoid scan DBC at each skill grow
5020 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5022 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5024 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5025 if ( !SkillId )
5026 return false;
5028 if(Chance <= 0) // speedup in 0 chance case
5030 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5031 return false;
5034 uint16 i=0;
5035 for (; i < PLAYER_MAX_SKILLS; ++i)
5036 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
5037 if ( i >= PLAYER_MAX_SKILLS )
5038 return false;
5040 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5041 uint16 SkillValue = SKILL_VALUE(data);
5042 uint16 MaxValue = SKILL_MAX(data);
5044 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5045 return false;
5047 int32 Roll = irand(1,1000);
5049 if ( Roll <= Chance )
5051 uint32 new_value = SkillValue+step;
5052 if(new_value > MaxValue)
5053 new_value = MaxValue;
5055 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
5056 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5058 if((SkillValue < *bsl && new_value >= *bsl))
5060 learnSkillRewardedSpells( SkillId, new_value);
5061 break;
5064 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5065 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5066 return true;
5069 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5070 return false;
5073 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5075 // no skill gain in pvp
5076 Unit *pVictim = getVictim();
5077 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5078 return;
5080 if(IsInFeralForm())
5081 return; // always maximized SKILL_FERAL_COMBAT in fact
5083 if(m_form == FORM_TREE)
5084 return; // use weapon but not skill up
5086 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5088 switch(attType)
5090 case BASE_ATTACK:
5092 Item *tmpitem = GetWeaponForAttack(attType,true);
5094 if (!tmpitem)
5095 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5096 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5097 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5098 break;
5100 case OFF_ATTACK:
5101 case RANGED_ATTACK:
5103 Item *tmpitem = GetWeaponForAttack(attType,true);
5104 if (tmpitem)
5105 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5106 break;
5109 UpdateAllCritPercentages();
5112 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5114 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5115 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5116 uint32 moblevel = pVictim->getLevelForTarget(this);
5117 if(moblevel < greylevel)
5118 return;
5120 if (moblevel > plevel + 5)
5121 moblevel = plevel + 5;
5123 uint32 lvldif = moblevel - greylevel;
5124 if(lvldif < 3)
5125 lvldif = 3;
5127 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5128 if(skilldif <= 0)
5129 return;
5131 float chance = float(3 * lvldif * skilldif) / plevel;
5132 if(!defence)
5134 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5135 chance *= 0.1f * GetStat(STAT_INTELLECT);
5138 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5140 if(roll_chance_f(chance))
5142 if(defence)
5143 UpdateDefense();
5144 else
5145 UpdateWeaponSkill(attType);
5147 else
5148 return;
5151 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5153 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5154 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5156 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5157 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5158 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5160 if(talent) // permanent bonus stored in high part
5161 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5162 else // temporary/item bonus stored in low part
5163 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5164 return;
5168 void Player::UpdateSkillsForLevel()
5170 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5171 uint32 maxSkill = GetMaxSkillValueForLevel();
5173 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5175 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5176 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5178 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5180 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5181 if(!pSkill)
5182 continue;
5184 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5185 continue;
5187 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5188 uint32 max = SKILL_MAX(data);
5189 uint32 val = SKILL_VALUE(data);
5191 /// update only level dependent max skill values
5192 if(max!=1)
5194 /// miximize skill always
5195 if(alwaysMaxSkill)
5196 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5197 /// update max skill value if current max skill not maximized
5198 else if(max != maxconfskill)
5199 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5204 void Player::UpdateSkillsToMaxSkillsForLevel()
5206 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5207 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5209 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5210 if( IsProfessionOrRidingSkill(pskill))
5211 continue;
5212 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5214 uint32 max = SKILL_MAX(data);
5216 if(max > 1)
5217 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5219 if(pskill == SKILL_DEFENSE)
5220 UpdateDefenseBonusesMod();
5224 // This functions sets a skill line value (and adds if doesn't exist yet)
5225 // To "remove" a skill line, set it's values to zero
5226 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5228 if(!id)
5229 return;
5231 uint16 i=0;
5232 for (; i < PLAYER_MAX_SKILLS; ++i)
5233 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5235 if(i<PLAYER_MAX_SKILLS) //has skill
5237 if(currVal)
5239 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5240 learnSkillRewardedSpells(id, currVal);
5241 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5242 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5244 else //remove
5246 // clear skill fields
5247 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5248 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5249 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5251 // remove all spells that related to this skill
5252 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5253 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5254 if (pAbility->skillId==id)
5255 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5258 else if(currVal) //add
5260 for (i=0; i < PLAYER_MAX_SKILLS; ++i)
5261 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5263 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5264 if(!pSkill)
5266 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5267 return;
5269 // enable unlearn button for primary professions only
5270 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5271 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5272 else
5273 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5274 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5275 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5276 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5278 // apply skill bonuses
5279 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5281 // temporary bonuses
5282 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5283 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5284 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5285 (*j)->ApplyModifier(true);
5287 // permanent bonuses
5288 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5289 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5290 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5291 (*j)->ApplyModifier(true);
5293 // Learn all spells for skill
5294 learnSkillRewardedSpells(id, currVal);
5295 return;
5300 bool Player::HasSkill(uint32 skill) const
5302 if(!skill)return false;
5303 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5305 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5307 return true;
5310 return false;
5313 uint16 Player::GetSkillValue(uint32 skill) const
5315 if(!skill)
5316 return 0;
5318 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5320 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5322 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5324 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5325 result += SKILL_TEMP_BONUS(bonus);
5326 result += SKILL_PERM_BONUS(bonus);
5327 return result < 0 ? 0 : result;
5330 return 0;
5333 uint16 Player::GetMaxSkillValue(uint32 skill) const
5335 if(!skill)return 0;
5336 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5338 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5340 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5342 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5343 result += SKILL_TEMP_BONUS(bonus);
5344 result += SKILL_PERM_BONUS(bonus);
5345 return result < 0 ? 0 : result;
5348 return 0;
5351 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5353 if(!skill)return 0;
5354 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5356 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5358 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5361 return 0;
5364 uint16 Player::GetBaseSkillValue(uint32 skill) const
5366 if(!skill)return 0;
5367 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5369 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5371 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5372 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5373 return result < 0 ? 0 : result;
5376 return 0;
5379 uint16 Player::GetPureSkillValue(uint32 skill) const
5381 if(!skill)return 0;
5382 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5384 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5386 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5389 return 0;
5392 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5394 if(!skill)
5395 return 0;
5397 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5399 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5401 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5405 return 0;
5408 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5410 if(!skill)
5411 return 0;
5413 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5415 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5417 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5421 return 0;
5424 void Player::SendInitialActionButtons() const
5426 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5428 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5429 data << uint8(0); // can be 0, 1, 2
5430 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5432 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5433 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5435 data << uint16(itr->second.action);
5436 data << uint8(itr->second.misc);
5437 data << uint8(itr->second.type);
5439 else
5441 data << uint32(0);
5445 GetSession()->SendPacket( &data );
5446 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5449 bool Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5451 if(button >= MAX_ACTION_BUTTONS)
5453 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5454 return false;
5457 // check cheating with adding non-known spells to action bar
5458 if(type==ACTION_BUTTON_SPELL)
5460 if(!sSpellStore.LookupEntry(action))
5462 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5463 return false;
5466 if(!HasSpell(action))
5468 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5469 return false;
5473 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5475 if (buttonItr==m_actionButtons.end())
5476 { // just add new button
5477 m_actionButtons[button] = ActionButton(action,type,misc);
5479 else
5480 { // change state of current button
5481 ActionButtonUpdateState uState = buttonItr->second.uState;
5482 buttonItr->second = ActionButton(action,type,misc);
5483 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5486 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5487 return true;
5490 void Player::removeActionButton(uint8 button)
5492 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5493 if (buttonItr==m_actionButtons.end())
5494 return;
5496 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5497 m_actionButtons.erase(buttonItr); // new and not saved
5498 else
5499 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5501 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5504 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5506 // prevent crash when a bad coord is sent by the client
5507 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5509 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5510 return false;
5513 Map *m = GetMap();
5515 const float old_x = GetPositionX();
5516 const float old_y = GetPositionY();
5517 const float old_z = GetPositionZ();
5518 const float old_r = GetOrientation();
5520 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5522 if (teleport || old_x != x || old_y != y || old_z != z)
5523 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5524 else
5525 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5527 // move and update visible state if need
5528 m->PlayerRelocation(this, x, y, z, orientation);
5530 // reread after Map::Relocation
5531 m = GetMap();
5532 x = GetPositionX();
5533 y = GetPositionY();
5534 z = GetPositionZ();
5536 // group update
5537 if(GetGroup() && (old_x != x || old_y != y))
5538 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5541 // code block for underwater state update
5542 UpdateUnderwaterState(m, x, y, z);
5544 CheckExploreSystem();
5546 return true;
5549 void Player::SaveRecallPosition()
5551 m_recallMap = GetMapId();
5552 m_recallX = GetPositionX();
5553 m_recallY = GetPositionY();
5554 m_recallZ = GetPositionZ();
5555 m_recallO = GetOrientation();
5558 void Player::SendMessageToSet(WorldPacket *data, bool self)
5560 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5561 if(_map)
5563 _map->MessageBroadcast(this, data, self);
5564 return;
5567 //if player is not in world and map in not created/already destroyed
5568 //no need to create one, just send packet for itself!
5569 if(self)
5570 GetSession()->SendPacket(data);
5573 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5575 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5576 if(_map)
5578 _map->MessageDistBroadcast(this, data, dist, self);
5579 return;
5582 if(self)
5583 GetSession()->SendPacket(data);
5586 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5588 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5589 if(_map)
5591 _map->MessageDistBroadcast(this, data, dist, self, own_team_only);
5592 return;
5595 if(self)
5596 GetSession()->SendPacket(data);
5599 void Player::SendDirectMessage(WorldPacket *data)
5601 GetSession()->SendPacket(data);
5604 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5606 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5607 data << uint32(CinematicSequenceId);
5608 SendDirectMessage(&data);
5611 void Player::SendMovieStart(uint32 MovieId)
5613 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5614 data << uint32(MovieId);
5615 SendDirectMessage(&data);
5618 void Player::CheckExploreSystem()
5620 if (!isAlive())
5621 return;
5623 if (isInFlight())
5624 return;
5626 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5627 if(areaFlag==0xffff)
5628 return;
5629 int offset = areaFlag / 32;
5631 if(offset >= 128)
5633 sLog.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset);
5634 return;
5637 uint32 val = (uint32)(1 << (areaFlag % 32));
5638 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5640 if( !(currFields & val) )
5642 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5644 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5646 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5647 if(!p)
5649 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5651 else if(p->area_level > 0)
5653 uint32 area = p->ID;
5654 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5656 SendExplorationExperience(area,0);
5658 else
5660 int32 diff = int32(getLevel()) - p->area_level;
5661 uint32 XP = 0;
5662 if (diff < -5)
5664 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5666 else if (diff > 5)
5668 int32 exploration_percent = (100-((diff-5)*5));
5669 if (exploration_percent > 100)
5670 exploration_percent = 100;
5671 else if (exploration_percent < 0)
5672 exploration_percent = 0;
5674 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5676 else
5678 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5681 GiveXP( XP, NULL );
5682 SendExplorationExperience(area,XP);
5684 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5689 uint32 Player::TeamForRace(uint8 race)
5691 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5692 if(!rEntry)
5694 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5695 return ALLIANCE;
5698 switch(rEntry->TeamID)
5700 case 7: return ALLIANCE;
5701 case 1: return HORDE;
5704 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5705 return ALLIANCE;
5708 uint32 Player::getFactionForRace(uint8 race)
5710 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5711 if(!rEntry)
5713 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5714 return 0;
5717 return rEntry->FactionID;
5720 void Player::setFactionForRace(uint8 race)
5722 m_team = TeamForRace(race);
5723 setFaction( getFactionForRace(race) );
5726 ReputationRank Player::GetReputationRank(uint32 faction) const
5728 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5729 return GetReputationMgr().GetRank(factionEntry);
5732 //Calculate total reputation percent player gain with quest/creature level
5733 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5735 float percent = 100.0f;
5737 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5739 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5740 percent *= rate;
5742 float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5744 if (!for_quest)
5745 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
5747 percent += rep > 0 ? repMod : -repMod;
5749 if (percent <= 0.0f)
5750 return 0;
5752 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100.0f);
5755 //Calculates how many reputation points player gains in victim's enemy factions
5756 void Player::RewardReputation(Unit *pVictim, float rate)
5758 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5759 return;
5761 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5763 if(!Rep)
5764 return;
5766 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5768 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
5769 donerep1 = int32(donerep1*rate);
5770 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5771 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5772 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5773 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5775 // Wiki: Team factions value divided by 2
5776 if (factionEntry1 && Rep->is_teamaward1)
5778 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5779 if(team1_factionEntry)
5780 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5784 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5786 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
5787 donerep2 = int32(donerep2*rate);
5788 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5789 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5790 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5791 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5793 // Wiki: Team factions value divided by 2
5794 if (factionEntry2 && Rep->is_teamaward2)
5796 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5797 if(team2_factionEntry)
5798 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5803 //Calculate how many reputation points player gain with the quest
5804 void Player::RewardReputation(Quest const *pQuest)
5806 // quest reputation reward/loss
5807 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5809 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5811 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
5812 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5813 if(factionEntry)
5814 GetReputationMgr().ModifyReputation(factionEntry, rep);
5818 // TODO: implement reputation spillover
5821 void Player::UpdateArenaFields(void)
5823 /* arena calcs go here */
5826 void Player::UpdateHonorFields()
5828 /// called when rewarding honor and at each save
5829 uint64 now = time(NULL);
5830 uint64 today = uint64(time(NULL) / DAY) * DAY;
5832 if(m_lastHonorUpdateTime < today)
5834 uint64 yesterday = today - DAY;
5836 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5838 // update yesterday's contribution
5839 if(m_lastHonorUpdateTime >= yesterday )
5841 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5843 // this is the first update today, reset today's contribution
5844 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5845 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5847 else
5849 // no honor/kills yesterday or today, reset
5850 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5851 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5855 m_lastHonorUpdateTime = now;
5858 ///Calculate the amount of honor gained based on the victim
5859 ///and the size of the group for which the honor is divided
5860 ///An exact honor value can also be given (overriding the calcs)
5861 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5863 // do not reward honor in arenas, but enable onkill spellproc
5864 if(InArena())
5866 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5867 return false;
5869 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5870 return false;
5872 return true;
5875 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5876 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5877 return false;
5879 uint64 victim_guid = 0;
5880 uint32 victim_rank = 0;
5882 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5883 UpdateHonorFields();
5885 if(honor <= 0)
5887 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5888 return false;
5890 victim_guid = uVictim->GetGUID();
5892 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5894 Player *pVictim = (Player *)uVictim;
5896 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5897 return false;
5899 float f = 1; //need for total kills (?? need more info)
5900 uint32 k_grey = 0;
5901 uint32 k_level = getLevel();
5902 uint32 v_level = pVictim->getLevel();
5905 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5906 // [0] Just name
5907 // [1..14] Alliance honor titles and player name
5908 // [15..28] Horde honor titles and player name
5909 // [29..38] Other title and player name
5910 // [39+] Nothing
5911 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5912 // Get Killer titles, CharTitlesEntry::bit_index
5913 // Ranks:
5914 // title[1..14] -> rank[5..18]
5915 // title[15..28] -> rank[5..18]
5916 // title[other] -> 0
5917 if (victim_title == 0)
5918 victim_guid = 0; // Don't show HK: <rank> message, only log.
5919 else if (victim_title < 15)
5920 victim_rank = victim_title + 4;
5921 else if (victim_title < 29)
5922 victim_rank = victim_title - 14 + 4;
5923 else
5924 victim_guid = 0; // Don't show HK: <rank> message, only log.
5927 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
5929 if(v_level<=k_grey)
5930 return false;
5932 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5934 int32 v_rank =1; //need more info
5936 honor = ((f * diff_level * (190 + v_rank*10))/6);
5937 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5939 // count the number of playerkills in one day
5940 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5941 // and those in a lifetime
5942 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5943 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
5944 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
5945 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
5947 else
5949 Creature *cVictim = (Creature *)uVictim;
5951 if (!cVictim->isRacialLeader())
5952 return false;
5954 honor = 100; // ??? need more info
5955 victim_rank = 19; // HK: Leader
5959 if (uVictim != NULL)
5961 honor *= sWorld.getRate(RATE_HONOR);
5963 if(groupsize > 1)
5964 honor /= groupsize;
5966 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5969 // honor - for show honor points in log
5970 // victim_guid - for show victim name in log
5971 // victim_rank [1..4] HK: <dishonored rank>
5972 // victim_rank [5..19] HK: <alliance\horde rank>
5973 // victim_rank [0,20+] HK: <>
5974 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5975 data << (uint32) honor;
5976 data << (uint64) victim_guid;
5977 data << (uint32) victim_rank;
5979 GetSession()->SendPacket(&data);
5981 // add honor points
5982 ModifyHonorPoints(int32(honor));
5984 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5985 return true;
5988 void Player::ModifyHonorPoints( int32 value )
5990 if(value < 0)
5992 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5993 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
5994 else
5995 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
5997 else
5998 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6001 void Player::ModifyArenaPoints( int32 value )
6003 if(value < 0)
6005 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6006 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6007 else
6008 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6010 else
6011 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6014 uint32 Player::GetGuildIdFromDB(uint64 guid)
6016 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6017 if(!result)
6018 return 0;
6020 uint32 id = result->Fetch()[0].GetUInt32();
6021 delete result;
6022 return id;
6025 uint32 Player::GetRankFromDB(uint64 guid)
6027 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6028 if( result )
6030 uint32 v = result->Fetch()[0].GetUInt32();
6031 delete result;
6032 return v;
6034 else
6035 return 0;
6038 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6040 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);
6041 if(!result)
6042 return 0;
6044 uint32 id = (*result)[0].GetUInt32();
6045 delete result;
6046 return id;
6049 uint32 Player::GetZoneIdFromDB(uint64 guid)
6051 uint32 guidLow = GUID_LOPART(guid);
6052 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6053 if (!result)
6054 return 0;
6055 Field* fields = result->Fetch();
6056 uint32 zone = fields[0].GetUInt32();
6057 delete result;
6059 if (!zone)
6061 // stored zone is zero, use generic and slow zone detection
6062 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6063 if( !result )
6064 return 0;
6065 fields = result->Fetch();
6066 uint32 map = fields[0].GetUInt32();
6067 float posx = fields[1].GetFloat();
6068 float posy = fields[2].GetFloat();
6069 float posz = fields[3].GetFloat();
6070 delete result;
6072 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6074 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6077 return zone;
6080 void Player::UpdateArea(uint32 newArea)
6082 // FFA_PVP flags are area and not zone id dependent
6083 // so apply them accordingly
6084 m_areaUpdateId = newArea;
6086 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6088 if(area && (area->flags & AREA_FLAG_ARENA))
6090 if(!isGameMaster())
6091 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6093 else
6095 // remove ffa flag only if not ffapvp realm
6096 // removal in sanctuaries and capitals is handled in zone update
6097 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6098 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6101 UpdateAreaDependentAuras(newArea);
6104 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6106 if(m_zoneUpdateId != newZone)
6107 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6109 m_zoneUpdateId = newZone;
6110 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6112 // zone changed, so area changed as well, update it
6113 UpdateArea(newArea);
6115 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6116 if(!zone)
6117 return;
6119 if (sWorld.getConfig(CONFIG_WEATHER))
6121 Weather *wth = sWorld.FindWeather(zone->ID);
6122 if(wth)
6124 wth->SendWeatherUpdateToPlayer(this);
6126 else
6128 if(!sWorld.AddWeather(zone->ID))
6130 // send fine weather packet to remove old zone's weather
6131 Weather::SendFineWeatherUpdateToPlayer(this);
6136 // in PvP, any not controlled zone (except zone->team == 6, default case)
6137 // in PvE, only opposition team capital
6138 switch(zone->team)
6140 case AREATEAM_ALLY:
6141 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6142 break;
6143 case AREATEAM_HORDE:
6144 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6145 break;
6146 case AREATEAM_NONE:
6147 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6148 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6149 break;
6150 default: // 6 in fact
6151 pvpInfo.inHostileArea = false;
6152 break;
6155 if(pvpInfo.inHostileArea) // in hostile area
6157 if(!IsPvP() || pvpInfo.endTimer != 0)
6158 UpdatePvP(true, true);
6160 else // in friendly area
6162 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6163 pvpInfo.endTimer = time(0); // start toggle-off
6166 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6168 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6169 if(sWorld.IsFFAPvPRealm())
6170 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6172 else
6174 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6177 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6179 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6180 SetRestType(REST_TYPE_IN_CITY);
6181 InnEnter(time(0),GetMapId(),0,0,0);
6183 if(sWorld.IsFFAPvPRealm())
6184 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6186 else // anywhere else
6188 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6190 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6192 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6194 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6195 SetRestType(REST_TYPE_NO);
6197 if(sWorld.IsFFAPvPRealm())
6198 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6201 else // not in tavern (leave city then)
6203 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6204 SetRestType(REST_TYPE_NO);
6206 // Set player to FFA PVP when not in rested environment.
6207 if(sWorld.IsFFAPvPRealm())
6208 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6213 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6214 // if player resurrected at teleport this will be applied in resurrect code
6215 if(isAlive())
6216 DestroyZoneLimitedItem( true, newZone );
6218 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6219 AutoUnequipOffhandIfNeed();
6221 // recent client version not send leave/join channel packets for built-in local channels
6222 UpdateLocalChannels( newZone );
6224 // group update
6225 if(GetGroup())
6226 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6228 UpdateZoneDependentAuras(newZone);
6231 //If players are too far way of duel flag... then player loose the duel
6232 void Player::CheckDuelDistance(time_t currTime)
6234 if(!duel)
6235 return;
6237 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6238 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6239 if(!obj)
6240 return;
6242 if(duel->outOfBound == 0)
6244 if(!IsWithinDistInMap(obj, 50))
6246 duel->outOfBound = currTime;
6248 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6249 GetSession()->SendPacket(&data);
6252 else
6254 if(IsWithinDistInMap(obj, 40))
6256 duel->outOfBound = 0;
6258 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6259 GetSession()->SendPacket(&data);
6261 else if(currTime >= (duel->outOfBound+10))
6263 DuelComplete(DUEL_FLED);
6268 void Player::DuelComplete(DuelCompleteType type)
6270 // duel not requested
6271 if(!duel)
6272 return;
6274 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6275 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6276 GetSession()->SendPacket(&data);
6277 duel->opponent->GetSession()->SendPacket(&data);
6279 if(type != DUEL_INTERUPTED)
6281 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6282 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6283 data << duel->opponent->GetName();
6284 data << GetName();
6285 SendMessageToSet(&data,true);
6288 if (type == DUEL_WON)
6290 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6291 if (duel->opponent)
6292 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6295 // cool-down duel spell
6296 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6298 data<<GetGUID();
6299 data<<uint8(0x0);
6301 data<<(uint32)7266;
6302 data<<uint32(0x0);
6303 GetSession()->SendPacket(&data);
6304 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6305 data<<duel->opponent->GetGUID();
6306 data<<uint8(0x0);
6307 data<<(uint32)7266;
6308 data<<uint32(0x0);
6309 duel->opponent->GetSession()->SendPacket(&data);*/
6311 //Remove Duel Flag object
6312 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6313 if(obj)
6314 duel->initiator->RemoveGameObject(obj,true);
6316 /* remove auras */
6317 std::vector<uint32> auras2remove;
6318 AuraMap const& vAuras = duel->opponent->GetAuras();
6319 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6321 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6322 auras2remove.push_back(i->second->GetId());
6325 for(size_t i=0; i<auras2remove.size(); ++i)
6326 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6328 auras2remove.clear();
6329 AuraMap const& auras = GetAuras();
6330 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6332 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6333 auras2remove.push_back(i->second->GetId());
6335 for(size_t i=0; i<auras2remove.size(); ++i)
6336 RemoveAurasDueToSpell(auras2remove[i]);
6338 // cleanup combo points
6339 if(GetComboTarget()==duel->opponent->GetGUID())
6340 ClearComboPoints();
6341 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6342 ClearComboPoints();
6344 if(duel->opponent->GetComboTarget()==GetGUID())
6345 duel->opponent->ClearComboPoints();
6346 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6347 duel->opponent->ClearComboPoints();
6349 //cleanups
6350 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6351 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6352 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6353 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6355 delete duel->opponent->duel;
6356 duel->opponent->duel = NULL;
6357 delete duel;
6358 duel = NULL;
6361 //---------------------------------------------------------//
6363 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6365 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6366 return;
6368 // not apply/remove mods for broken item
6369 if(item->IsBroken())
6370 return;
6372 ItemPrototype const *proto = item->GetProto();
6374 if(!proto)
6375 return;
6377 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6379 uint32 attacktype = Player::GetAttackBySlot(slot);
6380 if(attacktype < MAX_ATTACK)
6381 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6383 _ApplyItemBonuses(proto,slot,apply);
6385 if( slot==EQUIPMENT_SLOT_RANGED )
6386 _ApplyAmmoBonuses();
6388 ApplyItemEquipSpell(item,apply);
6389 ApplyEnchantment(item, apply);
6391 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6392 CorrectMetaGemEnchants(slot, apply);
6394 sLog.outDebug("_ApplyItemMods complete.");
6397 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6399 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6400 return;
6402 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : 0;
6403 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(getLevel()) : 0;
6405 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6407 uint32 statType = 0;
6408 int32 val = 0;
6409 // If set ScalingStatDistribution need get stats and values from it
6410 if (ssd && ssv)
6412 if (ssd->StatMod[i] < 0)
6413 continue;
6414 statType = ssd->StatMod[i];
6415 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6417 else
6419 if (i >= proto->StatsCount)
6420 continue;
6421 statType = proto->ItemStat[i].ItemStatType;
6422 val = proto->ItemStat[i].ItemStatValue;
6425 if(val == 0)
6426 continue;
6428 switch (statType)
6430 case ITEM_MOD_MANA:
6431 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6432 break;
6433 case ITEM_MOD_HEALTH: // modify HP
6434 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6435 break;
6436 case ITEM_MOD_AGILITY: // modify agility
6437 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6438 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6439 break;
6440 case ITEM_MOD_STRENGTH: //modify strength
6441 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6442 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6443 break;
6444 case ITEM_MOD_INTELLECT: //modify intellect
6445 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6446 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6447 break;
6448 case ITEM_MOD_SPIRIT: //modify spirit
6449 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6450 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6451 break;
6452 case ITEM_MOD_STAMINA: //modify stamina
6453 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6454 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6455 break;
6456 case ITEM_MOD_DEFENSE_SKILL_RATING:
6457 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6458 break;
6459 case ITEM_MOD_DODGE_RATING:
6460 ApplyRatingMod(CR_DODGE, int32(val), apply);
6461 break;
6462 case ITEM_MOD_PARRY_RATING:
6463 ApplyRatingMod(CR_PARRY, int32(val), apply);
6464 break;
6465 case ITEM_MOD_BLOCK_RATING:
6466 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6467 break;
6468 case ITEM_MOD_HIT_MELEE_RATING:
6469 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6470 break;
6471 case ITEM_MOD_HIT_RANGED_RATING:
6472 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6473 break;
6474 case ITEM_MOD_HIT_SPELL_RATING:
6475 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6476 break;
6477 case ITEM_MOD_CRIT_MELEE_RATING:
6478 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6479 break;
6480 case ITEM_MOD_CRIT_RANGED_RATING:
6481 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6482 break;
6483 case ITEM_MOD_CRIT_SPELL_RATING:
6484 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6485 break;
6486 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6487 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6488 break;
6489 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6490 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6491 break;
6492 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6493 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6494 break;
6495 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6496 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6497 break;
6498 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6499 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6500 break;
6501 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6502 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6503 break;
6504 case ITEM_MOD_HASTE_MELEE_RATING:
6505 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6506 break;
6507 case ITEM_MOD_HASTE_RANGED_RATING:
6508 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6509 break;
6510 case ITEM_MOD_HASTE_SPELL_RATING:
6511 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6512 break;
6513 case ITEM_MOD_HIT_RATING:
6514 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6515 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6516 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6517 break;
6518 case ITEM_MOD_CRIT_RATING:
6519 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6520 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6521 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6522 break;
6523 case ITEM_MOD_HIT_TAKEN_RATING:
6524 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6525 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6526 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6527 break;
6528 case ITEM_MOD_CRIT_TAKEN_RATING:
6529 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6530 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6531 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6532 break;
6533 case ITEM_MOD_RESILIENCE_RATING:
6534 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6535 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6536 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6537 break;
6538 case ITEM_MOD_HASTE_RATING:
6539 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6540 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6541 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6542 break;
6543 case ITEM_MOD_EXPERTISE_RATING:
6544 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6545 break;
6546 case ITEM_MOD_ATTACK_POWER:
6547 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6548 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6549 break;
6550 case ITEM_MOD_RANGED_ATTACK_POWER:
6551 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6552 break;
6553 case ITEM_MOD_FERAL_ATTACK_POWER:
6554 ApplyFeralAPBonus(int32(val), apply);
6555 break;
6556 case ITEM_MOD_SPELL_HEALING_DONE:
6557 ApplySpellHealingBonus(int32(val), apply);
6558 break;
6559 case ITEM_MOD_SPELL_DAMAGE_DONE:
6560 ApplySpellDamageBonus(int32(val), apply);
6561 break;
6562 case ITEM_MOD_MANA_REGENERATION:
6563 ApplyManaRegenBonus(int32(val), apply);
6564 break;
6565 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6566 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6567 break;
6568 case ITEM_MOD_SPELL_POWER:
6569 ApplySpellHealingBonus(int32(val), apply);
6570 ApplySpellDamageBonus(int32(val), apply);
6571 break;
6575 // If set ScalingStatValue armor get it or use item armor
6576 uint32 armor = proto->Armor;
6577 if (ssv)
6579 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6580 armor = ssvarmor;
6582 // Add armor bonus from ArmorDamageModifier if > 0
6583 if (proto->ArmorDamageModifier > 0)
6584 armor+=proto->ArmorDamageModifier;
6585 if (armor)
6586 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6588 if (proto->Block)
6589 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6591 if (proto->HolyRes)
6592 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6594 if (proto->FireRes)
6595 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6597 if (proto->NatureRes)
6598 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6600 if (proto->FrostRes)
6601 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6603 if (proto->ShadowRes)
6604 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6606 if (proto->ArcaneRes)
6607 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6609 WeaponAttackType attType = BASE_ATTACK;
6610 float damage = 0.0f;
6612 if( slot == EQUIPMENT_SLOT_RANGED && (
6613 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6614 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6616 attType = RANGED_ATTACK;
6618 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6620 attType = OFF_ATTACK;
6623 float minDamage = proto->Damage[0].DamageMin;
6624 float maxDamage = proto->Damage[0].DamageMax;
6625 int32 extraDPS = 0;
6626 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6627 if (ssv)
6629 if (extraDPS = ssv->getDPSMod(proto->ScalingStatValue))
6631 float average = extraDPS * proto->Delay / 1000.0f;
6632 minDamage = 0.7f * average;
6633 maxDamage = 1.3f * average;
6636 if (minDamage > 0 )
6638 damage = apply ? minDamage : BASE_MINDAMAGE;
6639 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6640 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6643 if (maxDamage > 0 )
6645 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6646 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6649 // Apply feral bonus from ScalingStatValue if set
6650 if (ssv)
6652 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6653 ApplyFeralAPBonus(feral_bonus, apply);
6655 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6656 if(getClass() == CLASS_DRUID)
6658 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6659 if (feral_bonus > 0)
6660 ApplyFeralAPBonus(feral_bonus, apply);
6663 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6664 return;
6666 if (proto->Delay)
6668 if(slot == EQUIPMENT_SLOT_RANGED)
6669 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6670 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6671 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6672 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6673 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6676 if(CanModifyStats() && (damage || proto->Delay))
6677 UpdateDamagePhysical(attType);
6680 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6682 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6683 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6684 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6686 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6687 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6688 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6690 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6691 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6692 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6695 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6697 // generic not weapon specific case processes in aura code
6698 if(aura->GetSpellProto()->EquippedItemClass == -1)
6699 return;
6701 BaseModGroup mod = BASEMOD_END;
6702 switch(attackType)
6704 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6705 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6706 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6707 default: return;
6710 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6712 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6716 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6718 // ignore spell mods for not wands
6719 Modifier const* modifier = aura->GetModifier();
6720 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6721 return;
6723 // generic not weapon specific case processes in aura code
6724 if(aura->GetSpellProto()->EquippedItemClass == -1)
6725 return;
6727 UnitMods unitMod = UNIT_MOD_END;
6728 switch(attackType)
6730 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6731 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6732 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6733 default: return;
6736 UnitModifierType unitModType = TOTAL_VALUE;
6737 switch(modifier->m_auraname)
6739 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6740 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6741 default: return;
6744 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6746 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6750 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6752 if(!item)
6753 return;
6755 ItemPrototype const *proto = item->GetProto();
6756 if(!proto)
6757 return;
6759 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6761 _Spell const& spellData = proto->Spells[i];
6763 // no spell
6764 if(!spellData.SpellId )
6765 continue;
6767 // wrong triggering type
6768 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6769 continue;
6771 // check if it is valid spell
6772 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6773 if(!spellproto)
6774 continue;
6776 ApplyEquipSpell(spellproto,item,apply,form_change);
6780 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6782 if(apply)
6784 // Cannot be used in this stance/form
6785 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6786 return;
6788 if(form_change) // check aura active state from other form
6790 bool found = false;
6791 for (int k=0; k < 3; ++k)
6793 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6794 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6796 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6798 found = true;
6799 break;
6802 if(found)
6803 break;
6806 if(found) // and skip re-cast already active aura at form change
6807 return;
6810 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6812 CastSpell(this,spellInfo,true,item);
6814 else
6816 if(form_change) // check aura compatibility
6818 // Cannot be used in this stance/form
6819 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6820 return; // and remove only not compatible at form change
6823 if(item)
6824 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6825 else
6826 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6830 void Player::UpdateEquipSpellsAtFormChange()
6832 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6834 if(m_items[i] && !m_items[i]->IsBroken())
6836 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6837 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6841 // item set bonuses not dependent from item broken state
6842 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6844 ItemSetEffect* eff = ItemSetEff[setindex];
6845 if(!eff)
6846 continue;
6848 for(uint32 y=0;y<8; ++y)
6850 SpellEntry const* spellInfo = eff->spells[y];
6851 if(!spellInfo)
6852 continue;
6854 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6855 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6860 void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
6862 Item *item = GetWeaponForAttack(attType, true);
6863 if(!item || item->IsBroken())
6864 return;
6866 ItemPrototype const *proto = item->GetProto();
6867 if(!proto)
6868 return;
6870 if (!Target || Target == this )
6871 return;
6873 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6875 _Spell const& spellData = proto->Spells[i];
6877 // no spell
6878 if(!spellData.SpellId )
6879 continue;
6881 // wrong triggering type
6882 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6883 continue;
6885 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6886 if(!spellInfo)
6888 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6889 continue;
6892 // not allow proc extra attack spell at extra attack
6893 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6894 return;
6896 float chance = spellInfo->procChance;
6898 if(spellData.SpellPPMRate)
6900 uint32 WeaponSpeed = GetAttackTime(attType);
6901 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6903 else if(chance > 100.0f)
6905 chance = GetWeaponProcChance();
6908 if (roll_chance_f(chance))
6909 CastSpell(Target, spellInfo->Id, true, item);
6912 // item combat enchantments
6913 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6915 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6916 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6917 if(!pEnchant) continue;
6918 for (int s=0;s<3;s++)
6920 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6921 continue;
6923 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6924 if (!spellInfo)
6926 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6927 continue;
6930 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6931 if (roll_chance_f(chance))
6933 if(IsPositiveSpell(pEnchant->spellid[s]))
6934 CastSpell(this, pEnchant->spellid[s], true, item);
6935 else
6936 CastSpell(Target, pEnchant->spellid[s], true, item);
6942 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
6944 ItemPrototype const* proto = item->GetProto();
6945 // special learning case
6946 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
6948 uint32 learn_spell_id = proto->Spells[0].SpellId;
6949 uint32 learning_spell_id = proto->Spells[1].SpellId;
6951 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
6952 if(!spellInfo)
6954 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
6955 SendEquipError(EQUIP_ERR_NONE,item,NULL);
6956 return;
6959 Spell *spell = new Spell(this, spellInfo, false);
6960 spell->m_CastItem = item;
6961 spell->m_cast_count = cast_count; //set count of casts
6962 spell->m_currentBasePoints[0] = learning_spell_id;
6963 spell->prepare(&targets);
6964 return;
6967 // use triggered flag only for items with many spell casts and for not first cast
6968 int count = 0;
6970 // item spells casted at use
6971 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6973 _Spell const& spellData = proto->Spells[i];
6975 // no spell
6976 if(!spellData.SpellId)
6977 continue;
6979 // wrong triggering type
6980 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
6981 continue;
6983 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6984 if(!spellInfo)
6986 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
6987 continue;
6990 Spell *spell = new Spell(this, spellInfo, (count > 0));
6991 spell->m_CastItem = item;
6992 spell->m_cast_count = cast_count; // set count of casts
6993 spell->m_glyphIndex = glyphIndex; // glyph index
6994 spell->prepare(&targets);
6996 ++count;
6999 // Item enchantments spells casted at use
7000 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7002 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7003 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7004 if(!pEnchant) continue;
7005 for (int s=0;s<3;s++)
7007 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7008 continue;
7010 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7011 if (!spellInfo)
7013 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7014 continue;
7017 Spell *spell = new Spell(this, spellInfo, (count > 0));
7018 spell->m_CastItem = item;
7019 spell->m_cast_count = cast_count; // set count of casts
7020 spell->m_glyphIndex = glyphIndex; // glyph index
7021 spell->prepare(&targets);
7023 ++count;
7028 void Player::_RemoveAllItemMods()
7030 sLog.outDebug("_RemoveAllItemMods start.");
7032 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7034 if(m_items[i])
7036 ItemPrototype const *proto = m_items[i]->GetProto();
7037 if(!proto)
7038 continue;
7040 // item set bonuses not dependent from item broken state
7041 if(proto->ItemSet)
7042 RemoveItemsSetItem(this,proto);
7044 if(m_items[i]->IsBroken())
7045 continue;
7047 ApplyItemEquipSpell(m_items[i],false);
7048 ApplyEnchantment(m_items[i], false);
7052 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7054 if(m_items[i])
7056 if(m_items[i]->IsBroken())
7057 continue;
7058 ItemPrototype const *proto = m_items[i]->GetProto();
7059 if(!proto)
7060 continue;
7062 uint32 attacktype = Player::GetAttackBySlot(i);
7063 if(attacktype < MAX_ATTACK)
7064 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7066 _ApplyItemBonuses(proto,i, false);
7068 if( i == EQUIPMENT_SLOT_RANGED )
7069 _ApplyAmmoBonuses();
7073 sLog.outDebug("_RemoveAllItemMods complete.");
7076 void Player::_ApplyAllItemMods()
7078 sLog.outDebug("_ApplyAllItemMods start.");
7080 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7082 if(m_items[i])
7084 if(m_items[i]->IsBroken())
7085 continue;
7087 ItemPrototype const *proto = m_items[i]->GetProto();
7088 if(!proto)
7089 continue;
7091 uint32 attacktype = Player::GetAttackBySlot(i);
7092 if(attacktype < MAX_ATTACK)
7093 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7095 _ApplyItemBonuses(proto,i, true);
7097 if( i == EQUIPMENT_SLOT_RANGED )
7098 _ApplyAmmoBonuses();
7102 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7104 if(m_items[i])
7106 ItemPrototype const *proto = m_items[i]->GetProto();
7107 if(!proto)
7108 continue;
7110 // item set bonuses not dependent from item broken state
7111 if(proto->ItemSet)
7112 AddItemsSetItem(this,m_items[i]);
7114 if(m_items[i]->IsBroken())
7115 continue;
7117 ApplyItemEquipSpell(m_items[i],true);
7118 ApplyEnchantment(m_items[i], true);
7122 sLog.outDebug("_ApplyAllItemMods complete.");
7125 void Player::_ApplyAmmoBonuses()
7127 // check ammo
7128 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7129 if(!ammo_id)
7130 return;
7132 float currentAmmoDPS;
7134 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7135 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7136 currentAmmoDPS = 0.0f;
7137 else
7138 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7140 if(currentAmmoDPS == GetAmmoDPS())
7141 return;
7143 m_ammoDPS = currentAmmoDPS;
7145 if(CanModifyStats())
7146 UpdateDamagePhysical(RANGED_ATTACK);
7149 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7151 if(!ammo_proto)
7152 return false;
7154 // check ranged weapon
7155 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7156 if(!weapon || weapon->IsBroken() )
7157 return false;
7159 ItemPrototype const* weapon_proto = weapon->GetProto();
7160 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7161 return false;
7163 // check ammo ws. weapon compatibility
7164 switch(weapon_proto->SubClass)
7166 case ITEM_SUBCLASS_WEAPON_BOW:
7167 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7168 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7169 return false;
7170 break;
7171 case ITEM_SUBCLASS_WEAPON_GUN:
7172 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7173 return false;
7174 break;
7175 default:
7176 return false;
7179 return true;
7182 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7183 Called by remove insignia spell effect */
7184 void Player::RemovedInsignia(Player* looterPlr)
7186 if (!GetBattleGroundId())
7187 return;
7189 // If not released spirit, do it !
7190 if(m_deathTimer > 0)
7192 m_deathTimer = 0;
7193 BuildPlayerRepop();
7194 RepopAtGraveyard();
7197 Corpse *corpse = GetCorpse();
7198 if (!corpse)
7199 return;
7201 // We have to convert player corpse to bones, not to be able to resurrect there
7202 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7203 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7204 if (!bones)
7205 return;
7207 // Now we must make bones lootable, and send player loot
7208 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7210 // We store the level of our player in the gold field
7211 // We retrieve this information at Player::SendLoot()
7212 bones->loot.gold = getLevel();
7213 bones->lootRecipient = looterPlr;
7214 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7217 void Player::SendLootRelease( uint64 guid )
7219 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7220 data << uint64(guid) << uint8(1);
7221 SendDirectMessage( &data );
7224 void Player::SendLoot(uint64 guid, LootType loot_type)
7226 if (uint64 lguid = GetLootGUID())
7227 m_session->DoLootRelease(lguid);
7229 Loot *loot = 0;
7230 PermissionTypes permission = ALL_PERMISSION;
7232 sLog.outDebug("Player::SendLoot");
7233 if (IS_GAMEOBJECT_GUID(guid))
7235 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7236 GameObject *go = GetMap()->GetGameObject(guid);
7238 // not check distance for GO in case owned GO (fishing bobber case, for example)
7239 // And permit out of range GO with no owner in case fishing hole
7240 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7242 SendLootRelease(guid);
7243 return;
7246 loot = &go->loot;
7248 if (go->getLootState() == GO_READY)
7250 uint32 lootid = go->GetLootId();
7252 if (lootid)
7254 sLog.outDebug(" if(lootid)");
7255 loot->clear();
7256 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7259 if (loot_type == LOOT_FISHING)
7260 go->getFishLoot(loot,this);
7262 go->SetLootState(GO_ACTIVATED);
7265 else if (IS_ITEM_GUID(guid))
7267 Item *item = GetItemByGuid( guid );
7269 if (!item)
7271 SendLootRelease(guid);
7272 return;
7275 loot = &item->loot;
7277 if (!item->m_lootGenerated)
7279 item->m_lootGenerated = true;
7280 loot->clear();
7282 switch(loot_type)
7284 case LOOT_DISENCHANTING:
7285 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7286 break;
7287 case LOOT_PROSPECTING:
7288 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7289 break;
7290 case LOOT_MILLING:
7291 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7292 break;
7293 default:
7294 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7295 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7296 break;
7300 else if (IS_CORPSE_GUID(guid)) // remove insignia
7302 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7304 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7306 SendLootRelease(guid);
7307 return;
7310 loot = &bones->loot;
7312 if (!bones->lootForBody)
7314 bones->lootForBody = true;
7315 uint32 pLevel = bones->loot.gold;
7316 bones->loot.clear();
7317 // It may need a better formula
7318 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7319 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7322 if (bones->lootRecipient != this)
7323 permission = NONE_PERMISSION;
7325 else
7327 Creature *creature = GetMap()->GetCreature(guid);
7329 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7330 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7332 SendLootRelease(guid);
7333 return;
7336 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7338 SendLootRelease(guid);
7339 return;
7342 loot = &creature->loot;
7344 if (loot_type == LOOT_PICKPOCKETING)
7346 if (!creature->lootForPickPocketed)
7348 creature->lootForPickPocketed = true;
7349 loot->clear();
7351 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7352 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7354 // Generate extra money for pick pocket loot
7355 const uint32 a = urand(0, creature->getLevel()/2);
7356 const uint32 b = urand(0, getLevel()/2);
7357 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7360 else
7362 // the player whose group may loot the corpse
7363 Player *recipient = creature->GetLootRecipient();
7364 if (!recipient)
7366 creature->SetLootRecipient(this);
7367 recipient = this;
7370 if (creature->lootForPickPocketed)
7372 creature->lootForPickPocketed = false;
7373 loot->clear();
7376 if (!creature->lootForBody)
7378 creature->lootForBody = true;
7379 loot->clear();
7381 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7382 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7384 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7386 if (Group* group = recipient->GetGroup())
7388 group->UpdateLooterGuid(creature,true);
7390 switch (group->GetLootMethod())
7392 case GROUP_LOOT:
7393 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7394 group->GroupLoot(recipient->GetGUID(), loot, creature);
7395 break;
7396 case NEED_BEFORE_GREED:
7397 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7398 break;
7399 case MASTER_LOOT:
7400 group->MasterLoot(recipient->GetGUID(), loot, creature);
7401 break;
7402 default:
7403 break;
7408 // possible only if creature->lootForBody && loot->empty() at spell cast check
7409 if (loot_type == LOOT_SKINNING)
7411 loot->clear();
7412 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7414 // set group rights only for loot_type != LOOT_SKINNING
7415 else
7417 if(Group* group = GetGroup())
7419 if (group == recipient->GetGroup())
7421 if (group->GetLootMethod() == FREE_FOR_ALL)
7422 permission = ALL_PERMISSION;
7423 else if (group->GetLooterGuid() == GetGUID())
7425 if (group->GetLootMethod() == MASTER_LOOT)
7426 permission = MASTER_PERMISSION;
7427 else
7428 permission = ALL_PERMISSION;
7430 else
7431 permission = GROUP_PERMISSION;
7433 else
7434 permission = NONE_PERMISSION;
7436 else if (recipient == this)
7437 permission = ALL_PERMISSION;
7438 else
7439 permission = NONE_PERMISSION;
7444 SetLootGUID(guid);
7446 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7447 switch(loot_type)
7449 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7450 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7451 default: break;
7454 // need know merged fishing/corpse loot type for achievements
7455 loot->loot_type = loot_type;
7457 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7459 data << uint64(guid);
7460 data << uint8(loot_type);
7461 data << LootView(*loot, this, permission);
7463 SendDirectMessage(&data);
7465 // add 'this' player as one of the players that are looting 'loot'
7466 if (permission != NONE_PERMISSION)
7467 loot->AddLooter(GetGUID());
7469 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7470 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7473 void Player::SendNotifyLootMoneyRemoved()
7475 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7476 GetSession()->SendPacket( &data );
7479 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7481 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7482 data << uint8(lootSlot);
7483 GetSession()->SendPacket( &data );
7486 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7488 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7489 data << Field;
7490 data << Value;
7491 GetSession()->SendPacket(&data);
7494 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7496 // data depends on zoneid/mapid...
7497 BattleGround* bg = GetBattleGround();
7498 uint16 NumberOfFields = 0;
7499 uint32 mapid = GetMapId();
7501 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7503 // may be exist better way to do this...
7504 switch(zoneid)
7506 case 0:
7507 case 1:
7508 case 4:
7509 case 8:
7510 case 10:
7511 case 11:
7512 case 12:
7513 case 36:
7514 case 38:
7515 case 40:
7516 case 41:
7517 case 51:
7518 case 267:
7519 case 1519:
7520 case 1537:
7521 case 2257:
7522 case 2918:
7523 NumberOfFields = 8;
7524 break;
7525 case 139:
7526 NumberOfFields = 41;
7527 break;
7528 case 1377:
7529 NumberOfFields = 15;
7530 break;
7531 case 2597:
7532 NumberOfFields = 83;
7533 break;
7534 case 3277:
7535 NumberOfFields = 16;
7536 break;
7537 case 3358:
7538 case 3820:
7539 NumberOfFields = 40;
7540 break;
7541 case 3483:
7542 NumberOfFields = 27;
7543 break;
7544 case 3518:
7545 NumberOfFields = 39;
7546 break;
7547 case 3519:
7548 NumberOfFields = 38;
7549 break;
7550 case 3521:
7551 NumberOfFields = 37;
7552 break;
7553 case 3698:
7554 case 3702:
7555 case 3968:
7556 NumberOfFields = 11;
7557 break;
7558 case 3703:
7559 NumberOfFields = 11;
7560 break;
7561 default:
7562 NumberOfFields = 12;
7563 break;
7566 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7567 data << uint32(mapid); // mapid
7568 data << uint32(zoneid); // zone id
7569 data << uint32(areaid); // area id, new 2.1.0
7570 data << uint16(NumberOfFields); // count of uint64 blocks
7571 data << uint32(0x8d8) << uint32(0x0); // 1
7572 data << uint32(0x8d7) << uint32(0x0); // 2
7573 data << uint32(0x8d6) << uint32(0x0); // 3
7574 data << uint32(0x8d5) << uint32(0x0); // 4
7575 data << uint32(0x8d4) << uint32(0x0); // 5
7576 data << uint32(0x8d3) << uint32(0x0); // 6
7577 // 7 1 - Arena season in progress, 0 - end of season
7578 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7579 // 8 Arena season id
7580 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7581 if(mapid == 530) // Outland
7583 data << uint32(0x9bf) << uint32(0x0); // 7
7584 data << uint32(0x9bd) << uint32(0xF); // 8
7585 data << uint32(0x9bb) << uint32(0xF); // 9
7587 switch(zoneid)
7589 case 1:
7590 case 11:
7591 case 12:
7592 case 38:
7593 case 40:
7594 case 51:
7595 case 1519:
7596 case 1537:
7597 case 2257:
7598 break;
7599 case 2597: // AV
7600 data << uint32(0x7ae) << uint32(0x1); // 7
7601 data << uint32(0x532) << uint32(0x1); // 8
7602 data << uint32(0x531) << uint32(0x0); // 9
7603 data << uint32(0x52e) << uint32(0x0); // 10
7604 data << uint32(0x571) << uint32(0x0); // 11
7605 data << uint32(0x570) << uint32(0x0); // 12
7606 data << uint32(0x567) << uint32(0x1); // 13
7607 data << uint32(0x566) << uint32(0x1); // 14
7608 data << uint32(0x550) << uint32(0x1); // 15
7609 data << uint32(0x544) << uint32(0x0); // 16
7610 data << uint32(0x536) << uint32(0x0); // 17
7611 data << uint32(0x535) << uint32(0x1); // 18
7612 data << uint32(0x518) << uint32(0x0); // 19
7613 data << uint32(0x517) << uint32(0x0); // 20
7614 data << uint32(0x574) << uint32(0x0); // 21
7615 data << uint32(0x573) << uint32(0x0); // 22
7616 data << uint32(0x572) << uint32(0x0); // 23
7617 data << uint32(0x56f) << uint32(0x0); // 24
7618 data << uint32(0x56e) << uint32(0x0); // 25
7619 data << uint32(0x56d) << uint32(0x0); // 26
7620 data << uint32(0x56c) << uint32(0x0); // 27
7621 data << uint32(0x56b) << uint32(0x0); // 28
7622 data << uint32(0x56a) << uint32(0x1); // 29
7623 data << uint32(0x569) << uint32(0x1); // 30
7624 data << uint32(0x568) << uint32(0x1); // 13
7625 data << uint32(0x565) << uint32(0x0); // 32
7626 data << uint32(0x564) << uint32(0x0); // 33
7627 data << uint32(0x563) << uint32(0x0); // 34
7628 data << uint32(0x562) << uint32(0x0); // 35
7629 data << uint32(0x561) << uint32(0x0); // 36
7630 data << uint32(0x560) << uint32(0x0); // 37
7631 data << uint32(0x55f) << uint32(0x0); // 38
7632 data << uint32(0x55e) << uint32(0x0); // 39
7633 data << uint32(0x55d) << uint32(0x0); // 40
7634 data << uint32(0x3c6) << uint32(0x4); // 41
7635 data << uint32(0x3c4) << uint32(0x6); // 42
7636 data << uint32(0x3c2) << uint32(0x4); // 43
7637 data << uint32(0x516) << uint32(0x1); // 44
7638 data << uint32(0x515) << uint32(0x0); // 45
7639 data << uint32(0x3b6) << uint32(0x6); // 46
7640 data << uint32(0x55c) << uint32(0x0); // 47
7641 data << uint32(0x55b) << uint32(0x0); // 48
7642 data << uint32(0x55a) << uint32(0x0); // 49
7643 data << uint32(0x559) << uint32(0x0); // 50
7644 data << uint32(0x558) << uint32(0x0); // 51
7645 data << uint32(0x557) << uint32(0x0); // 52
7646 data << uint32(0x556) << uint32(0x0); // 53
7647 data << uint32(0x555) << uint32(0x0); // 54
7648 data << uint32(0x554) << uint32(0x1); // 55
7649 data << uint32(0x553) << uint32(0x1); // 56
7650 data << uint32(0x552) << uint32(0x1); // 57
7651 data << uint32(0x551) << uint32(0x1); // 58
7652 data << uint32(0x54f) << uint32(0x0); // 59
7653 data << uint32(0x54e) << uint32(0x0); // 60
7654 data << uint32(0x54d) << uint32(0x1); // 61
7655 data << uint32(0x54c) << uint32(0x0); // 62
7656 data << uint32(0x54b) << uint32(0x0); // 63
7657 data << uint32(0x545) << uint32(0x0); // 64
7658 data << uint32(0x543) << uint32(0x1); // 65
7659 data << uint32(0x542) << uint32(0x0); // 66
7660 data << uint32(0x540) << uint32(0x0); // 67
7661 data << uint32(0x53f) << uint32(0x0); // 68
7662 data << uint32(0x53e) << uint32(0x0); // 69
7663 data << uint32(0x53d) << uint32(0x0); // 70
7664 data << uint32(0x53c) << uint32(0x0); // 71
7665 data << uint32(0x53b) << uint32(0x0); // 72
7666 data << uint32(0x53a) << uint32(0x1); // 73
7667 data << uint32(0x539) << uint32(0x0); // 74
7668 data << uint32(0x538) << uint32(0x0); // 75
7669 data << uint32(0x537) << uint32(0x0); // 76
7670 data << uint32(0x534) << uint32(0x0); // 77
7671 data << uint32(0x533) << uint32(0x0); // 78
7672 data << uint32(0x530) << uint32(0x0); // 79
7673 data << uint32(0x52f) << uint32(0x0); // 80
7674 data << uint32(0x52d) << uint32(0x1); // 81
7675 break;
7676 case 3277: // WS
7677 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7678 bg->FillInitialWorldStates(data);
7679 else
7681 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7682 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7683 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7684 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7685 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7686 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7687 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7688 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7690 break;
7691 case 3358: // AB
7692 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7693 bg->FillInitialWorldStates(data);
7694 else
7696 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7697 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7698 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7699 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7700 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7701 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7702 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7703 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7704 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7705 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7706 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7707 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7708 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7709 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7710 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7711 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7712 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7713 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7714 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7715 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7716 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7717 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7718 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7719 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7720 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7721 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7722 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7723 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7724 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7725 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7726 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7727 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7729 break;
7730 case 3820: // EY
7731 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7732 bg->FillInitialWorldStates(data);
7733 else
7735 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7736 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7737 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7738 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7739 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7740 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7741 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7742 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7743 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7744 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7745 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7746 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7747 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7748 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7749 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7750 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7751 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7752 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7753 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7754 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7755 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7756 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7757 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7758 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7759 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7760 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7761 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7762 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7763 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7764 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7765 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7766 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7767 // and some more ... unknown
7769 break;
7770 case 3483: // Hellfire Peninsula
7771 data << uint32(0x9ba) << uint32(0x1); // 10
7772 data << uint32(0x9b9) << uint32(0x1); // 11
7773 data << uint32(0x9b5) << uint32(0x0); // 12
7774 data << uint32(0x9b4) << uint32(0x1); // 13
7775 data << uint32(0x9b3) << uint32(0x0); // 14
7776 data << uint32(0x9b2) << uint32(0x0); // 15
7777 data << uint32(0x9b1) << uint32(0x1); // 16
7778 data << uint32(0x9b0) << uint32(0x0); // 17
7779 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7780 data << uint32(0x9ac) << uint32(0x0); // 19
7781 data << uint32(0x9a8) << uint32(0x0); // 20
7782 data << uint32(0x9a7) << uint32(0x0); // 21
7783 data << uint32(0x9a6) << uint32(0x1); // 22
7784 break;
7785 case 3519: // Terokkar Forest
7786 data << uint32(0xa41) << uint32(0x0); // 10
7787 data << uint32(0xa40) << uint32(0x14); // 11
7788 data << uint32(0xa3f) << uint32(0x0); // 12
7789 data << uint32(0xa3e) << uint32(0x0); // 13
7790 data << uint32(0xa3d) << uint32(0x5); // 14
7791 data << uint32(0xa3c) << uint32(0x0); // 15
7792 data << uint32(0xa87) << uint32(0x0); // 16
7793 data << uint32(0xa86) << uint32(0x0); // 17
7794 data << uint32(0xa85) << uint32(0x0); // 18
7795 data << uint32(0xa84) << uint32(0x0); // 19
7796 data << uint32(0xa83) << uint32(0x0); // 20
7797 data << uint32(0xa82) << uint32(0x0); // 21
7798 data << uint32(0xa81) << uint32(0x0); // 22
7799 data << uint32(0xa80) << uint32(0x0); // 23
7800 data << uint32(0xa7e) << uint32(0x0); // 24
7801 data << uint32(0xa7d) << uint32(0x0); // 25
7802 data << uint32(0xa7c) << uint32(0x0); // 26
7803 data << uint32(0xa7b) << uint32(0x0); // 27
7804 data << uint32(0xa7a) << uint32(0x0); // 28
7805 data << uint32(0xa79) << uint32(0x0); // 29
7806 data << uint32(0x9d0) << uint32(0x5); // 30
7807 data << uint32(0x9ce) << uint32(0x0); // 31
7808 data << uint32(0x9cd) << uint32(0x0); // 32
7809 data << uint32(0x9cc) << uint32(0x0); // 33
7810 data << uint32(0xa88) << uint32(0x0); // 34
7811 data << uint32(0xad0) << uint32(0x0); // 35
7812 data << uint32(0xacf) << uint32(0x1); // 36
7813 break;
7814 case 3521: // Zangarmarsh
7815 data << uint32(0x9e1) << uint32(0x0); // 10
7816 data << uint32(0x9e0) << uint32(0x0); // 11
7817 data << uint32(0x9df) << uint32(0x0); // 12
7818 data << uint32(0xa5d) << uint32(0x1); // 13
7819 data << uint32(0xa5c) << uint32(0x0); // 14
7820 data << uint32(0xa5b) << uint32(0x1); // 15
7821 data << uint32(0xa5a) << uint32(0x0); // 16
7822 data << uint32(0xa59) << uint32(0x1); // 17
7823 data << uint32(0xa58) << uint32(0x0); // 18
7824 data << uint32(0xa57) << uint32(0x0); // 19
7825 data << uint32(0xa56) << uint32(0x0); // 20
7826 data << uint32(0xa55) << uint32(0x1); // 21
7827 data << uint32(0xa54) << uint32(0x0); // 22
7828 data << uint32(0x9e7) << uint32(0x0); // 23
7829 data << uint32(0x9e6) << uint32(0x0); // 24
7830 data << uint32(0x9e5) << uint32(0x0); // 25
7831 data << uint32(0xa00) << uint32(0x0); // 26
7832 data << uint32(0x9ff) << uint32(0x1); // 27
7833 data << uint32(0x9fe) << uint32(0x0); // 28
7834 data << uint32(0x9fd) << uint32(0x0); // 29
7835 data << uint32(0x9fc) << uint32(0x1); // 30
7836 data << uint32(0x9fb) << uint32(0x0); // 31
7837 data << uint32(0xa62) << uint32(0x0); // 32
7838 data << uint32(0xa61) << uint32(0x1); // 33
7839 data << uint32(0xa60) << uint32(0x1); // 34
7840 data << uint32(0xa5f) << uint32(0x0); // 35
7841 break;
7842 case 3698: // Nagrand Arena
7843 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7844 bg->FillInitialWorldStates(data);
7845 else
7847 data << uint32(0xa0f) << uint32(0x0); // 7
7848 data << uint32(0xa10) << uint32(0x0); // 8
7849 data << uint32(0xa11) << uint32(0x0); // 9 show
7851 break;
7852 case 3702: // Blade's Edge Arena
7853 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7854 bg->FillInitialWorldStates(data);
7855 else
7857 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7858 data << uint32(0x9f1) << uint32(0x0); // 8 green
7859 data << uint32(0x9f3) << uint32(0x0); // 9 show
7861 break;
7862 case 3968: // Ruins of Lordaeron
7863 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7864 bg->FillInitialWorldStates(data);
7865 else
7867 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7868 data << uint32(0xbb9) << uint32(0x0); // 8 green
7869 data << uint32(0xbba) << uint32(0x0); // 9 show
7871 break;
7872 case 3703: // Shattrath City
7873 break;
7874 default:
7875 data << uint32(0x914) << uint32(0x0); // 7
7876 data << uint32(0x913) << uint32(0x0); // 8
7877 data << uint32(0x912) << uint32(0x0); // 9
7878 data << uint32(0x915) << uint32(0x0); // 10
7879 break;
7881 GetSession()->SendPacket(&data);
7884 uint32 Player::GetXPRestBonus(uint32 xp)
7886 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7888 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7889 rested_bonus = xp;
7891 SetRestBonus( GetRestBonus() - rested_bonus);
7893 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7894 return rested_bonus;
7897 void Player::SetBindPoint(uint64 guid)
7899 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7900 data << uint64(guid);
7901 GetSession()->SendPacket( &data );
7904 void Player::SendTalentWipeConfirm(uint64 guid)
7906 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7907 data << uint64(guid);
7908 data << uint32(resetTalentsCost());
7909 GetSession()->SendPacket( &data );
7912 void Player::SendPetSkillWipeConfirm()
7914 Pet* pet = GetPet();
7915 if(!pet)
7916 return;
7917 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7918 data << pet->GetGUID();
7919 data << uint32(pet->resetTalentsCost());
7920 GetSession()->SendPacket( &data );
7923 /*********************************************************/
7924 /*** STORAGE SYSTEM ***/
7925 /*********************************************************/
7927 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7929 assert(i < 3);
7930 if(i < 2 && item)
7932 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7933 return;
7934 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7935 if(charges == 0)
7936 return;
7937 if(charges > 1)
7938 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7939 else if(charges <= 1)
7941 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7942 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7947 void Player::SetSheath( SheathState sheathed )
7949 switch (sheathed)
7951 case SHEATH_STATE_UNARMED: // no prepared weapon
7952 SetVirtualItemSlot(0,NULL);
7953 SetVirtualItemSlot(1,NULL);
7954 SetVirtualItemSlot(2,NULL);
7955 break;
7956 case SHEATH_STATE_MELEE: // prepared melee weapon
7958 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7959 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7960 SetVirtualItemSlot(2,NULL);
7961 }; break;
7962 case SHEATH_STATE_RANGED: // prepared ranged weapon
7963 SetVirtualItemSlot(0,NULL);
7964 SetVirtualItemSlot(1,NULL);
7965 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7966 break;
7967 default:
7968 SetVirtualItemSlot(0,NULL);
7969 SetVirtualItemSlot(1,NULL);
7970 SetVirtualItemSlot(2,NULL);
7971 break;
7973 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
7976 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7978 uint8 pClass = getClass();
7980 uint8 slots[4];
7981 slots[0] = NULL_SLOT;
7982 slots[1] = NULL_SLOT;
7983 slots[2] = NULL_SLOT;
7984 slots[3] = NULL_SLOT;
7985 switch( proto->InventoryType )
7987 case INVTYPE_HEAD:
7988 slots[0] = EQUIPMENT_SLOT_HEAD;
7989 break;
7990 case INVTYPE_NECK:
7991 slots[0] = EQUIPMENT_SLOT_NECK;
7992 break;
7993 case INVTYPE_SHOULDERS:
7994 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7995 break;
7996 case INVTYPE_BODY:
7997 slots[0] = EQUIPMENT_SLOT_BODY;
7998 break;
7999 case INVTYPE_CHEST:
8000 slots[0] = EQUIPMENT_SLOT_CHEST;
8001 break;
8002 case INVTYPE_ROBE:
8003 slots[0] = EQUIPMENT_SLOT_CHEST;
8004 break;
8005 case INVTYPE_WAIST:
8006 slots[0] = EQUIPMENT_SLOT_WAIST;
8007 break;
8008 case INVTYPE_LEGS:
8009 slots[0] = EQUIPMENT_SLOT_LEGS;
8010 break;
8011 case INVTYPE_FEET:
8012 slots[0] = EQUIPMENT_SLOT_FEET;
8013 break;
8014 case INVTYPE_WRISTS:
8015 slots[0] = EQUIPMENT_SLOT_WRISTS;
8016 break;
8017 case INVTYPE_HANDS:
8018 slots[0] = EQUIPMENT_SLOT_HANDS;
8019 break;
8020 case INVTYPE_FINGER:
8021 slots[0] = EQUIPMENT_SLOT_FINGER1;
8022 slots[1] = EQUIPMENT_SLOT_FINGER2;
8023 break;
8024 case INVTYPE_TRINKET:
8025 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8026 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8027 break;
8028 case INVTYPE_CLOAK:
8029 slots[0] = EQUIPMENT_SLOT_BACK;
8030 break;
8031 case INVTYPE_WEAPON:
8033 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8035 // suggest offhand slot only if know dual wielding
8036 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8037 if(CanDualWield())
8038 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8039 break;
8041 case INVTYPE_SHIELD:
8042 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8043 break;
8044 case INVTYPE_RANGED:
8045 slots[0] = EQUIPMENT_SLOT_RANGED;
8046 break;
8047 case INVTYPE_2HWEAPON:
8048 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8049 if (CanDualWield() && CanTitanGrip())
8050 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8051 break;
8052 case INVTYPE_TABARD:
8053 slots[0] = EQUIPMENT_SLOT_TABARD;
8054 break;
8055 case INVTYPE_WEAPONMAINHAND:
8056 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8057 break;
8058 case INVTYPE_WEAPONOFFHAND:
8059 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8060 break;
8061 case INVTYPE_HOLDABLE:
8062 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8063 break;
8064 case INVTYPE_THROWN:
8065 slots[0] = EQUIPMENT_SLOT_RANGED;
8066 break;
8067 case INVTYPE_RANGEDRIGHT:
8068 slots[0] = EQUIPMENT_SLOT_RANGED;
8069 break;
8070 case INVTYPE_BAG:
8071 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8072 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8073 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8074 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8075 break;
8076 case INVTYPE_RELIC:
8078 switch(proto->SubClass)
8080 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8081 if (pClass == CLASS_PALADIN)
8082 slots[0] = EQUIPMENT_SLOT_RANGED;
8083 break;
8084 case ITEM_SUBCLASS_ARMOR_IDOL:
8085 if (pClass == CLASS_DRUID)
8086 slots[0] = EQUIPMENT_SLOT_RANGED;
8087 break;
8088 case ITEM_SUBCLASS_ARMOR_TOTEM:
8089 if (pClass == CLASS_SHAMAN)
8090 slots[0] = EQUIPMENT_SLOT_RANGED;
8091 break;
8092 case ITEM_SUBCLASS_ARMOR_MISC:
8093 if (pClass == CLASS_WARLOCK)
8094 slots[0] = EQUIPMENT_SLOT_RANGED;
8095 break;
8096 case ITEM_SUBCLASS_ARMOR_SIGIL:
8097 if (pClass == CLASS_DEATH_KNIGHT)
8098 slots[0] = EQUIPMENT_SLOT_RANGED;
8099 break;
8101 break;
8103 default :
8104 return NULL_SLOT;
8107 if( slot != NULL_SLOT )
8109 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8111 for (int i = 0; i < 4; ++i)
8113 if ( slots[i] == slot )
8114 return slot;
8118 else
8120 // search free slot at first
8121 for (int i = 0; i < 4; ++i)
8123 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8125 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8126 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8127 return slots[i];
8131 // if not found free and can swap return first appropriate from used
8132 for (int i = 0; i < 4; ++i)
8134 if ( slots[i] != NULL_SLOT && swap )
8135 return slots[i];
8139 // no free position
8140 return NULL_SLOT;
8143 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8145 Item *pItem;
8146 uint32 tempcount = 0;
8148 uint8 res = EQUIP_ERR_OK;
8150 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8152 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8153 if( pItem && pItem->GetEntry() == item )
8155 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8156 if(ires==EQUIP_ERR_OK)
8158 tempcount += pItem->GetCount();
8159 if( tempcount >= count )
8160 return EQUIP_ERR_OK;
8162 else
8163 res = ires;
8166 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8168 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8169 if( pItem && pItem->GetEntry() == item )
8171 tempcount += pItem->GetCount();
8172 if( tempcount >= count )
8173 return EQUIP_ERR_OK;
8176 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8178 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8179 if( pItem && pItem->GetEntry() == item )
8181 tempcount += pItem->GetCount();
8182 if( tempcount >= count )
8183 return EQUIP_ERR_OK;
8186 Bag *pBag;
8187 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8189 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8190 if( pBag )
8192 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8194 pItem = GetItemByPos( i, j );
8195 if( pItem && pItem->GetEntry() == item )
8197 tempcount += pItem->GetCount();
8198 if( tempcount >= count )
8199 return EQUIP_ERR_OK;
8205 // not found req. item count and have unequippable items
8206 return res;
8209 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8211 uint32 count = 0;
8212 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8214 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8215 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8216 count += pItem->GetCount();
8218 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8220 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8221 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8222 count += pItem->GetCount();
8224 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8226 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8227 if( pBag )
8228 count += pBag->GetItemCount(item,skipItem);
8231 if(skipItem && skipItem->GetProto()->GemProperties)
8233 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8235 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8236 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8237 count += pItem->GetGemCountWithID(item);
8241 if(inBankAlso)
8243 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8245 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8246 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8247 count += pItem->GetCount();
8249 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8251 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8252 if( pBag )
8253 count += pBag->GetItemCount(item,skipItem);
8256 if(skipItem && skipItem->GetProto()->GemProperties)
8258 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8260 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8261 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8262 count += pItem->GetGemCountWithID(item);
8267 return count;
8270 Item* Player::GetItemByGuid( uint64 guid ) const
8272 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8274 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8275 if( pItem && pItem->GetGUID() == guid )
8276 return pItem;
8278 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8280 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8281 if( pItem && pItem->GetGUID() == guid )
8282 return pItem;
8285 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8287 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8288 if( pBag )
8290 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8292 Item* pItem = pBag->GetItemByPos( j );
8293 if( pItem && pItem->GetGUID() == guid )
8294 return pItem;
8298 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8300 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8301 if( pBag )
8303 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8305 Item* pItem = pBag->GetItemByPos( j );
8306 if( pItem && pItem->GetGUID() == guid )
8307 return pItem;
8312 return NULL;
8315 Item* Player::GetItemByPos( uint16 pos ) const
8317 uint8 bag = pos >> 8;
8318 uint8 slot = pos & 255;
8319 return GetItemByPos( bag, slot );
8322 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8324 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8325 return m_items[slot];
8326 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8327 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8329 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8330 if ( pBag )
8331 return pBag->GetItemByPos(slot);
8333 return NULL;
8336 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8338 uint16 slot;
8339 switch (attackType)
8341 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8342 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8343 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8344 default: return NULL;
8347 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8348 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8349 return NULL;
8351 if(!useable)
8352 return item;
8354 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8355 return NULL;
8357 return item;
8360 Item* Player::GetShield(bool useable) const
8362 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8363 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8364 return NULL;
8366 if(!useable)
8367 return item;
8369 if( item->IsBroken())
8370 return NULL;
8372 return item;
8375 uint32 Player::GetAttackBySlot( uint8 slot )
8377 switch(slot)
8379 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8380 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8381 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8382 default: return MAX_ATTACK;
8386 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8388 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8389 return true;
8390 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8391 return true;
8392 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8393 return true;
8394 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8395 return true;
8396 return false;
8399 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8401 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8402 return true;
8403 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8404 return true;
8405 return false;
8408 bool Player::IsBankPos( uint8 bag, uint8 slot )
8410 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8411 return true;
8412 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8413 return true;
8414 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8415 return true;
8416 return false;
8419 bool Player::IsBagPos( uint16 pos )
8421 uint8 bag = pos >> 8;
8422 uint8 slot = pos & 255;
8423 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8424 return true;
8425 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8426 return true;
8427 return false;
8430 bool Player::IsValidPos( uint8 bag, uint8 slot )
8432 // post selected
8433 if(bag == NULL_BAG)
8434 return true;
8436 if (bag == INVENTORY_SLOT_BAG_0)
8438 // any post selected
8439 if (slot == NULL_SLOT)
8440 return true;
8442 // equipment
8443 if (slot < EQUIPMENT_SLOT_END)
8444 return true;
8446 // bag equip slots
8447 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8448 return true;
8450 // backpack slots
8451 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8452 return true;
8454 // keyring slots
8455 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8456 return true;
8458 // bank main slots
8459 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8460 return true;
8462 // bank bag slots
8463 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8464 return true;
8466 return false;
8469 // bag content slots
8470 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8472 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8473 if(!pBag)
8474 return false;
8476 // any post selected
8477 if (slot == NULL_SLOT)
8478 return true;
8480 return slot < pBag->GetBagSize();
8483 // bank bag content slots
8484 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8486 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8487 if(!pBag)
8488 return false;
8490 // any post selected
8491 if (slot == NULL_SLOT)
8492 return true;
8494 return slot < pBag->GetBagSize();
8497 // where this?
8498 return false;
8502 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8504 uint32 tempcount = 0;
8505 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8507 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8508 if( pItem && pItem->GetEntry() == item )
8510 tempcount += pItem->GetCount();
8511 if( tempcount >= count )
8512 return true;
8515 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8517 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8518 if( pItem && pItem->GetEntry() == item )
8520 tempcount += pItem->GetCount();
8521 if( tempcount >= count )
8522 return true;
8525 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8527 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8529 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8531 Item* pItem = GetItemByPos( i, j );
8532 if( pItem && pItem->GetEntry() == item )
8534 tempcount += pItem->GetCount();
8535 if( tempcount >= count )
8536 return true;
8542 if(inBankAlso)
8544 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8546 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8547 if( pItem && pItem->GetEntry() == item )
8549 tempcount += pItem->GetCount();
8550 if( tempcount >= count )
8551 return true;
8554 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8556 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8558 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8560 Item* pItem = GetItemByPos( i, j );
8561 if( pItem && pItem->GetEntry() == item )
8563 tempcount += pItem->GetCount();
8564 if( tempcount >= count )
8565 return true;
8572 return false;
8575 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8577 uint32 tempcount = 0;
8578 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8580 if(i==int(except_slot))
8581 continue;
8583 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8584 if( pItem && pItem->GetEntry() == item)
8586 tempcount += pItem->GetCount();
8587 if( tempcount >= count )
8588 return true;
8592 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8593 if (pProto && pProto->GemProperties)
8595 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8597 if(i==int(except_slot))
8598 continue;
8600 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8601 if( pItem && pItem->GetProto()->Socket[0].Color)
8603 tempcount += pItem->GetGemCountWithID(item);
8604 if( tempcount >= count )
8605 return true;
8610 return false;
8613 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8615 uint32 tempcount = 0;
8616 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8618 if(i==int(except_slot))
8619 continue;
8621 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8622 if (!pItem)
8623 continue;
8625 ItemPrototype const *pProto = pItem->GetProto();
8626 if (!pProto)
8627 continue;
8629 if (pProto->ItemLimitCategory == limitCategory)
8631 tempcount += pItem->GetCount();
8632 if( tempcount >= count )
8633 return true;
8636 if( pProto->Socket[0].Color)
8638 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8639 if( tempcount >= count )
8640 return true;
8644 return false;
8647 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8649 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8650 if( !pProto )
8652 if(no_space_count)
8653 *no_space_count = count;
8654 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8657 // no maximum
8658 if(pProto->MaxCount <= 0)
8659 return EQUIP_ERR_OK;
8661 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8663 if (curcount + count > uint32(pProto->MaxCount))
8665 if(no_space_count)
8666 *no_space_count = count +curcount - pProto->MaxCount;
8667 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8670 return EQUIP_ERR_OK;
8673 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8675 Item *pItem;
8676 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8678 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8679 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8680 return true;
8682 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8684 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8685 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8686 return true;
8688 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8690 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8692 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8694 pItem = GetItemByPos( i, j );
8695 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8696 return true;
8700 return false;
8703 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8705 Item* pItem2 = GetItemByPos( bag, slot );
8707 // ignore move item (this slot will be empty at move)
8708 if(pItem2==pSrcItem)
8709 pItem2 = NULL;
8711 uint32 need_space;
8713 // empty specific slot - check item fit to slot
8714 if( !pItem2 || swap )
8716 if( bag == INVENTORY_SLOT_BAG_0 )
8718 // keyring case
8719 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8720 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8722 // currencytoken case
8723 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8724 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8726 // prevent cheating
8727 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8728 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8730 else
8732 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8733 if( !pBag )
8734 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8736 ItemPrototype const* pBagProto = pBag->GetProto();
8737 if( !pBagProto )
8738 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8740 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8741 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8744 // non empty stack with space
8745 need_space = pProto->GetMaxStackSize();
8747 // non empty slot, check item type
8748 else
8750 // check item type
8751 if(pItem2->GetEntry() != pProto->ItemId)
8752 return EQUIP_ERR_ITEM_CANT_STACK;
8754 // check free space
8755 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8756 return EQUIP_ERR_ITEM_CANT_STACK;
8758 // free stack space or infinity
8759 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8762 if(need_space > count)
8763 need_space = count;
8765 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8766 if(!newPosition.isContainedIn(dest))
8768 dest.push_back(newPosition);
8769 count -= need_space;
8771 return EQUIP_ERR_OK;
8774 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
8776 // skip specific bag already processed in first called _CanStoreItem_InBag
8777 if(bag==skip_bag)
8778 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8780 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8781 if( !pBag )
8782 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8784 ItemPrototype const* pBagProto = pBag->GetProto();
8785 if( !pBagProto )
8786 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8788 // specialized bag mode or non-specilized
8789 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8790 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8792 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8793 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8795 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8797 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8798 if(j==skip_slot)
8799 continue;
8801 Item* pItem2 = GetItemByPos( bag, j );
8803 // ignore move item (this slot will be empty at move)
8804 if(pItem2==pSrcItem)
8805 pItem2 = NULL;
8807 // if merge skip empty, if !merge skip non-empty
8808 if((pItem2!=NULL)!=merge)
8809 continue;
8811 if( pItem2 )
8813 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8815 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8816 if(need_space > count)
8817 need_space = count;
8819 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8820 if(!newPosition.isContainedIn(dest))
8822 dest.push_back(newPosition);
8823 count -= need_space;
8825 if(count==0)
8826 return EQUIP_ERR_OK;
8830 else
8832 uint32 need_space = pProto->GetMaxStackSize();
8833 if(need_space > count)
8834 need_space = count;
8836 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8837 if(!newPosition.isContainedIn(dest))
8839 dest.push_back(newPosition);
8840 count -= need_space;
8842 if(count==0)
8843 return EQUIP_ERR_OK;
8847 return EQUIP_ERR_OK;
8850 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
8852 for(uint32 j = slot_begin; j < slot_end; ++j)
8854 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8855 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8856 continue;
8858 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8860 // ignore move item (this slot will be empty at move)
8861 if(pItem2==pSrcItem)
8862 pItem2 = NULL;
8864 // if merge skip empty, if !merge skip non-empty
8865 if((pItem2!=NULL)!=merge)
8866 continue;
8868 if( pItem2 )
8870 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8872 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8873 if(need_space > count)
8874 need_space = count;
8875 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8876 if(!newPosition.isContainedIn(dest))
8878 dest.push_back(newPosition);
8879 count -= need_space;
8881 if(count==0)
8882 return EQUIP_ERR_OK;
8886 else
8888 uint32 need_space = pProto->GetMaxStackSize();
8889 if(need_space > count)
8890 need_space = count;
8892 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8893 if(!newPosition.isContainedIn(dest))
8895 dest.push_back(newPosition);
8896 count -= need_space;
8898 if(count==0)
8899 return EQUIP_ERR_OK;
8903 return EQUIP_ERR_OK;
8906 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8908 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8910 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8911 if( !pProto )
8913 if(no_space_count)
8914 *no_space_count = count;
8915 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8918 if(pItem && pItem->IsBindedNotWith(this))
8920 if(no_space_count)
8921 *no_space_count = count;
8922 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8925 // check count of items (skip for auto move for same player from bank)
8926 uint32 no_similar_count = 0; // can't store this amount similar items
8927 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8928 if(res!=EQUIP_ERR_OK)
8930 if(count==no_similar_count)
8932 if(no_space_count)
8933 *no_space_count = no_similar_count;
8934 return res;
8936 count -= no_similar_count;
8939 // in specific slot
8940 if( bag != NULL_BAG && slot != NULL_SLOT )
8942 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8943 if(res!=EQUIP_ERR_OK)
8945 if(no_space_count)
8946 *no_space_count = count + no_similar_count;
8947 return res;
8950 if(count==0)
8952 if(no_similar_count==0)
8953 return EQUIP_ERR_OK;
8955 if(no_space_count)
8956 *no_space_count = count + no_similar_count;
8957 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8961 // not specific slot or have space for partly store only in specific slot
8963 // in specific bag
8964 if( bag != NULL_BAG )
8966 // search stack in bag for merge to
8967 if( pProto->Stackable != 1 )
8969 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8971 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8972 if(res!=EQUIP_ERR_OK)
8974 if(no_space_count)
8975 *no_space_count = count + no_similar_count;
8976 return res;
8979 if(count==0)
8981 if(no_similar_count==0)
8982 return EQUIP_ERR_OK;
8984 if(no_space_count)
8985 *no_space_count = count + no_similar_count;
8986 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8989 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8990 if(res!=EQUIP_ERR_OK)
8992 if(no_space_count)
8993 *no_space_count = count + no_similar_count;
8994 return res;
8997 if(count==0)
8999 if(no_similar_count==0)
9000 return EQUIP_ERR_OK;
9002 if(no_space_count)
9003 *no_space_count = count + no_similar_count;
9004 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9007 else // equipped bag
9009 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9010 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9011 if(res!=EQUIP_ERR_OK)
9012 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9014 if(res!=EQUIP_ERR_OK)
9016 if(no_space_count)
9017 *no_space_count = count + no_similar_count;
9018 return res;
9021 if(count==0)
9023 if(no_similar_count==0)
9024 return EQUIP_ERR_OK;
9026 if(no_space_count)
9027 *no_space_count = count + no_similar_count;
9028 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9033 // search free slot in bag for place to
9034 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9036 // search free slot - keyring case
9037 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9039 uint32 keyringSize = GetMaxKeyringSize();
9040 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9041 if(res!=EQUIP_ERR_OK)
9043 if(no_space_count)
9044 *no_space_count = count + no_similar_count;
9045 return res;
9048 if(count==0)
9050 if(no_similar_count==0)
9051 return EQUIP_ERR_OK;
9053 if(no_space_count)
9054 *no_space_count = count + no_similar_count;
9055 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9058 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9059 if(res!=EQUIP_ERR_OK)
9061 if(no_space_count)
9062 *no_space_count = count + no_similar_count;
9063 return res;
9066 if(count==0)
9068 if(no_similar_count==0)
9069 return EQUIP_ERR_OK;
9071 if(no_space_count)
9072 *no_space_count = count + no_similar_count;
9073 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9076 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9078 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9079 if(res!=EQUIP_ERR_OK)
9081 if(no_space_count)
9082 *no_space_count = count + no_similar_count;
9083 return res;
9086 if(count==0)
9088 if(no_similar_count==0)
9089 return EQUIP_ERR_OK;
9091 if(no_space_count)
9092 *no_space_count = count + no_similar_count;
9093 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9097 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9098 if(res!=EQUIP_ERR_OK)
9100 if(no_space_count)
9101 *no_space_count = count + no_similar_count;
9102 return res;
9105 if(count==0)
9107 if(no_similar_count==0)
9108 return EQUIP_ERR_OK;
9110 if(no_space_count)
9111 *no_space_count = count + no_similar_count;
9112 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9115 else // equipped bag
9117 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9118 if(res!=EQUIP_ERR_OK)
9119 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9121 if(res!=EQUIP_ERR_OK)
9123 if(no_space_count)
9124 *no_space_count = count + no_similar_count;
9125 return res;
9128 if(count==0)
9130 if(no_similar_count==0)
9131 return EQUIP_ERR_OK;
9133 if(no_space_count)
9134 *no_space_count = count + no_similar_count;
9135 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9140 // not specific bag or have space for partly store only in specific bag
9142 // search stack for merge to
9143 if( pProto->Stackable != 1 )
9145 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9146 if(res!=EQUIP_ERR_OK)
9148 if(no_space_count)
9149 *no_space_count = count + no_similar_count;
9150 return res;
9153 if(count==0)
9155 if(no_similar_count==0)
9156 return EQUIP_ERR_OK;
9158 if(no_space_count)
9159 *no_space_count = count + no_similar_count;
9160 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9163 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9164 if(res!=EQUIP_ERR_OK)
9166 if(no_space_count)
9167 *no_space_count = count + no_similar_count;
9168 return res;
9171 if(count==0)
9173 if(no_similar_count==0)
9174 return EQUIP_ERR_OK;
9176 if(no_space_count)
9177 *no_space_count = count + no_similar_count;
9178 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9181 if( pProto->BagFamily )
9183 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9185 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9186 if(res!=EQUIP_ERR_OK)
9187 continue;
9189 if(count==0)
9191 if(no_similar_count==0)
9192 return EQUIP_ERR_OK;
9194 if(no_space_count)
9195 *no_space_count = count + no_similar_count;
9196 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9201 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9203 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9204 if(res!=EQUIP_ERR_OK)
9205 continue;
9207 if(count==0)
9209 if(no_similar_count==0)
9210 return EQUIP_ERR_OK;
9212 if(no_space_count)
9213 *no_space_count = count + no_similar_count;
9214 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9219 // search free slot - special bag case
9220 if( pProto->BagFamily )
9222 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9224 uint32 keyringSize = GetMaxKeyringSize();
9225 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9226 if(res!=EQUIP_ERR_OK)
9228 if(no_space_count)
9229 *no_space_count = count + no_similar_count;
9230 return res;
9233 if(count==0)
9235 if(no_similar_count==0)
9236 return EQUIP_ERR_OK;
9238 if(no_space_count)
9239 *no_space_count = count + no_similar_count;
9240 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9243 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9245 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9246 if(res!=EQUIP_ERR_OK)
9248 if(no_space_count)
9249 *no_space_count = count + no_similar_count;
9250 return res;
9253 if(count==0)
9255 if(no_similar_count==0)
9256 return EQUIP_ERR_OK;
9258 if(no_space_count)
9259 *no_space_count = count + no_similar_count;
9260 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9264 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9266 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9267 if(res!=EQUIP_ERR_OK)
9268 continue;
9270 if(count==0)
9272 if(no_similar_count==0)
9273 return EQUIP_ERR_OK;
9275 if(no_space_count)
9276 *no_space_count = count + no_similar_count;
9277 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9282 // search free slot
9283 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9284 if(res!=EQUIP_ERR_OK)
9286 if(no_space_count)
9287 *no_space_count = count + no_similar_count;
9288 return res;
9291 if(count==0)
9293 if(no_similar_count==0)
9294 return EQUIP_ERR_OK;
9296 if(no_space_count)
9297 *no_space_count = count + no_similar_count;
9298 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9301 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9303 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9304 if(res!=EQUIP_ERR_OK)
9305 continue;
9307 if(count==0)
9309 if(no_similar_count==0)
9310 return EQUIP_ERR_OK;
9312 if(no_space_count)
9313 *no_space_count = count + no_similar_count;
9314 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9318 if(no_space_count)
9319 *no_space_count = count + no_similar_count;
9321 return EQUIP_ERR_INVENTORY_FULL;
9324 //////////////////////////////////////////////////////////////////////////
9325 uint8 Player::CanStoreItems( Item **pItems,int count) const
9327 Item *pItem2;
9329 // fill space table
9330 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9331 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9332 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9333 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9335 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9336 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9337 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9338 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9340 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9342 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9344 if (pItem2 && !pItem2->IsInTrade())
9346 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9350 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9352 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9354 if (pItem2 && !pItem2->IsInTrade())
9356 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9360 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9362 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9364 if (pItem2 && !pItem2->IsInTrade())
9366 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9370 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9372 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9374 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9376 pItem2 = GetItemByPos( i, j );
9377 if (pItem2 && !pItem2->IsInTrade())
9379 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9385 // check free space for all items
9386 for (int k = 0; k < count; ++k)
9388 Item *pItem = pItems[k];
9390 // no item
9391 if (!pItem) continue;
9393 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9394 ItemPrototype const *pProto = pItem->GetProto();
9396 // strange item
9397 if( !pProto )
9398 return EQUIP_ERR_ITEM_NOT_FOUND;
9400 // item it 'bind'
9401 if(pItem->IsBindedNotWith(this))
9402 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9404 Bag *pBag;
9405 ItemPrototype const *pBagProto;
9407 // item is 'one item only'
9408 uint8 res = CanTakeMoreSimilarItems(pItem);
9409 if(res != EQUIP_ERR_OK)
9410 return res;
9412 // search stack for merge to
9413 if( pProto->Stackable != 1 )
9415 bool b_found = false;
9417 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9419 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9420 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9422 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9423 b_found = true;
9424 break;
9427 if (b_found) continue;
9429 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9431 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9432 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9434 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9435 b_found = true;
9436 break;
9439 if (b_found) continue;
9441 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9443 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9444 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9446 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9447 b_found = true;
9448 break;
9451 if (b_found) continue;
9453 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9455 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9456 if( pBag )
9458 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9460 pItem2 = GetItemByPos( t, j );
9461 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9463 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9464 b_found = true;
9465 break;
9470 if (b_found) continue;
9473 // special bag case
9474 if( pProto->BagFamily )
9476 bool b_found = false;
9477 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9479 uint32 keyringSize = GetMaxKeyringSize();
9480 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9482 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9484 inv_keys[t-KEYRING_SLOT_START] = 1;
9485 b_found = true;
9486 break;
9491 if (b_found) continue;
9493 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9495 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9497 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9499 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9500 b_found = true;
9501 break;
9506 if (b_found) continue;
9508 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9510 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9511 if( pBag )
9513 pBagProto = pBag->GetProto();
9515 // not plain container check
9516 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9517 ItemCanGoIntoBag(pProto,pBagProto) )
9519 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9521 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9523 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9524 b_found = true;
9525 break;
9531 if (b_found) continue;
9534 // search free slot
9535 bool b_found = false;
9536 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9538 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9540 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9541 b_found = true;
9542 break;
9545 if (b_found) continue;
9547 // search free slot in bags
9548 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9550 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9551 if( pBag )
9553 pBagProto = pBag->GetProto();
9555 // special bag already checked
9556 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9557 continue;
9559 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9561 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9563 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9564 b_found = true;
9565 break;
9571 // no free slot found?
9572 if (!b_found)
9573 return EQUIP_ERR_INVENTORY_FULL;
9576 return EQUIP_ERR_OK;
9579 //////////////////////////////////////////////////////////////////////////
9580 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9582 dest = 0;
9583 Item *pItem = Item::CreateItem( item, 1, this );
9584 if( pItem )
9586 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9587 delete pItem;
9588 return result;
9591 return EQUIP_ERR_ITEM_NOT_FOUND;
9594 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9596 dest = 0;
9597 if( pItem )
9599 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9600 ItemPrototype const *pProto = pItem->GetProto();
9601 if( pProto )
9603 if(pItem->IsBindedNotWith(this))
9604 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9606 // check count of items (skip for auto move for same player from bank)
9607 uint8 res = CanTakeMoreSimilarItems(pItem);
9608 if(res != EQUIP_ERR_OK)
9609 return res;
9611 // check this only in game
9612 if(not_loading)
9614 // May be here should be more stronger checks; STUNNED checked
9615 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9616 if (hasUnitState(UNIT_STAT_STUNNED))
9617 return EQUIP_ERR_YOU_ARE_STUNNED;
9619 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9620 // - combat
9621 // - in-progress arenas
9622 if( !pProto->CanChangeEquipStateInCombat() )
9624 if( isInCombat() )
9625 return EQUIP_ERR_NOT_IN_COMBAT;
9627 if(BattleGround* bg = GetBattleGround())
9628 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9629 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9632 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9633 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9635 if(IsNonMeleeSpellCasted(false))
9636 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9639 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
9640 if (ssd && ssd->MaxLevel < getLevel())
9641 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9643 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9644 if (eslot == NULL_SLOT)
9645 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9647 uint8 msg = CanUseItem(pItem , not_loading);
9648 if (msg != EQUIP_ERR_OK)
9649 return msg;
9650 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
9651 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9653 // if swap ignore item (equipped also)
9654 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9655 return res2;
9657 // check unique-equipped special item classes
9658 if (pProto->Class == ITEM_CLASS_QUIVER)
9660 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9662 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
9664 if (pBag != pItem)
9666 if (ItemPrototype const* pBagProto = pBag->GetProto())
9668 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
9669 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9670 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
9671 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9678 uint32 type = pProto->InventoryType;
9680 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9682 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9684 if (!CanDualWield())
9685 return EQUIP_ERR_CANT_DUAL_WIELD;
9687 else if (type == INVTYPE_2HWEAPON)
9689 if (!CanDualWield() || !CanTitanGrip())
9690 return EQUIP_ERR_CANT_DUAL_WIELD;
9693 if (IsTwoHandUsed())
9694 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9697 // equip two-hand weapon case (with possible unequip 2 items)
9698 if (type == INVTYPE_2HWEAPON)
9700 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9702 if (!CanTitanGrip())
9703 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9705 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9706 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9708 if (!CanTitanGrip())
9710 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9711 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9712 ItemPosCountVec off_dest;
9713 if (offItem && (!not_loading ||
9714 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9715 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
9716 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9719 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9720 return EQUIP_ERR_OK;
9724 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9727 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9729 // Applied only to equipped items and bank bags
9730 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9731 return EQUIP_ERR_OK;
9733 Item* pItem = GetItemByPos(pos);
9735 // Applied only to existed equipped item
9736 if( !pItem )
9737 return EQUIP_ERR_OK;
9739 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9741 ItemPrototype const *pProto = pItem->GetProto();
9742 if( !pProto )
9743 return EQUIP_ERR_ITEM_NOT_FOUND;
9745 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9746 // - combat
9747 // - in-progress arenas
9748 if( !pProto->CanChangeEquipStateInCombat() )
9750 if( isInCombat() )
9751 return EQUIP_ERR_NOT_IN_COMBAT;
9753 if(BattleGround* bg = GetBattleGround())
9754 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9755 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9758 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9759 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9761 return EQUIP_ERR_OK;
9764 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9766 if (!pItem)
9767 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9769 uint32 count = pItem->GetCount();
9771 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9772 ItemPrototype const *pProto = pItem->GetProto();
9773 if (!pProto)
9774 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9776 if (pItem->IsBindedNotWith(this))
9777 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9779 // check count of items (skip for auto move for same player from bank)
9780 uint8 res = CanTakeMoreSimilarItems(pItem);
9781 if (res != EQUIP_ERR_OK)
9782 return res;
9784 // in specific slot
9785 if (bag != NULL_BAG && slot != NULL_SLOT)
9787 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
9789 if (!pItem->IsBag())
9790 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9792 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
9793 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9795 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
9796 return cantuse;
9799 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9800 if (res!=EQUIP_ERR_OK)
9801 return res;
9803 if (count==0)
9804 return EQUIP_ERR_OK;
9807 // not specific slot or have space for partly store only in specific slot
9809 // in specific bag
9810 if( bag != NULL_BAG )
9812 if( pProto->InventoryType == INVTYPE_BAG )
9814 Bag *pBag = (Bag*)pItem;
9815 if( pBag && !pBag->IsEmpty() )
9816 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9819 // search stack in bag for merge to
9820 if( pProto->Stackable != 1 )
9822 if( bag == INVENTORY_SLOT_BAG_0 )
9824 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9825 if(res!=EQUIP_ERR_OK)
9826 return res;
9828 if(count==0)
9829 return EQUIP_ERR_OK;
9831 else
9833 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9834 if(res!=EQUIP_ERR_OK)
9835 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9837 if(res!=EQUIP_ERR_OK)
9838 return res;
9840 if(count==0)
9841 return EQUIP_ERR_OK;
9845 // search free slot in bag
9846 if( bag == INVENTORY_SLOT_BAG_0 )
9848 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9849 if(res!=EQUIP_ERR_OK)
9850 return res;
9852 if(count==0)
9853 return EQUIP_ERR_OK;
9855 else
9857 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
9858 if(res != EQUIP_ERR_OK)
9859 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
9861 if(res != EQUIP_ERR_OK)
9862 return res;
9864 if(count == 0)
9865 return EQUIP_ERR_OK;
9869 // not specific bag or have space for partly store only in specific bag
9871 // search stack for merge to
9872 if( pProto->Stackable != 1 )
9874 // in slots
9875 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9876 if(res != EQUIP_ERR_OK)
9877 return res;
9879 if(count == 0)
9880 return EQUIP_ERR_OK;
9882 // in special bags
9883 if( pProto->BagFamily )
9885 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9887 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9888 if(res!=EQUIP_ERR_OK)
9889 continue;
9891 if(count==0)
9892 return EQUIP_ERR_OK;
9896 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9898 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9899 if(res!=EQUIP_ERR_OK)
9900 continue;
9902 if(count==0)
9903 return EQUIP_ERR_OK;
9907 // search free place in special bag
9908 if( pProto->BagFamily )
9910 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9912 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9913 if(res!=EQUIP_ERR_OK)
9914 continue;
9916 if(count==0)
9917 return EQUIP_ERR_OK;
9921 // search free space
9922 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9923 if(res!=EQUIP_ERR_OK)
9924 return res;
9926 if(count==0)
9927 return EQUIP_ERR_OK;
9929 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9931 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9932 if(res!=EQUIP_ERR_OK)
9933 continue;
9935 if(count==0)
9936 return EQUIP_ERR_OK;
9938 return EQUIP_ERR_BANK_FULL;
9941 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9943 if (pItem)
9945 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9947 if (!isAlive() && not_loading)
9948 return EQUIP_ERR_YOU_ARE_DEAD;
9950 //if (isStunned())
9951 // return EQUIP_ERR_YOU_ARE_STUNNED;
9953 ItemPrototype const *pProto = pItem->GetProto();
9954 if (pProto)
9956 if (pItem->IsBindedNotWith(this))
9957 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9959 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
9960 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9962 if (pItem->GetSkill() != 0)
9964 if (GetSkillValue( pItem->GetSkill() ) == 0)
9965 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9968 if (pProto->RequiredSkill != 0)
9970 if (GetSkillValue( pProto->RequiredSkill ) == 0)
9971 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9973 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
9974 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9977 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
9978 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9980 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
9981 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9983 if (getLevel() < pProto->RequiredLevel)
9984 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9986 return EQUIP_ERR_OK;
9989 return EQUIP_ERR_ITEM_NOT_FOUND;
9992 bool Player::CanUseItem( ItemPrototype const *pProto )
9994 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9996 if( pProto )
9998 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9999 return false;
10000 if( pProto->RequiredSkill != 0 )
10002 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10003 return false;
10004 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10005 return false;
10007 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10008 return false;
10009 if( getLevel() < pProto->RequiredLevel )
10010 return false;
10011 return true;
10013 return false;
10016 uint8 Player::CanUseAmmo( uint32 item ) const
10018 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10019 if( !isAlive() )
10020 return EQUIP_ERR_YOU_ARE_DEAD;
10021 //if( isStunned() )
10022 // return EQUIP_ERR_YOU_ARE_STUNNED;
10023 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10024 if( pProto )
10026 if( pProto->InventoryType!= INVTYPE_AMMO )
10027 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10028 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10029 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10030 if( pProto->RequiredSkill != 0 )
10032 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10033 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10034 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10035 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10037 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10038 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10039 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10040 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10042 if( getLevel() < pProto->RequiredLevel )
10043 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10045 // Requires No Ammo
10046 if(GetDummyAura(46699))
10047 return EQUIP_ERR_BAG_FULL6;
10049 return EQUIP_ERR_OK;
10051 return EQUIP_ERR_ITEM_NOT_FOUND;
10054 void Player::SetAmmo( uint32 item )
10056 if(!item)
10057 return;
10059 // already set
10060 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10061 return;
10063 // check ammo
10064 if(item)
10066 uint8 msg = CanUseAmmo( item );
10067 if( msg != EQUIP_ERR_OK )
10069 SendEquipError( msg, NULL, NULL );
10070 return;
10074 SetUInt32Value(PLAYER_AMMO_ID, item);
10076 _ApplyAmmoBonuses();
10079 void Player::RemoveAmmo()
10081 SetUInt32Value(PLAYER_AMMO_ID, 0);
10083 m_ammoDPS = 0.0f;
10085 if(CanModifyStats())
10086 UpdateDamagePhysical(RANGED_ATTACK);
10089 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10090 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10092 uint32 count = 0;
10093 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10094 count += itr->count;
10096 Item *pItem = Item::CreateItem( item, count, this );
10097 if( pItem )
10099 ItemAddedQuestCheck( item, count );
10100 if(randomPropertyId)
10101 pItem->SetItemRandomProperties(randomPropertyId);
10102 pItem = StoreItem( dest, pItem, update );
10104 return pItem;
10107 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10109 if( !pItem )
10110 return NULL;
10112 Item* lastItem = pItem;
10113 uint32 entry = pItem->GetEntry();
10114 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10116 uint16 pos = itr->pos;
10117 uint32 count = itr->count;
10119 ++itr;
10121 if(itr == dest.end())
10123 lastItem = _StoreItem(pos,pItem,count,false,update);
10124 break;
10127 lastItem = _StoreItem(pos,pItem,count,true,update);
10129 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10130 return lastItem;
10133 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10134 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10136 if( !pItem )
10137 return NULL;
10139 uint8 bag = pos >> 8;
10140 uint8 slot = pos & 255;
10142 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10144 Item *pItem2 = GetItemByPos( bag, slot );
10146 if (!pItem2)
10148 if (clone)
10149 pItem = pItem->CloneItem(count, this);
10150 else
10151 pItem->SetCount(count);
10153 if (!pItem)
10154 return NULL;
10156 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10157 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10158 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10159 pItem->SetBinding( true );
10161 if (bag == INVENTORY_SLOT_BAG_0)
10163 m_items[slot] = pItem;
10164 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10165 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10166 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10168 pItem->SetSlot( slot );
10169 pItem->SetContainer( NULL );
10171 // need update known currency
10172 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10173 UpdateKnownCurrencies(pItem->GetEntry(), true);
10175 if (IsInWorld() && update)
10177 pItem->AddToWorld();
10178 pItem->SendUpdateToPlayer( this );
10181 pItem->SetState(ITEM_CHANGED, this);
10183 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10185 pBag->StoreItem( slot, pItem, update );
10186 if( IsInWorld() && update )
10188 pItem->AddToWorld();
10189 pItem->SendUpdateToPlayer( this );
10191 pItem->SetState(ITEM_CHANGED, this);
10192 pBag->SetState(ITEM_CHANGED, this);
10195 AddEnchantmentDurations(pItem);
10196 AddItemDurations(pItem);
10198 return pItem;
10200 else
10202 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10203 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10204 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10205 pItem2->SetBinding( true );
10207 pItem2->SetCount( pItem2->GetCount() + count );
10208 if (IsInWorld() && update)
10209 pItem2->SendUpdateToPlayer( this );
10211 if (!clone)
10213 // delete item (it not in any slot currently)
10214 if (IsInWorld() && update)
10216 pItem->RemoveFromWorld();
10217 pItem->DestroyForPlayer( this );
10220 RemoveEnchantmentDurations(pItem);
10221 RemoveItemDurations(pItem);
10223 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10224 pItem->SetState(ITEM_REMOVED, this);
10227 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10228 AddEnchantmentDurations(pItem2);
10230 pItem2->SetState(ITEM_CHANGED, this);
10232 return pItem2;
10236 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10238 if (Item *pItem = Item::CreateItem( item, 1, this ))
10240 ItemAddedQuestCheck( item, 1 );
10241 return EquipItem( pos, pItem, update );
10244 return NULL;
10247 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10250 AddEnchantmentDurations(pItem);
10251 AddItemDurations(pItem);
10253 uint8 bag = pos >> 8;
10254 uint8 slot = pos & 255;
10256 Item *pItem2 = GetItemByPos( bag, slot );
10258 if( !pItem2 )
10260 VisualizeItem( slot, pItem);
10262 if(isAlive())
10264 ItemPrototype const *pProto = pItem->GetProto();
10266 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10267 if(pProto && pProto->ItemSet)
10268 AddItemsSetItem(this, pItem);
10270 _ApplyItemMods(pItem, slot, true);
10272 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10274 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10276 if (getClass() == CLASS_ROGUE)
10277 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10279 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10281 if (!spellProto)
10282 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10283 else
10285 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10287 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10288 data << uint64(GetGUID());
10289 data << uint8(1);
10290 data << uint32(cooldownSpell);
10291 data << uint32(0);
10292 GetSession()->SendPacket(&data);
10297 if( IsInWorld() && update )
10299 pItem->AddToWorld();
10300 pItem->SendUpdateToPlayer( this );
10303 ApplyEquipCooldown(pItem);
10305 if( slot == EQUIPMENT_SLOT_MAINHAND )
10306 UpdateExpertise(BASE_ATTACK);
10307 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10308 UpdateExpertise(OFF_ATTACK);
10310 else
10312 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10313 if( IsInWorld() && update )
10314 pItem2->SendUpdateToPlayer( this );
10316 // delete item (it not in any slot currently)
10317 //pItem->DeleteFromDB();
10318 if( IsInWorld() && update )
10320 pItem->RemoveFromWorld();
10321 pItem->DestroyForPlayer( this );
10324 RemoveEnchantmentDurations(pItem);
10325 RemoveItemDurations(pItem);
10327 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10328 pItem->SetState(ITEM_REMOVED, this);
10329 pItem2->SetState(ITEM_CHANGED, this);
10331 ApplyEquipCooldown(pItem2);
10333 return pItem2;
10336 // only for full equip instead adding to stack
10337 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10339 return pItem;
10342 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10344 if( pItem )
10346 AddEnchantmentDurations(pItem);
10347 AddItemDurations(pItem);
10349 uint8 slot = pos & 255;
10350 VisualizeItem( slot, pItem);
10352 if( IsInWorld() )
10354 pItem->AddToWorld();
10355 pItem->SendUpdateToPlayer( this );
10358 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10362 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10364 if(pItem)
10366 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10367 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10368 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10370 else
10372 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10373 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10377 void Player::VisualizeItem( uint8 slot, Item *pItem)
10379 if(!pItem)
10380 return;
10382 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10383 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10384 pItem->SetBinding( true );
10386 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10388 m_items[slot] = pItem;
10389 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10390 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10391 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10392 pItem->SetSlot( slot );
10393 pItem->SetContainer( NULL );
10395 if( slot < EQUIPMENT_SLOT_END )
10396 SetVisibleItemSlot(slot, pItem);
10398 pItem->SetState(ITEM_CHANGED, this);
10401 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10403 // note: removeitem does not actually change the item
10404 // it only takes the item out of storage temporarily
10405 // note2: if removeitem is to be used for delinking
10406 // the item must be removed from the player's updatequeue
10408 Item *pItem = GetItemByPos( bag, slot );
10409 if( pItem )
10411 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10413 RemoveEnchantmentDurations(pItem);
10414 RemoveItemDurations(pItem);
10416 if( bag == INVENTORY_SLOT_BAG_0 )
10418 if ( slot < INVENTORY_SLOT_BAG_END )
10420 ItemPrototype const *pProto = pItem->GetProto();
10421 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10423 if(pProto && pProto->ItemSet)
10424 RemoveItemsSetItem(this, pProto);
10426 _ApplyItemMods(pItem, slot, false);
10428 // remove item dependent auras and casts (only weapon and armor slots)
10429 if(slot < EQUIPMENT_SLOT_END)
10431 RemoveItemDependentAurasAndCasts(pItem);
10433 // remove held enchantments, update expertise
10434 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10436 if (pItem->GetItemSuffixFactor())
10438 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10439 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10441 else
10443 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10444 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10447 UpdateExpertise(BASE_ATTACK);
10449 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10450 UpdateExpertise(OFF_ATTACK);
10453 // need update known currency
10454 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10455 UpdateKnownCurrencies(pItem->GetEntry(), false);
10457 m_items[slot] = NULL;
10458 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10460 if ( slot < EQUIPMENT_SLOT_END )
10461 SetVisibleItemSlot(slot, NULL);
10463 else
10465 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10466 if( pBag )
10467 pBag->RemoveItem(slot, update);
10469 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10470 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10471 pItem->SetSlot( NULL_SLOT );
10472 if( IsInWorld() && update )
10473 pItem->SendUpdateToPlayer( this );
10477 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10478 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10480 if(Item* it = GetItemByPos(bag,slot))
10482 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10483 RemoveItem(bag, slot, update);
10484 it->RemoveFromUpdateQueueOf(this);
10485 if(it->IsInWorld())
10487 it->RemoveFromWorld();
10488 it->DestroyForPlayer( this );
10493 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10494 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10496 // update quest counters
10497 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10499 // store item
10500 Item* pLastItem = StoreItem(dest, pItem, update);
10502 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10503 if(pLastItem == pItem)
10505 // update owner for last item (this can be original item with wrong owner
10506 if(pLastItem->GetOwnerGUID() != GetGUID())
10507 pLastItem->SetOwnerGUID(GetGUID());
10509 // if this original item then it need create record in inventory
10510 // in case trade we already have item in other player inventory
10511 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10515 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10517 Item *pItem = GetItemByPos( bag, slot );
10518 if( pItem )
10520 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10522 // start from destroy contained items (only equipped bag can have its)
10523 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10525 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10526 DestroyItem(slot, i, update);
10529 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10530 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10532 RemoveEnchantmentDurations(pItem);
10533 RemoveItemDurations(pItem);
10535 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10537 if( bag == INVENTORY_SLOT_BAG_0 )
10539 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10541 // equipment and equipped bags can have applied bonuses
10542 if ( slot < INVENTORY_SLOT_BAG_END )
10544 ItemPrototype const *pProto = pItem->GetProto();
10546 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10547 if(pProto && pProto->ItemSet)
10548 RemoveItemsSetItem(this, pProto);
10550 _ApplyItemMods(pItem, slot, false);
10553 if ( slot < EQUIPMENT_SLOT_END )
10555 // remove item dependent auras and casts (only weapon and armor slots)
10556 RemoveItemDependentAurasAndCasts(pItem);
10558 // update expertise
10559 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10560 UpdateExpertise(BASE_ATTACK);
10561 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10562 UpdateExpertise(OFF_ATTACK);
10564 // equipment visual show
10565 SetVisibleItemSlot(slot, NULL);
10567 // need update known currency
10568 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10569 UpdateKnownCurrencies(pItem->GetEntry(), false);
10571 m_items[slot] = NULL;
10573 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10574 pBag->RemoveItem(slot, update);
10576 if( IsInWorld() && update )
10578 pItem->RemoveFromWorld();
10579 pItem->DestroyForPlayer(this);
10582 //pItem->SetOwnerGUID(0);
10583 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10584 pItem->SetSlot( NULL_SLOT );
10585 pItem->SetState(ITEM_REMOVED, this);
10589 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10591 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10592 uint32 remcount = 0;
10594 // in inventory
10595 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10597 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10599 if (pItem->GetEntry() == item)
10601 if (pItem->GetCount() + remcount <= count)
10603 // all items in inventory can unequipped
10604 remcount += pItem->GetCount();
10605 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10607 if (remcount >= count)
10608 return;
10610 else
10612 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10613 pItem->SetCount( pItem->GetCount() - count + remcount );
10614 if (IsInWorld() & update)
10615 pItem->SendUpdateToPlayer( this );
10616 pItem->SetState(ITEM_CHANGED, this);
10617 return;
10623 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10625 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10627 if (pItem->GetEntry() == item)
10629 if (pItem->GetCount() + remcount <= count)
10631 // all keys can be unequipped
10632 remcount += pItem->GetCount();
10633 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10635 if (remcount >= count)
10636 return;
10638 else
10640 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10641 pItem->SetCount( pItem->GetCount() - count + remcount );
10642 if (IsInWorld() & update)
10643 pItem->SendUpdateToPlayer( this );
10644 pItem->SetState(ITEM_CHANGED, this);
10645 return;
10651 // in inventory bags
10652 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10654 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10656 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10658 if(Item* pItem = pBag->GetItemByPos(j))
10660 if (pItem->GetEntry() == item)
10662 // all items in bags can be unequipped
10663 if (pItem->GetCount() + remcount <= count)
10665 remcount += pItem->GetCount();
10666 DestroyItem( i, j, update );
10668 if (remcount >= count)
10669 return;
10671 else
10673 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10674 pItem->SetCount( pItem->GetCount() - count + remcount );
10675 if (IsInWorld() && update)
10676 pItem->SendUpdateToPlayer( this );
10677 pItem->SetState(ITEM_CHANGED, this);
10678 return;
10686 // in equipment and bag list
10687 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10689 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10691 if (pItem && pItem->GetEntry() == item)
10693 if (pItem->GetCount() + remcount <= count)
10695 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
10697 remcount += pItem->GetCount();
10698 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10700 if (remcount >= count)
10701 return;
10704 else
10706 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10707 pItem->SetCount( pItem->GetCount() - count + remcount );
10708 if (IsInWorld() & update)
10709 pItem->SendUpdateToPlayer( this );
10710 pItem->SetState(ITEM_CHANGED, this);
10711 return;
10718 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10720 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10722 // in inventory
10723 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10724 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10725 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10726 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10728 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10729 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10730 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10731 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10733 // in inventory bags
10734 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10735 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10736 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10737 if (Item* pItem = pBag->GetItemByPos(j))
10738 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10739 DestroyItem(i, j, update);
10741 // in equipment and bag list
10742 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10743 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10744 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10745 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10748 void Player::DestroyConjuredItems( bool update )
10750 // used when entering arena
10751 // destroys all conjured items
10752 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10754 // in inventory
10755 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10756 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10757 if (pItem->IsConjuredConsumable())
10758 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10760 // in inventory bags
10761 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10762 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10763 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10764 if (Item* pItem = pBag->GetItemByPos(j))
10765 if (pItem->IsConjuredConsumable())
10766 DestroyItem( i, j, update);
10768 // in equipment and bag list
10769 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10770 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10771 if (pItem->IsConjuredConsumable())
10772 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10775 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10777 if(!pItem)
10778 return;
10780 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10782 if( pItem->GetCount() <= count )
10784 count -= pItem->GetCount();
10786 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10788 else
10790 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10791 pItem->SetCount( pItem->GetCount() - count );
10792 count = 0;
10793 if( IsInWorld() & update )
10794 pItem->SendUpdateToPlayer( this );
10795 pItem->SetState(ITEM_CHANGED, this);
10799 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10801 uint8 srcbag = src >> 8;
10802 uint8 srcslot = src & 255;
10804 uint8 dstbag = dst >> 8;
10805 uint8 dstslot = dst & 255;
10807 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10808 if( !pSrcItem )
10810 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10811 return;
10814 // not let split all items (can be only at cheating)
10815 if(pSrcItem->GetCount() == count)
10817 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10818 return;
10821 // not let split more existed items (can be only at cheating)
10822 if(pSrcItem->GetCount() < count)
10824 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10825 return;
10828 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10830 //best error message found for attempting to split while looting
10831 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10832 return;
10835 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10836 Item *pNewItem = pSrcItem->CloneItem( count, this );
10837 if( !pNewItem )
10839 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10840 return;
10843 if( IsInventoryPos( dst ) )
10845 // change item amount before check (for unique max count check)
10846 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10848 ItemPosCountVec dest;
10849 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10850 if( msg != EQUIP_ERR_OK )
10852 delete pNewItem;
10853 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10854 SendEquipError( msg, pSrcItem, NULL );
10855 return;
10858 if( IsInWorld() )
10859 pSrcItem->SendUpdateToPlayer( this );
10860 pSrcItem->SetState(ITEM_CHANGED, this);
10861 StoreItem( dest, pNewItem, true);
10863 else if( IsBankPos ( dst ) )
10865 // change item amount before check (for unique max count check)
10866 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10868 ItemPosCountVec dest;
10869 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10870 if( msg != EQUIP_ERR_OK )
10872 delete pNewItem;
10873 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10874 SendEquipError( msg, pSrcItem, NULL );
10875 return;
10878 if( IsInWorld() )
10879 pSrcItem->SendUpdateToPlayer( this );
10880 pSrcItem->SetState(ITEM_CHANGED, this);
10881 BankItem( dest, pNewItem, true);
10883 else if( IsEquipmentPos ( dst ) )
10885 // change item amount before check (for unique max count check), provide space for splitted items
10886 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10888 uint16 dest;
10889 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10890 if( msg != EQUIP_ERR_OK )
10892 delete pNewItem;
10893 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10894 SendEquipError( msg, pSrcItem, NULL );
10895 return;
10898 if( IsInWorld() )
10899 pSrcItem->SendUpdateToPlayer( this );
10900 pSrcItem->SetState(ITEM_CHANGED, this);
10901 EquipItem( dest, pNewItem, true);
10902 AutoUnequipOffhandIfNeed();
10906 void Player::SwapItem( uint16 src, uint16 dst )
10908 uint8 srcbag = src >> 8;
10909 uint8 srcslot = src & 255;
10911 uint8 dstbag = dst >> 8;
10912 uint8 dstslot = dst & 255;
10914 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10915 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10917 if( !pSrcItem )
10918 return;
10920 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10922 if(!isAlive() )
10924 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10925 return;
10928 // SRC checks
10930 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10932 //best error message found for attempting to swap while looting
10933 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10934 return;
10937 // check unequip potability for equipped items and bank bags
10938 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10940 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10941 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
10942 if(msg != EQUIP_ERR_OK)
10944 SendEquipError( msg, pSrcItem, pDstItem );
10945 return;
10949 // prevent put equipped/bank bag in self
10950 if( IsBagPos ( src ) && srcslot == dstbag)
10952 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10953 return;
10956 // DST checks
10958 if (pDstItem)
10960 if(pDstItem->m_lootGenerated) // prevent swap looting item
10962 //best error message found for attempting to swap while looting
10963 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10964 return;
10967 // check unequip potability for equipped items and bank bags
10968 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10970 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10971 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
10972 if(msg != EQUIP_ERR_OK)
10974 SendEquipError( msg, pSrcItem, pDstItem );
10975 return;
10980 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10981 // or swap empty bag with another empty or not empty bag (with items exchange)
10983 // Move case
10984 if( !pDstItem )
10986 if( IsInventoryPos( dst ) )
10988 ItemPosCountVec dest;
10989 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10990 if( msg != EQUIP_ERR_OK )
10992 SendEquipError( msg, pSrcItem, NULL );
10993 return;
10996 RemoveItem(srcbag, srcslot, true);
10997 StoreItem( dest, pSrcItem, true);
10999 else if( IsBankPos ( dst ) )
11001 ItemPosCountVec dest;
11002 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11003 if( msg != EQUIP_ERR_OK )
11005 SendEquipError( msg, pSrcItem, NULL );
11006 return;
11009 RemoveItem(srcbag, srcslot, true);
11010 BankItem( dest, pSrcItem, true);
11012 else if( IsEquipmentPos ( dst ) )
11014 uint16 dest;
11015 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11016 if( msg != EQUIP_ERR_OK )
11018 SendEquipError( msg, pSrcItem, NULL );
11019 return;
11022 RemoveItem(srcbag, srcslot, true);
11023 EquipItem(dest, pSrcItem, true);
11024 AutoUnequipOffhandIfNeed();
11027 return;
11030 // attempt merge to / fill target item
11031 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11033 uint8 msg;
11034 ItemPosCountVec sDest;
11035 uint16 eDest;
11036 if( IsInventoryPos( dst ) )
11037 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11038 else if( IsBankPos ( dst ) )
11039 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11040 else if( IsEquipmentPos ( dst ) )
11041 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11042 else
11043 return;
11045 // can be merge/fill
11046 if(msg == EQUIP_ERR_OK)
11048 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11050 RemoveItem(srcbag, srcslot, true);
11052 if( IsInventoryPos( dst ) )
11053 StoreItem( sDest, pSrcItem, true);
11054 else if( IsBankPos ( dst ) )
11055 BankItem( sDest, pSrcItem, true);
11056 else if( IsEquipmentPos ( dst ) )
11058 EquipItem( eDest, pSrcItem, true);
11059 AutoUnequipOffhandIfNeed();
11062 else
11064 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11065 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11066 pSrcItem->SetState(ITEM_CHANGED, this);
11067 pDstItem->SetState(ITEM_CHANGED, this);
11068 if( IsInWorld() )
11070 pSrcItem->SendUpdateToPlayer( this );
11071 pDstItem->SendUpdateToPlayer( this );
11074 return;
11078 // impossible merge/fill, do real swap
11079 uint8 msg;
11081 // check src->dest move possibility
11082 ItemPosCountVec sDest;
11083 uint16 eDest = 0;
11084 if( IsInventoryPos( dst ) )
11085 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11086 else if( IsBankPos( dst ) )
11087 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11088 else if( IsEquipmentPos( dst ) )
11090 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11091 if( msg == EQUIP_ERR_OK )
11092 msg = CanUnequipItem( eDest, true );
11095 if( msg != EQUIP_ERR_OK )
11097 SendEquipError( msg, pSrcItem, pDstItem );
11098 return;
11101 // check dest->src move possibility
11102 ItemPosCountVec sDest2;
11103 uint16 eDest2 = 0;
11104 if( IsInventoryPos( src ) )
11105 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11106 else if( IsBankPos( src ) )
11107 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11108 else if( IsEquipmentPos( src ) )
11110 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11111 if( msg == EQUIP_ERR_OK )
11112 msg = CanUnequipItem( eDest2, true);
11115 if( msg != EQUIP_ERR_OK )
11117 SendEquipError( msg, pDstItem, pSrcItem );
11118 return;
11121 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11122 if(pSrcItem->IsBag() && pDstItem->IsBag())
11124 Bag* emptyBag = NULL;
11125 Bag* fullBag = NULL;
11126 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11128 emptyBag = (Bag*)pSrcItem;
11129 fullBag = (Bag*)pDstItem;
11131 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11133 emptyBag = (Bag*)pDstItem;
11134 fullBag = (Bag*)pSrcItem;
11137 // bag swap (with items exchange) case
11138 if(emptyBag && fullBag)
11140 ItemPrototype const* emotyProto = emptyBag->GetProto();
11142 uint32 count = 0;
11144 for(int i=0; i < fullBag->GetBagSize(); ++i)
11146 Item *bagItem = fullBag->GetItemByPos(i);
11147 if (!bagItem)
11148 continue;
11150 ItemPrototype const* bagItemProto = bagItem->GetProto();
11151 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11153 // one from items not go to empty target bag
11154 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11155 return;
11158 ++count;
11162 if (count > emptyBag->GetBagSize())
11164 // too small targeted bag
11165 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11166 return;
11169 // Items swap
11170 count = 0; // will pos in new bag
11171 for(int i = 0; i< fullBag->GetBagSize(); ++i)
11173 Item *bagItem = fullBag->GetItemByPos(i);
11174 if (!bagItem)
11175 continue;
11177 fullBag->RemoveItem(i, true);
11178 emptyBag->StoreItem(count, bagItem, true);
11179 bagItem->SetState(ITEM_CHANGED, this);
11181 ++count;
11186 // now do moves, remove...
11187 RemoveItem(dstbag, dstslot, false);
11188 RemoveItem(srcbag, srcslot, false);
11190 // add to dest
11191 if( IsInventoryPos( dst ) )
11192 StoreItem(sDest, pSrcItem, true);
11193 else if( IsBankPos( dst ) )
11194 BankItem(sDest, pSrcItem, true);
11195 else if( IsEquipmentPos( dst ) )
11196 EquipItem(eDest, pSrcItem, true);
11198 // add to src
11199 if( IsInventoryPos( src ) )
11200 StoreItem(sDest2, pDstItem, true);
11201 else if( IsBankPos( src ) )
11202 BankItem(sDest2, pDstItem, true);
11203 else if( IsEquipmentPos( src ) )
11204 EquipItem(eDest2, pDstItem, true);
11206 AutoUnequipOffhandIfNeed();
11209 void Player::AddItemToBuyBackSlot( Item *pItem )
11211 if( pItem )
11213 uint32 slot = m_currentBuybackSlot;
11214 // if current back slot non-empty search oldest or free
11215 if(m_items[slot])
11217 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11218 uint32 oldest_slot = BUYBACK_SLOT_START;
11220 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11222 // found empty
11223 if(!m_items[i])
11225 slot = i;
11226 break;
11229 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11231 if(oldest_time > i_time)
11233 oldest_time = i_time;
11234 oldest_slot = i;
11238 // find oldest
11239 slot = oldest_slot;
11242 RemoveItemFromBuyBackSlot( slot, true );
11243 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11245 m_items[slot] = pItem;
11246 time_t base = time(NULL);
11247 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11248 uint32 eslot = slot - BUYBACK_SLOT_START;
11250 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11251 ItemPrototype const *pProto = pItem->GetProto();
11252 if( pProto )
11253 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11254 else
11255 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11256 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11258 // move to next (for non filled list is move most optimized choice)
11259 if(m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11260 ++m_currentBuybackSlot;
11264 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11266 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11267 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11268 return m_items[slot];
11269 return NULL;
11272 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11274 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11275 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11277 Item *pItem = m_items[slot];
11278 if( pItem )
11280 pItem->RemoveFromWorld();
11281 if(del) pItem->SetState(ITEM_REMOVED, this);
11284 m_items[slot] = NULL;
11286 uint32 eslot = slot - BUYBACK_SLOT_START;
11287 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11288 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11289 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11291 // if current backslot is filled set to now free slot
11292 if(m_items[m_currentBuybackSlot])
11293 m_currentBuybackSlot = slot;
11297 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11299 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11300 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11301 data << uint8(msg);
11303 if(msg)
11305 data << uint64(pItem ? pItem->GetGUID() : 0);
11306 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11307 data << uint8(0); // not 0 there...
11309 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11311 uint32 level = 0;
11313 if(pItem)
11314 if(ItemPrototype const* proto = pItem->GetProto())
11315 level = proto->RequiredLevel;
11317 data << uint32(level); // new 2.4.0
11320 GetSession()->SendPacket(&data);
11323 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11325 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11326 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11327 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11328 data << uint32(item);
11329 if( param > 0 )
11330 data << uint32(param);
11331 data << uint8(msg);
11332 GetSession()->SendPacket(&data);
11335 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11337 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11338 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11339 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11340 data << uint64(guid);
11341 if( param > 0 )
11342 data << uint32(param);
11343 data << uint8(msg);
11344 GetSession()->SendPacket(&data);
11347 void Player::ClearTrade()
11349 tradeGold = 0;
11350 acceptTrade = false;
11351 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11352 tradeItems[i] = NULL_SLOT;
11355 void Player::TradeCancel(bool sendback)
11357 if(pTrader)
11359 // send yellow "Trade canceled" message to both traders
11360 WorldSession* ws;
11361 ws = GetSession();
11362 if(sendback)
11363 ws->SendCancelTrade();
11364 ws = pTrader->GetSession();
11365 if(!ws->PlayerLogout())
11366 ws->SendCancelTrade();
11368 // cleanup
11369 ClearTrade();
11370 pTrader->ClearTrade();
11371 // prevent loss of reference
11372 pTrader->pTrader = NULL;
11373 pTrader = NULL;
11377 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11379 if(m_itemDuration.empty())
11380 return;
11382 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11384 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11386 Item* item = *itr;
11387 ++itr; // current element can be erased in UpdateDuration
11389 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11390 item->UpdateDuration(this,time);
11394 void Player::UpdateEnchantTime(uint32 time)
11396 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11398 assert(itr->item);
11399 next = itr;
11400 if(!itr->item->GetEnchantmentId(itr->slot))
11402 next = m_enchantDuration.erase(itr);
11404 else if(itr->leftduration <= time)
11406 ApplyEnchantment(itr->item, itr->slot, false, false);
11407 itr->item->ClearEnchantment(itr->slot);
11408 next = m_enchantDuration.erase(itr);
11410 else if(itr->leftduration > time)
11412 itr->leftduration -= time;
11413 ++next;
11418 void Player::AddEnchantmentDurations(Item *item)
11420 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11422 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11423 continue;
11425 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11426 if( duration > 0 )
11427 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11431 void Player::RemoveEnchantmentDurations(Item *item)
11433 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11435 if(itr->item == item)
11437 // save duration in item
11438 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11439 itr = m_enchantDuration.erase(itr);
11441 else
11442 ++itr;
11446 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11448 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11449 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11451 next = itr;
11452 if(itr->slot == slot)
11454 if(itr->item && itr->item->GetEnchantmentId(slot))
11456 // remove from stats
11457 ApplyEnchantment(itr->item, slot, false, false);
11458 // remove visual
11459 itr->item->ClearEnchantment(slot);
11461 // remove from update list
11462 next = m_enchantDuration.erase(itr);
11464 else
11465 ++next;
11468 // remove enchants from inventory items
11469 // NOTE: no need to remove these from stats, since these aren't equipped
11470 // in inventory
11471 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11473 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11474 if( pItem && pItem->GetEnchantmentId(slot) )
11475 pItem->ClearEnchantment(slot);
11478 // in inventory bags
11479 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11481 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11482 if( pBag )
11484 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11486 Item* pItem = pBag->GetItemByPos(j);
11487 if( pItem && pItem->GetEnchantmentId(slot) )
11488 pItem->ClearEnchantment(slot);
11494 // duration == 0 will remove item enchant
11495 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11497 if(!item)
11498 return;
11500 if(slot >= MAX_ENCHANTMENT_SLOT)
11501 return;
11503 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11505 if(itr->item == item && itr->slot == slot)
11507 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11508 m_enchantDuration.erase(itr);
11509 break;
11512 if(item && duration > 0 )
11514 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11515 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11519 void Player::ApplyEnchantment(Item *item,bool apply)
11521 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11522 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11525 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11527 if(!item)
11528 return;
11530 if(!item->IsEquipped())
11531 return;
11533 if(slot >= MAX_ENCHANTMENT_SLOT)
11534 return;
11536 uint32 enchant_id = item->GetEnchantmentId(slot);
11537 if(!enchant_id)
11538 return;
11540 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11541 if(!pEnchant)
11542 return;
11544 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11545 return;
11547 if (!item->IsBroken())
11549 for (int s = 0; s < 3; ++s)
11551 uint32 enchant_display_type = pEnchant->type[s];
11552 uint32 enchant_amount = pEnchant->amount[s];
11553 uint32 enchant_spell_id = pEnchant->spellid[s];
11555 switch(enchant_display_type)
11557 case ITEM_ENCHANTMENT_TYPE_NONE:
11558 break;
11559 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11560 // processed in Player::CastItemCombatSpell
11561 break;
11562 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11563 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11564 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11565 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11566 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11567 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11568 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11569 break;
11570 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11571 if(enchant_spell_id)
11573 if(apply)
11575 int32 basepoints = 0;
11576 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11577 if (item->GetItemRandomPropertyId())
11579 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11580 if (item_rand)
11582 // Search enchant_amount
11583 for (int k = 0; k < 3; ++k)
11585 if(item_rand->enchant_id[k] == enchant_id)
11587 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11588 break;
11593 // Cast custom spell vs all equal basepoints getted from enchant_amount
11594 if (basepoints)
11595 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11596 else
11597 CastSpell(this, enchant_spell_id, true, item);
11599 else
11600 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11602 break;
11603 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11604 if (!enchant_amount)
11606 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11607 if(item_rand)
11609 for (int k = 0; k < 3; ++k)
11611 if(item_rand->enchant_id[k] == enchant_id)
11613 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11614 break;
11620 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11621 break;
11622 case ITEM_ENCHANTMENT_TYPE_STAT:
11624 if (!enchant_amount)
11626 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11627 if(item_rand_suffix)
11629 for (int k = 0; k < 3; ++k)
11631 if(item_rand_suffix->enchant_id[k] == enchant_id)
11633 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11634 break;
11640 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11641 switch (enchant_spell_id)
11643 case ITEM_MOD_MANA:
11644 sLog.outDebug("+ %u MANA",enchant_amount);
11645 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
11646 break;
11647 case ITEM_MOD_HEALTH:
11648 sLog.outDebug("+ %u HEALTH",enchant_amount);
11649 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
11650 break;
11651 case ITEM_MOD_AGILITY:
11652 sLog.outDebug("+ %u AGILITY",enchant_amount);
11653 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11654 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11655 break;
11656 case ITEM_MOD_STRENGTH:
11657 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11658 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11659 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11660 break;
11661 case ITEM_MOD_INTELLECT:
11662 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11663 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11664 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11665 break;
11666 case ITEM_MOD_SPIRIT:
11667 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11668 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11669 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11670 break;
11671 case ITEM_MOD_STAMINA:
11672 sLog.outDebug("+ %u STAMINA",enchant_amount);
11673 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11674 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11675 break;
11676 case ITEM_MOD_DEFENSE_SKILL_RATING:
11677 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11678 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11679 break;
11680 case ITEM_MOD_DODGE_RATING:
11681 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11682 sLog.outDebug("+ %u DODGE", enchant_amount);
11683 break;
11684 case ITEM_MOD_PARRY_RATING:
11685 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11686 sLog.outDebug("+ %u PARRY", enchant_amount);
11687 break;
11688 case ITEM_MOD_BLOCK_RATING:
11689 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11690 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11691 break;
11692 case ITEM_MOD_HIT_MELEE_RATING:
11693 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11694 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11695 break;
11696 case ITEM_MOD_HIT_RANGED_RATING:
11697 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11698 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11699 break;
11700 case ITEM_MOD_HIT_SPELL_RATING:
11701 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11702 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11703 break;
11704 case ITEM_MOD_CRIT_MELEE_RATING:
11705 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11706 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11707 break;
11708 case ITEM_MOD_CRIT_RANGED_RATING:
11709 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11710 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11711 break;
11712 case ITEM_MOD_CRIT_SPELL_RATING:
11713 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11714 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11715 break;
11716 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11717 // in Enchantments
11718 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11719 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11720 // break;
11721 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11722 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11723 // break;
11724 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11725 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11726 // break;
11727 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11728 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11729 // break;
11730 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11731 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11732 // break;
11733 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11734 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11735 // break;
11736 // case ITEM_MOD_HASTE_MELEE_RATING:
11737 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11738 // break;
11739 // case ITEM_MOD_HASTE_RANGED_RATING:
11740 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11741 // break;
11742 case ITEM_MOD_HASTE_SPELL_RATING:
11743 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11744 break;
11745 case ITEM_MOD_HIT_RATING:
11746 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11747 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11748 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11749 sLog.outDebug("+ %u HIT", enchant_amount);
11750 break;
11751 case ITEM_MOD_CRIT_RATING:
11752 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11753 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11754 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11755 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11756 break;
11757 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11758 // case ITEM_MOD_HIT_TAKEN_RATING:
11759 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11760 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11761 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11762 // break;
11763 // case ITEM_MOD_CRIT_TAKEN_RATING:
11764 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11765 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11766 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11767 // break;
11768 case ITEM_MOD_RESILIENCE_RATING:
11769 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11770 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11771 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11772 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11773 break;
11774 case ITEM_MOD_HASTE_RATING:
11775 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11776 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11777 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11778 sLog.outDebug("+ %u HASTE", enchant_amount);
11779 break;
11780 case ITEM_MOD_EXPERTISE_RATING:
11781 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11782 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11783 break;
11784 case ITEM_MOD_ATTACK_POWER:
11785 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11786 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11787 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11788 break;
11789 case ITEM_MOD_RANGED_ATTACK_POWER:
11790 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11791 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11792 break;
11793 case ITEM_MOD_FERAL_ATTACK_POWER:
11794 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11795 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11796 break;
11797 case ITEM_MOD_SPELL_HEALING_DONE:
11798 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11799 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
11800 break;
11801 case ITEM_MOD_SPELL_DAMAGE_DONE:
11802 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11803 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
11804 break;
11805 case ITEM_MOD_MANA_REGENERATION:
11806 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
11807 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
11808 break;
11809 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11810 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11811 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11812 break;
11813 case ITEM_MOD_SPELL_POWER:
11814 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11815 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11816 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
11817 break;
11818 default:
11819 break;
11821 break;
11823 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11825 if(getClass() == CLASS_SHAMAN)
11827 float addValue = 0.0f;
11828 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11830 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11831 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11833 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11835 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11836 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11839 break;
11841 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
11842 // processed in Player::CastItemUseSpell
11843 break;
11844 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
11845 // nothing do..
11846 break;
11847 default:
11848 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
11849 break;
11850 } /*switch(enchant_display_type)*/
11851 } /*for*/
11854 // visualize enchantment at player and equipped items
11855 if(slot == PERM_ENCHANTMENT_SLOT)
11856 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
11858 if(slot == TEMP_ENCHANTMENT_SLOT)
11859 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
11862 if(apply_dur)
11864 if(apply)
11866 // set duration
11867 uint32 duration = item->GetEnchantmentDuration(slot);
11868 if(duration > 0)
11869 AddEnchantmentDuration(item, slot, duration);
11871 else
11873 // duration == 0 will remove EnchantDuration
11874 AddEnchantmentDuration(item, slot, 0);
11879 void Player::SendEnchantmentDurations()
11881 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11883 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
11887 void Player::SendItemDurations()
11889 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
11891 (*itr)->SendTimeUpdate(this);
11895 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11897 if(!item) // prevent crash
11898 return;
11900 // last check 2.0.10
11901 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11902 data << uint64(GetGUID()); // player GUID
11903 data << uint32(received); // 0=looted, 1=from npc
11904 data << uint32(created); // 0=received, 1=created
11905 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11906 data << uint8(item->GetBagSlot()); // bagslot
11907 // item slot, but when added to stack: 0xFFFFFFFF
11908 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
11909 data << uint32(item->GetEntry()); // item id
11910 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11911 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11912 data << uint32(count); // count of items
11913 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
11915 if (broadcast && GetGroup())
11916 GetGroup()->BroadcastPacket(&data, true);
11917 else
11918 GetSession()->SendPacket(&data);
11921 /*********************************************************/
11922 /*** QUEST SYSTEM ***/
11923 /*********************************************************/
11925 void Player::PrepareQuestMenu( uint64 guid )
11927 Object *pObject;
11928 QuestRelations* pObjectQR;
11929 QuestRelations* pObjectQIR;
11931 // pets also can have quests
11932 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
11933 if( pCreature )
11935 pObject = (Object*)pCreature;
11936 pObjectQR = &objmgr.mCreatureQuestRelations;
11937 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11939 else
11941 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11942 if( pGameObject )
11944 pObject = (Object*)pGameObject;
11945 pObjectQR = &objmgr.mGOQuestRelations;
11946 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11948 else
11949 return;
11952 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11953 qm.ClearMenu();
11955 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11957 uint32 quest_id = i->second;
11958 QuestStatus status = GetQuestStatus( quest_id );
11959 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11960 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11961 else if ( status == QUEST_STATUS_INCOMPLETE )
11962 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11963 else if (status == QUEST_STATUS_AVAILABLE )
11964 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11967 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11969 uint32 quest_id = i->second;
11970 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11971 if(!pQuest) continue;
11973 QuestStatus status = GetQuestStatus( quest_id );
11975 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11976 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11977 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11978 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11982 void Player::SendPreparedQuest( uint64 guid )
11984 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11985 if( questMenu.Empty() )
11986 return;
11988 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11990 uint32 status = qmi0.m_qIcon;
11992 // single element case
11993 if ( questMenu.MenuItemCount() == 1 )
11995 // Auto open -- maybe also should verify there is no greeting
11996 uint32 quest_id = qmi0.m_qId;
11997 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11999 if ( pQuest )
12001 if( status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus( quest_id ) )
12002 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
12003 else if( status == DIALOG_STATUS_UNK2 )
12004 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
12005 // Send completable on repeatable quest if player don't have quest
12006 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
12007 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
12008 else
12009 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
12012 // multiply entries
12013 else
12015 QEmote qe;
12016 qe._Delay = 0;
12017 qe._Emote = 0;
12018 std::string title = "";
12020 // need pet case for some quests
12021 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
12022 if( pCreature )
12024 uint32 textid = pCreature->GetNpcTextId();
12025 GossipText const* gossiptext = objmgr.GetGossipText(textid);
12026 if( !gossiptext )
12028 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12029 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12030 title = "";
12032 else
12034 qe = gossiptext->Options[0].Emotes[0];
12036 if(!gossiptext->Options[0].Text_0.empty())
12038 title = gossiptext->Options[0].Text_0;
12040 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12041 if (loc_idx >= 0)
12043 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12044 if (nl)
12046 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12047 title = nl->Text_0[0][loc_idx];
12051 else
12053 title = gossiptext->Options[0].Text_1;
12055 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12056 if (loc_idx >= 0)
12058 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12059 if (nl)
12061 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12062 title = nl->Text_1[0][loc_idx];
12068 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12072 bool Player::IsActiveQuest( uint32 quest_id ) const
12074 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12076 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12079 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12081 Object *pObject;
12082 QuestRelations* pObjectQR;
12083 QuestRelations* pObjectQIR;
12085 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
12086 if( pCreature )
12088 pObject = (Object*)pCreature;
12089 pObjectQR = &objmgr.mCreatureQuestRelations;
12090 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12092 else
12094 GameObject *pGameObject = GetMap()->GetGameObject(guid);
12095 if( pGameObject )
12097 pObject = (Object*)pGameObject;
12098 pObjectQR = &objmgr.mGOQuestRelations;
12099 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12101 else
12102 return NULL;
12105 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12106 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12108 if (itr->second == nextQuestID)
12109 return objmgr.GetQuestTemplate(nextQuestID);
12112 return NULL;
12115 bool Player::CanSeeStartQuest( Quest const *pQuest )
12117 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12118 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12119 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12120 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12122 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12125 return false;
12128 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12130 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12131 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12132 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12133 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12134 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12135 && SatisfyQuestDay( pQuest, msg );
12138 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12140 if( !SatisfyQuestLog( msg ) )
12141 return false;
12143 uint32 srcitem = pQuest->GetSrcItemId();
12144 if( srcitem > 0 )
12146 uint32 count = pQuest->GetSrcItemCount();
12147 ItemPosCountVec dest;
12148 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12150 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12151 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12152 return true;
12153 else if( msg2 != EQUIP_ERR_OK )
12155 SendEquipError( msg2, NULL, NULL );
12156 return false;
12159 return true;
12162 bool Player::CanCompleteQuest( uint32 quest_id )
12164 if( quest_id )
12166 QuestStatusData& q_status = mQuestStatus[quest_id];
12167 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12168 return false; // not allow re-complete quest
12170 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12172 if(!qInfo)
12173 return false;
12175 // auto complete quest
12176 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12177 return true;
12179 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12182 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12184 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12186 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12187 return false;
12191 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12193 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12195 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12196 continue;
12198 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12199 return false;
12203 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12204 return false;
12206 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12207 return false;
12209 if ( qInfo->GetRewOrReqMoney() < 0 )
12211 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12212 return false;
12215 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12216 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12217 return false;
12219 return true;
12222 return false;
12225 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12227 // Solve problem that player don't have the quest and try complete it.
12228 // if repeatable she must be able to complete event if player don't have it.
12229 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12230 if( !CanTakeQuest(pQuest, false) )
12231 return false;
12233 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12234 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12235 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12236 return false;
12238 if( !CanRewardQuest(pQuest, false) )
12239 return false;
12241 return true;
12244 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12246 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12247 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12248 return false;
12250 // daily quest can't be rewarded (25 daily quest already completed)
12251 if(!SatisfyQuestDay(pQuest,true))
12252 return false;
12254 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12255 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12256 return false;
12258 // prevent receive reward with quest items in bank
12259 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12261 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12263 if( pQuest->ReqItemCount[i]!= 0 &&
12264 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12266 if(msg)
12267 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12268 return false;
12273 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12274 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12275 return false;
12277 return true;
12280 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12282 // prevent receive reward with quest items in bank or for not completed quest
12283 if(!CanRewardQuest(pQuest,msg))
12284 return false;
12286 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12288 if( pQuest->RewChoiceItemId[reward] )
12290 ItemPosCountVec dest;
12291 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12292 if( res != EQUIP_ERR_OK )
12294 SendEquipError( res, NULL, NULL );
12295 return false;
12300 if ( pQuest->GetRewItemsCount() > 0 )
12302 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12304 if( pQuest->RewItemId[i] )
12306 ItemPosCountVec dest;
12307 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12308 if( res != EQUIP_ERR_OK )
12310 SendEquipError( res, NULL, NULL );
12311 return false;
12317 return true;
12320 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12322 uint16 log_slot = FindQuestSlot( 0 );
12323 assert(log_slot < MAX_QUEST_LOG_SIZE);
12325 uint32 quest_id = pQuest->GetQuestId();
12327 // if not exist then created with set uState==NEW and rewarded=false
12328 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12330 // check for repeatable quests status reset
12331 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12332 questStatusData.m_explored = false;
12334 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12336 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12337 questStatusData.m_itemcount[i] = 0;
12340 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12342 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12343 questStatusData.m_creatureOrGOcount[i] = 0;
12346 GiveQuestSourceItem( pQuest );
12347 AdjustQuestReqItemCount( pQuest, questStatusData );
12349 if( pQuest->GetRepObjectiveFaction() )
12350 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12351 GetReputationMgr().SetVisible(factionEntry);
12353 uint32 qtime = 0;
12354 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12356 uint32 limittime = pQuest->GetLimitTime();
12358 // shared timed quest
12359 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12360 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12362 AddTimedQuest( quest_id );
12363 questStatusData.m_timer = limittime * IN_MILISECONDS;
12364 qtime = static_cast<uint32>(time(NULL)) + limittime;
12366 else
12367 questStatusData.m_timer = 0;
12369 SetQuestSlot(log_slot, quest_id, qtime);
12371 if (questStatusData.uState != QUEST_NEW)
12372 questStatusData.uState = QUEST_CHANGED;
12374 //starting initial quest script
12375 if(questGiver && pQuest->GetQuestStartScript()!=0)
12376 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12378 // Some spells applied at quest activation
12379 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12380 if(saBounds.first != saBounds.second)
12382 uint32 zone, area;
12383 GetZoneAndAreaId(zone,area);
12385 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12386 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12387 if( !HasAura(itr->second->spellId,0) )
12388 CastSpell(this,itr->second->spellId,true);
12391 UpdateForQuestWorldObjects();
12394 void Player::CompleteQuest( uint32 quest_id )
12396 if( quest_id )
12398 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12400 uint16 log_slot = FindQuestSlot( quest_id );
12401 if( log_slot < MAX_QUEST_LOG_SIZE)
12402 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12404 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12406 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12407 RewardQuest(qInfo,0,this,false);
12408 else
12409 SendQuestComplete( quest_id );
12414 void Player::IncompleteQuest( uint32 quest_id )
12416 if( quest_id )
12418 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12420 uint16 log_slot = FindQuestSlot( quest_id );
12421 if( log_slot < MAX_QUEST_LOG_SIZE)
12422 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12426 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12428 uint32 quest_id = pQuest->GetQuestId();
12430 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i )
12432 if ( pQuest->ReqItemId[i] )
12433 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12436 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12437 // SetTimedQuest( 0 );
12438 m_timedquests.erase(pQuest->GetQuestId());
12440 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12442 if( pQuest->RewChoiceItemId[reward] )
12444 ItemPosCountVec dest;
12445 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12447 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12448 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12453 if ( pQuest->GetRewItemsCount() > 0 )
12455 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12457 if( pQuest->RewItemId[i] )
12459 ItemPosCountVec dest;
12460 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12462 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12463 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12469 RewardReputation( pQuest );
12471 if( pQuest->GetRewSpellCast() > 0 )
12472 CastSpell( this, pQuest->GetRewSpellCast(), true);
12473 else if( pQuest->GetRewSpell() > 0)
12474 CastSpell( this, pQuest->GetRewSpell(), true);
12476 uint16 log_slot = FindQuestSlot( quest_id );
12477 if( log_slot < MAX_QUEST_LOG_SIZE)
12478 SetQuestSlot(log_slot,0);
12480 QuestStatusData& q_status = mQuestStatus[quest_id];
12482 // Not give XP in case already completed once repeatable quest
12483 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12485 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12486 GiveXP( XP , NULL );
12487 else
12489 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12490 ModifyMoney( money );
12491 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12494 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12495 if(pQuest->GetRewOrReqMoney())
12497 ModifyMoney( pQuest->GetRewOrReqMoney() );
12499 if(pQuest->GetRewOrReqMoney() > 0)
12500 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12503 // honor reward
12504 if(pQuest->GetRewHonorableKills())
12505 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12507 // title reward
12508 if(pQuest->GetCharTitleId())
12510 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12511 SetTitle(titleEntry);
12514 if(pQuest->GetBonusTalents())
12516 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12517 InitTalentForLevel();
12520 // Send reward mail
12521 if(pQuest->GetRewMailTemplateId())
12523 MailMessageType mailType;
12524 uint32 senderGuidOrEntry;
12525 switch(questGiver->GetTypeId())
12527 case TYPEID_UNIT:
12528 mailType = MAIL_CREATURE;
12529 senderGuidOrEntry = questGiver->GetEntry();
12530 break;
12531 case TYPEID_GAMEOBJECT:
12532 mailType = MAIL_GAMEOBJECT;
12533 senderGuidOrEntry = questGiver->GetEntry();
12534 break;
12535 case TYPEID_ITEM:
12536 mailType = MAIL_ITEM;
12537 senderGuidOrEntry = questGiver->GetEntry();
12538 break;
12539 case TYPEID_PLAYER:
12540 mailType = MAIL_NORMAL;
12541 senderGuidOrEntry = questGiver->GetGUIDLow();
12542 break;
12543 default:
12544 mailType = MAIL_NORMAL;
12545 senderGuidOrEntry = GetGUIDLow();
12546 break;
12549 Loot questMailLoot;
12551 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12553 // fill mail
12554 MailItemsInfo mi; // item list preparing
12556 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12557 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12559 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12561 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12563 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12564 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12569 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12572 if(pQuest->IsDaily())
12574 SetDailyQuestStatus(quest_id);
12575 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12578 if ( !pQuest->IsRepeatable() )
12579 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12580 else
12581 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12583 q_status.m_rewarded = true;
12585 if(announce)
12586 SendQuestReward( pQuest, XP, questGiver );
12588 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12589 if (pQuest->GetZoneOrSort() > 0)
12590 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12591 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12592 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
12594 uint32 zone = 0;
12595 uint32 area = 0;
12597 // remove auras from spells with quest reward state limitations
12598 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12599 if(saEndBounds.first != saEndBounds.second)
12601 GetZoneAndAreaId(zone,area);
12603 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12604 if(!itr->second->IsFitToRequirements(this,zone,area))
12605 RemoveAurasDueToSpell(itr->second->spellId);
12608 // Some spells applied at quest reward
12609 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12610 if(saBounds.first != saBounds.second)
12612 if(!zone || !area)
12613 GetZoneAndAreaId(zone,area);
12615 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12616 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12617 if( !HasAura(itr->second->spellId,0) )
12618 CastSpell(this,itr->second->spellId,true);
12622 void Player::FailQuest( uint32 quest_id )
12624 if( quest_id )
12626 IncompleteQuest( quest_id );
12628 uint16 log_slot = FindQuestSlot( quest_id );
12629 if( log_slot < MAX_QUEST_LOG_SIZE)
12631 SetQuestSlotTimer(log_slot, 1 );
12632 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12634 SendQuestFailed( quest_id );
12638 void Player::FailTimedQuest( uint32 quest_id )
12640 if( quest_id )
12642 QuestStatusData& q_status = mQuestStatus[quest_id];
12644 q_status.m_timer = 0;
12645 if (q_status.uState != QUEST_NEW)
12646 q_status.uState = QUEST_CHANGED;
12648 IncompleteQuest( quest_id );
12650 uint16 log_slot = FindQuestSlot( quest_id );
12651 if( log_slot < MAX_QUEST_LOG_SIZE)
12653 SetQuestSlotTimer(log_slot, 1 );
12654 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12656 SendQuestTimerFailed( quest_id );
12660 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12662 int32 zoneOrSort = qInfo->GetZoneOrSort();
12663 int32 skillOrClass = qInfo->GetSkillOrClass();
12665 // skip zone zoneOrSort and 0 case skillOrClass
12666 if( zoneOrSort >= 0 && skillOrClass == 0 )
12667 return true;
12669 int32 questSort = -zoneOrSort;
12670 uint8 reqSortClass = ClassByQuestSort(questSort);
12672 // check class sort cases in zoneOrSort
12673 if( reqSortClass != 0 && getClass() != reqSortClass)
12675 if( msg )
12676 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12677 return false;
12680 // check class
12681 if( skillOrClass < 0 )
12683 uint8 reqClass = -int32(skillOrClass);
12684 if(getClass() != reqClass)
12686 if( msg )
12687 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12688 return false;
12691 // check skill
12692 else if( skillOrClass > 0 )
12694 uint32 reqSkill = skillOrClass;
12695 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12697 if( msg )
12698 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12699 return false;
12703 return true;
12706 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12708 if( getLevel() < qInfo->GetMinLevel() )
12710 if( msg )
12711 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12712 return false;
12714 return true;
12717 bool Player::SatisfyQuestLog( bool msg )
12719 // exist free slot
12720 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12721 return true;
12723 if( msg )
12725 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12726 GetSession()->SendPacket( &data );
12727 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12729 return false;
12732 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12734 // No previous quest (might be first quest in a series)
12735 if( qInfo->prevQuests.empty())
12736 return true;
12738 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12740 uint32 prevId = abs(*iter);
12742 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12743 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12745 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12747 // If any of the positive previous quests completed, return true
12748 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12750 // skip one-from-all exclusive group
12751 if(qPrevInfo->GetExclusiveGroup() >= 0)
12752 return true;
12754 // each-from-all exclusive group ( < 0)
12755 // can be start if only all quests in prev quest exclusive group completed and rewarded
12756 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12757 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12759 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12761 for(; iter2 != end; ++iter2)
12763 uint32 exclude_Id = iter2->second;
12765 // skip checked quest id, only state of other quests in group is interesting
12766 if(exclude_Id == prevId)
12767 continue;
12769 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12771 // alternative quest from group also must be completed and rewarded(reported)
12772 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12774 if( msg )
12775 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12776 return false;
12779 return true;
12781 // If any of the negative previous quests active, return true
12782 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12783 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12785 // skip one-from-all exclusive group
12786 if(qPrevInfo->GetExclusiveGroup() >= 0)
12787 return true;
12789 // each-from-all exclusive group ( < 0)
12790 // can be start if only all quests in prev quest exclusive group active
12791 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12792 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12794 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12796 for(; iter2 != end; ++iter2)
12798 uint32 exclude_Id = iter2->second;
12800 // skip checked quest id, only state of other quests in group is interesting
12801 if(exclude_Id == prevId)
12802 continue;
12804 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12806 // alternative quest from group also must be active
12807 if( i_exstatus == mQuestStatus.end() ||
12808 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12809 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12811 if( msg )
12812 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12813 return false;
12816 return true;
12821 // Has only positive prev. quests in non-rewarded state
12822 // and negative prev. quests in non-active state
12823 if( msg )
12824 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12826 return false;
12829 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12831 uint32 reqraces = qInfo->GetRequiredRaces();
12832 if ( reqraces == 0 )
12833 return true;
12834 if( (reqraces & getRaceMask()) == 0 )
12836 if( msg )
12837 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12838 return false;
12840 return true;
12843 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12845 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12846 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12848 if( msg )
12849 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12850 return false;
12853 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12854 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12856 if( msg )
12857 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12858 return false;
12861 return true;
12864 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12866 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12867 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12869 if( msg )
12870 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12871 return false;
12873 return true;
12876 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12878 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12880 if( msg )
12881 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12882 return false;
12884 return true;
12887 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12889 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12890 if(qInfo->GetExclusiveGroup() <= 0)
12891 return true;
12893 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12894 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12896 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12898 for(; iter != end; ++iter)
12900 uint32 exclude_Id = iter->second;
12902 // skip checked quest id, only state of other quests in group is interesting
12903 if(exclude_Id == qInfo->GetQuestId())
12904 continue;
12906 // not allow have daily quest if daily quest from exclusive group already recently completed
12907 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12908 if( !SatisfyQuestDay(Nquest, false) )
12910 if( msg )
12911 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12912 return false;
12915 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12917 // alternative quest already started or completed
12918 if( i_exstatus != mQuestStatus.end()
12919 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12921 if( msg )
12922 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12923 return false;
12926 return true;
12929 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12931 if(!qInfo->GetNextQuestInChain())
12932 return true;
12934 // next quest in chain already started or completed
12935 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12936 if( itr != mQuestStatus.end()
12937 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12939 if( msg )
12940 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12941 return false;
12944 // check for all quests further up the chain
12945 // only necessary if there are quest chains with more than one quest that can be skipped
12946 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12947 return true;
12950 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12952 // No previous quest in chain
12953 if( qInfo->prevChainQuests.empty())
12954 return true;
12956 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12958 uint32 prevId = *iter;
12960 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12962 if( i_prevstatus != mQuestStatus.end() )
12964 // If any of the previous quests in chain active, return false
12965 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12966 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12968 if( msg )
12969 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12970 return false;
12974 // check for all quests further down the chain
12975 // only necessary if there are quest chains with more than one quest that can be skipped
12976 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12977 // return false;
12980 // No previous quest in chain active
12981 return true;
12984 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12986 if(!qInfo->IsDaily())
12987 return true;
12989 bool have_slot = false;
12990 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12992 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12993 if(qInfo->GetQuestId()==id)
12994 return false;
12996 if(!id)
12997 have_slot = true;
13000 if(!have_slot)
13002 if( msg )
13003 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13004 return false;
13007 return true;
13010 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13012 uint32 srcitem = pQuest->GetSrcItemId();
13013 if( srcitem > 0 )
13015 uint32 count = pQuest->GetSrcItemCount();
13016 if( count <= 0 )
13017 count = 1;
13019 ItemPosCountVec dest;
13020 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13021 if( msg == EQUIP_ERR_OK )
13023 Item * item = StoreNewItem(dest, srcitem, true);
13024 SendNewItem(item, count, true, false);
13025 return true;
13027 // player already have max amount required item, just report success
13028 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13029 return true;
13030 else
13031 SendEquipError( msg, NULL, NULL );
13032 return false;
13035 return true;
13038 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13040 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13041 if( qInfo )
13043 uint32 srcitem = qInfo->GetSrcItemId();
13044 if( srcitem > 0 )
13046 uint32 count = qInfo->GetSrcItemCount();
13047 if( count <= 0 )
13048 count = 1;
13050 // exist one case when destroy source quest item not possible:
13051 // non un-equippable item (equipped non-empty bag, for example)
13052 uint8 res = CanUnequipItems(srcitem,count);
13053 if(res != EQUIP_ERR_OK)
13055 if(msg)
13056 SendEquipError( res, NULL, NULL );
13057 return false;
13060 DestroyItemCount(srcitem, count, true, true);
13063 return true;
13066 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13068 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13069 if( qInfo )
13071 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13072 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13073 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13074 && !qInfo->IsRepeatable() )
13075 return itr->second.m_rewarded;
13077 return false;
13079 return false;
13082 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13084 if( quest_id )
13086 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13087 if( itr != mQuestStatus.end() )
13088 return itr->second.m_status;
13090 return QUEST_STATUS_NONE;
13093 bool Player::CanShareQuest(uint32 quest_id) const
13095 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13096 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13098 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13099 if( itr != mQuestStatus.end() )
13100 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13102 return false;
13105 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13107 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13108 if( qInfo )
13110 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13112 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13113 m_timedquests.erase(qInfo->GetQuestId());
13116 QuestStatusData& q_status = mQuestStatus[quest_id];
13118 q_status.m_status = status;
13119 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13122 UpdateForQuestWorldObjects();
13125 // not used in MaNGOS, but used in scripting code
13126 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13128 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13129 if( !qInfo )
13130 return 0;
13132 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13133 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13134 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13136 return 0;
13139 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13141 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13143 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13145 uint32 reqitemcount = pQuest->ReqItemCount[i];
13146 if( reqitemcount != 0 )
13148 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13150 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13151 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13157 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13159 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13160 if ( GetQuestSlotQuestId(i) == quest_id )
13161 return i;
13163 return MAX_QUEST_LOG_SIZE;
13166 void Player::AreaExploredOrEventHappens( uint32 questId )
13168 if( questId )
13170 uint16 log_slot = FindQuestSlot( questId );
13171 if( log_slot < MAX_QUEST_LOG_SIZE)
13173 QuestStatusData& q_status = mQuestStatus[questId];
13175 if(!q_status.m_explored)
13177 q_status.m_explored = true;
13178 if (q_status.uState != QUEST_NEW)
13179 q_status.uState = QUEST_CHANGED;
13182 if( CanCompleteQuest( questId ) )
13183 CompleteQuest( questId );
13187 //not used in mangosd, function for external script library
13188 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13190 if( Group *pGroup = GetGroup() )
13192 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13194 Player *pGroupGuy = itr->getSource();
13196 // for any leave or dead (with not released body) group member at appropriate distance
13197 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13198 pGroupGuy->AreaExploredOrEventHappens(questId);
13201 else
13202 AreaExploredOrEventHappens(questId);
13205 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13207 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13209 uint32 questid = GetQuestSlotQuestId(i);
13210 if ( questid == 0 )
13211 continue;
13213 QuestStatusData& q_status = mQuestStatus[questid];
13215 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13216 continue;
13218 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13219 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13220 continue;
13222 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13224 uint32 reqitem = qInfo->ReqItemId[j];
13225 if ( reqitem == entry )
13227 uint32 reqitemcount = qInfo->ReqItemCount[j];
13228 uint32 curitemcount = q_status.m_itemcount[j];
13229 if ( curitemcount < reqitemcount )
13231 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13232 q_status.m_itemcount[j] += additemcount;
13233 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13235 SendQuestUpdateAddItem( qInfo, j, additemcount );
13237 if ( CanCompleteQuest( questid ) )
13238 CompleteQuest( questid );
13239 return;
13243 UpdateForQuestWorldObjects();
13246 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13248 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13250 uint32 questid = GetQuestSlotQuestId(i);
13251 if(!questid)
13252 continue;
13253 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13254 if ( !qInfo )
13255 continue;
13256 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13257 continue;
13259 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13261 uint32 reqitem = qInfo->ReqItemId[j];
13262 if ( reqitem == entry )
13264 QuestStatusData& q_status = mQuestStatus[questid];
13266 uint32 reqitemcount = qInfo->ReqItemCount[j];
13267 uint32 curitemcount;
13268 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13269 curitemcount = q_status.m_itemcount[j];
13270 else
13271 curitemcount = GetItemCount(entry,true);
13272 if ( curitemcount < reqitemcount + count )
13274 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13275 q_status.m_itemcount[j] = curitemcount - remitemcount;
13276 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13278 IncompleteQuest( questid );
13280 return;
13284 UpdateForQuestWorldObjects();
13287 void Player::KilledMonster( uint32 entry, uint64 guid )
13289 uint32 addkillcount = 1;
13290 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13291 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13293 uint32 questid = GetQuestSlotQuestId(i);
13294 if(!questid)
13295 continue;
13297 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13298 if( !qInfo )
13299 continue;
13300 // just if !ingroup || !noraidgroup || raidgroup
13301 QuestStatusData& q_status = mQuestStatus[questid];
13302 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13304 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13306 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13308 // skip GO activate objective or none
13309 if(qInfo->ReqCreatureOrGOId[j] <=0)
13310 continue;
13312 // skip Cast at creature objective
13313 if(qInfo->ReqSpell[j] !=0 )
13314 continue;
13316 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13318 if ( reqkill == entry )
13320 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13321 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13322 if ( curkillcount < reqkillcount )
13324 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13325 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13327 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13329 if ( CanCompleteQuest( questid ) )
13330 CompleteQuest( questid );
13332 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13333 continue;
13341 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13343 bool isCreature = IS_CREATURE_GUID(guid);
13345 uint32 addCastCount = 1;
13346 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13348 uint32 questid = GetQuestSlotQuestId(i);
13349 if(!questid)
13350 continue;
13352 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13353 if ( !qInfo )
13354 continue;
13356 QuestStatusData& q_status = mQuestStatus[questid];
13358 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13360 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13362 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13364 // skip kill creature objective (0) or wrong spell casts
13365 if(qInfo->ReqSpell[j] != spell_id )
13366 continue;
13368 uint32 reqTarget = 0;
13370 if(isCreature)
13372 // creature activate objectives
13373 if(qInfo->ReqCreatureOrGOId[j] > 0)
13374 // checked at quest_template loading
13375 reqTarget = qInfo->ReqCreatureOrGOId[j];
13377 else
13379 // GO activate objective
13380 if(qInfo->ReqCreatureOrGOId[j] < 0)
13381 // checked at quest_template loading
13382 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13385 // other not this creature/GO related objectives
13386 if( reqTarget != entry )
13387 continue;
13389 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13390 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13391 if ( curCastCount < reqCastCount )
13393 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13394 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13396 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13399 if ( CanCompleteQuest( questid ) )
13400 CompleteQuest( questid );
13402 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13403 break;
13410 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13412 uint32 addTalkCount = 1;
13413 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13415 uint32 questid = GetQuestSlotQuestId(i);
13416 if(!questid)
13417 continue;
13419 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13420 if ( !qInfo )
13421 continue;
13423 QuestStatusData& q_status = mQuestStatus[questid];
13425 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13427 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13429 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13431 // skip spell casts and Gameobject objectives
13432 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13433 continue;
13435 uint32 reqTarget = 0;
13437 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13438 // checked at quest_template loading
13439 reqTarget = qInfo->ReqCreatureOrGOId[j];
13440 else
13441 continue;
13443 if ( reqTarget == entry )
13445 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13446 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13447 if ( curTalkCount < reqTalkCount )
13449 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13450 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13452 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13454 if ( CanCompleteQuest( questid ) )
13455 CompleteQuest( questid );
13457 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13458 continue;
13466 void Player::MoneyChanged( uint32 count )
13468 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13470 uint32 questid = GetQuestSlotQuestId(i);
13471 if (!questid)
13472 continue;
13474 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13475 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13477 QuestStatusData& q_status = mQuestStatus[questid];
13479 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13481 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13483 if ( CanCompleteQuest( questid ) )
13484 CompleteQuest( questid );
13487 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13489 if(int32(count) < -qInfo->GetRewOrReqMoney())
13490 IncompleteQuest( questid );
13496 void Player::ReputationChanged(FactionEntry const* factionEntry )
13498 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13500 if(uint32 questid = GetQuestSlotQuestId(i))
13502 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13504 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13506 QuestStatusData& q_status = mQuestStatus[questid];
13507 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13509 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13510 if ( CanCompleteQuest( questid ) )
13511 CompleteQuest( questid );
13513 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13515 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13516 IncompleteQuest( questid );
13524 bool Player::HasQuestForItem( uint32 itemid ) const
13526 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13528 uint32 questid = GetQuestSlotQuestId(i);
13529 if ( questid == 0 )
13530 continue;
13532 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13533 if(qs_itr == mQuestStatus.end())
13534 continue;
13536 QuestStatusData const& q_status = qs_itr->second;
13538 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13540 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13541 if(!qinfo)
13542 continue;
13544 // hide quest if player is in raid-group and quest is no raid quest
13545 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13546 continue;
13548 // There should be no mixed ReqItem/ReqSource drop
13549 // This part for ReqItem drop
13550 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13552 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13553 return true;
13555 // This part - for ReqSource
13556 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
13558 // examined item is a source item
13559 if (qinfo->ReqSourceId[j] == itemid)
13561 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13563 // 'unique' item
13564 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13565 return true;
13567 // allows custom amount drop when not 0
13568 if (qinfo->ReqSourceCount[j])
13570 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13571 return true;
13572 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13573 return true;
13578 return false;
13581 void Player::SendQuestComplete( uint32 quest_id )
13583 if( quest_id )
13585 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13586 data << uint32(quest_id);
13587 GetSession()->SendPacket( &data );
13588 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13592 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13594 uint32 questid = pQuest->GetQuestId();
13595 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13596 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13597 data << uint32(questid);
13599 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13601 data << uint32(XP);
13602 data << uint32(pQuest->GetRewOrReqMoney());
13604 else
13606 data << uint32(0);
13607 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13610 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13611 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13612 GetSession()->SendPacket( &data );
13614 if (pQuest->GetQuestCompleteScript() != 0)
13615 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13618 void Player::SendQuestFailed( uint32 quest_id )
13620 if( quest_id )
13622 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13623 data << quest_id;
13624 data << uint32(0); // failed reason (4 for inventory is full)
13625 GetSession()->SendPacket( &data );
13626 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13630 void Player::SendQuestTimerFailed( uint32 quest_id )
13632 if( quest_id )
13634 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13635 data << quest_id;
13636 GetSession()->SendPacket( &data );
13637 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13641 void Player::SendCanTakeQuestResponse( uint32 msg )
13643 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13644 data << uint32(msg);
13645 GetSession()->SendPacket( &data );
13646 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13649 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13651 if( pPlayer )
13653 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13654 data << uint64(pPlayer->GetGUID());
13655 data << uint8(msg); // valid values: 0-8
13656 GetSession()->SendPacket( &data );
13657 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13661 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13663 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13664 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13665 //data << pQuest->ReqItemId[item_idx];
13666 //data << count;
13667 GetSession()->SendPacket( &data );
13670 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13672 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13674 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13675 if (entry < 0)
13676 // client expected gameobject template id in form (id|0x80000000)
13677 entry = (-entry) | 0x80000000;
13679 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13680 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13681 data << uint32(pQuest->GetQuestId());
13682 data << uint32(entry);
13683 data << uint32(old_count + add_count);
13684 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13685 data << uint64(guid);
13686 GetSession()->SendPacket(&data);
13688 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13689 if( log_slot < MAX_QUEST_LOG_SIZE)
13690 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13693 /*********************************************************/
13694 /*** LOAD SYSTEM ***/
13695 /*********************************************************/
13697 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13699 bool delete_result = true;
13700 if (!result)
13702 // 0 1 2 3 4 5 6 7 8 9 10
13703 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login, zone FROM characters WHERE guid = '%u'",guid);
13704 if (!result)
13705 return false;
13707 else
13708 delete_result = false;
13710 Field *fields = result->Fetch();
13712 if (!LoadValues( fields[1].GetString()))
13714 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13715 if (delete_result)
13716 delete result;
13717 return false;
13720 // overwrite possible wrong/corrupted guid
13721 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13723 m_name = fields[2].GetCppString();
13725 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13726 SetMapId(fields[6].GetUInt32());
13727 // the instance id is not needed at character enum
13729 m_Played_time[0] = fields[7].GetUInt32();
13730 m_Played_time[1] = fields[8].GetUInt32();
13732 m_atLoginFlags = fields[9].GetUInt32();
13734 // I don't see these used anywhere ..
13735 /*_LoadGroup();
13737 _LoadBoundInstances();*/
13739 if (delete_result)
13740 delete result;
13742 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
13743 m_items[i] = NULL;
13745 if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
13746 m_deathState = DEAD;
13748 return true;
13751 void Player::_LoadDeclinedNames(QueryResult* result)
13753 if(!result)
13754 return;
13756 if(m_declinedname)
13757 delete m_declinedname;
13759 m_declinedname = new DeclinedName;
13760 Field *fields = result->Fetch();
13761 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13762 m_declinedname->name[i] = fields[i].GetCppString();
13764 delete result;
13767 void Player::_LoadArenaTeamInfo(QueryResult *result)
13769 // arenateamid, played_week, played_season, personal_rating
13770 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13771 if (!result)
13772 return;
13776 Field *fields = result->Fetch();
13778 uint32 arenateamid = fields[0].GetUInt32();
13779 uint32 played_week = fields[1].GetUInt32();
13780 uint32 played_season = fields[2].GetUInt32();
13781 uint32 personal_rating = fields[3].GetUInt32();
13783 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13784 if(!aTeam)
13786 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13787 continue;
13789 uint8 arenaSlot = aTeam->GetSlot();
13791 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13792 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13793 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13794 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13795 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13796 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13798 }while (result->NextRow());
13799 delete result;
13802 void Player::_LoadEquipmentSets(QueryResult *result)
13804 // SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
13805 if (!result)
13806 return;
13808 uint32 count = 0;
13811 Field *fields = result->Fetch();
13813 EquipmentSet eqSet;
13815 eqSet.Guid = fields[0].GetUInt64();
13816 uint32 index = fields[1].GetUInt32();
13817 eqSet.Name = fields[2].GetCppString();
13818 eqSet.IconName = fields[3].GetCppString();
13819 eqSet.state = EQUIPMENT_SET_UNCHANGED;
13821 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
13822 eqSet.Items[i] = fields[4+i].GetUInt32();
13824 m_EquipmentSets[index] = eqSet;
13826 ++count;
13828 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
13829 break;
13830 } while (result->NextRow());
13831 delete result;
13834 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13836 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13837 if(!result)
13838 return false;
13840 Field *fields = result->Fetch();
13842 x = fields[0].GetFloat();
13843 y = fields[1].GetFloat();
13844 z = fields[2].GetFloat();
13845 o = fields[3].GetFloat();
13846 mapid = fields[4].GetUInt32();
13847 in_flight = !fields[5].GetCppString().empty();
13849 delete result;
13850 return true;
13853 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13855 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13856 if( !result )
13857 return false;
13859 Field *fields = result->Fetch();
13861 data = StrSplit(fields[0].GetCppString(), " ");
13863 delete result;
13865 return true;
13868 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13870 if(index >= data.size())
13871 return 0;
13873 return (uint32)atoi(data[index].c_str());
13876 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13878 float result;
13879 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13880 memcpy(&result, &temp, sizeof(result));
13882 return result;
13885 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13887 Tokens data;
13888 if(!LoadValuesArrayFromDB(data,guid))
13889 return 0;
13891 return GetUInt32ValueFromArray(data,index);
13894 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13896 float result;
13897 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13898 memcpy(&result, &temp, sizeof(result));
13900 return result;
13903 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13905 //// 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
13906 //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);
13907 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13909 if(!result)
13911 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13912 return false;
13915 Field *fields = result->Fetch();
13917 uint32 dbAccountId = fields[1].GetUInt32();
13919 // check if the character's account in the db and the logged in account match.
13920 // player should be able to load/delete character only with correct account!
13921 if( dbAccountId != GetSession()->GetAccountId() )
13923 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13924 delete result;
13925 return false;
13928 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13930 m_name = fields[3].GetCppString();
13932 // check name limitations
13933 if(!ObjectMgr::IsValidName(m_name) || (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name)))
13935 delete result;
13936 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13937 return false;
13940 if(!LoadValues( fields[2].GetString()))
13942 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
13943 delete result;
13944 return false;
13947 // overwrite possible wrong/corrupted guid
13948 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13950 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13951 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13953 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
13954 SetVisibleItemSlot(slot, NULL);
13956 if (m_items[slot])
13958 delete m_items[slot];
13959 m_items[slot] = NULL;
13963 // update money limits
13964 if(GetMoney() > MAX_MONEY_AMOUNT)
13965 SetMoney(MAX_MONEY_AMOUNT);
13967 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13968 outDebugValues();
13970 m_race = fields[4].GetUInt8();
13971 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13972 //Other way is to saves m_team into characters table.
13973 setFactionForRace(m_race);
13974 SetCharm(NULL);
13976 m_class = fields[5].GetUInt8();
13978 // load home bind and check in same time class/race pair, it used later for restore broken positions
13979 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13981 delete result;
13982 return false;
13985 InitPrimaryProfessions(); // to max set before any spell loaded
13987 // init saved position, and fix it later if problematic
13988 uint32 transGUID = fields[24].GetUInt32();
13989 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13990 SetMapId(fields[9].GetUInt32());
13991 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13993 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13995 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
13997 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
13998 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
13999 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14001 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14003 // check arena teams integrity
14004 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14006 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14007 if(!arena_team_id)
14008 continue;
14010 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
14011 if(at->HaveMember(GetGUID()))
14012 continue;
14014 // arena team not exist or not member, cleanup fields
14015 for(int j =0; j < 6; ++j)
14016 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
14019 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14021 if(!IsPositionValid())
14023 sLog.outError("Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
14024 RelocateToHomebind();
14026 transGUID = 0;
14028 m_movementInfo.t_x = 0.0f;
14029 m_movementInfo.t_y = 0.0f;
14030 m_movementInfo.t_z = 0.0f;
14031 m_movementInfo.t_o = 0.0f;
14034 uint32 bgid = fields[34].GetUInt32();
14035 uint32 bgteam = fields[35].GetUInt32();
14037 if(bgid) //saved in BattleGround
14039 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14041 // check entry point and fix to homebind if need
14042 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
14043 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
14044 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
14046 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid, BATTLEGROUND_TYPE_NONE);
14048 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14050 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14051 AddBattleGroundQueueId(bgQueueTypeId);
14053 SetBattleGroundId(currentBg->GetInstanceID(), currentBg->GetTypeID());
14054 SetBGTeam(bgteam);
14056 //join player to battleground group
14057 currentBg->EventPlayerLoggedIn(this, GetGUID());
14058 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
14060 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14062 else
14064 Relocate(GetBattleGroundEntryPoint());
14065 //RemoveArenaAuras(true);
14068 else
14070 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14071 // if server restart after player save in BG or area
14072 // player can have current coordinates in to BG/Arean map, fix this
14073 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14075 // return to BG master
14076 SetMapId(fields[36].GetUInt32());
14077 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14079 // check entry point and fix to homebind if need
14080 mapEntry = sMapStore.LookupEntry(GetMapId());
14081 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
14082 RelocateToHomebind();
14086 if (transGUID != 0)
14088 m_movementInfo.t_x = fields[20].GetFloat();
14089 m_movementInfo.t_y = fields[21].GetFloat();
14090 m_movementInfo.t_z = fields[22].GetFloat();
14091 m_movementInfo.t_o = fields[23].GetFloat();
14093 if( !MaNGOS::IsValidMapCoord(
14094 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14095 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14096 // transport size limited
14097 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14099 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14100 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14101 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14103 RelocateToHomebind();
14105 m_movementInfo.t_x = 0.0f;
14106 m_movementInfo.t_y = 0.0f;
14107 m_movementInfo.t_z = 0.0f;
14108 m_movementInfo.t_o = 0.0f;
14110 transGUID = 0;
14114 if (transGUID != 0)
14116 for (MapManager::TransportSet::const_iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14118 if( (*iter)->GetGUIDLow() == transGUID)
14120 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14121 // client without expansion support
14122 if(GetSession()->Expansion() < transMapEntry->Expansion())
14124 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14125 break;
14128 m_transport = *iter;
14129 m_transport->AddPassenger(this);
14130 SetMapId(m_transport->GetMapId());
14131 break;
14135 if(!m_transport)
14137 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14138 guid,transGUID);
14140 RelocateToHomebind();
14142 m_movementInfo.t_x = 0.0f;
14143 m_movementInfo.t_y = 0.0f;
14144 m_movementInfo.t_z = 0.0f;
14145 m_movementInfo.t_o = 0.0f;
14147 transGUID = 0;
14150 else // not transport case
14152 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14153 // client without expansion support
14154 if(GetSession()->Expansion() < mapEntry->Expansion())
14156 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14157 RelocateToHomebind();
14161 // NOW player must have valid map
14162 // load the player's map here if it's not already loaded
14163 Map *map = GetMap();
14165 // since the player may not be bound to the map yet, make sure subsequent
14166 // getmap calls won't create new maps
14167 SetInstanceId(map->GetInstanceId());
14169 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14170 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14172 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14173 if(at)
14174 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14175 else
14176 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());
14179 SaveRecallPosition();
14181 time_t now = time(NULL);
14182 time_t logoutTime = time_t(fields[16].GetUInt64());
14184 // since last logout (in seconds)
14185 uint64 time_diff = uint64(now - logoutTime);
14187 // set value, including drunk invisibility detection
14188 // calculate sobering. after 15 minutes logged out, the player will be sober again
14189 float soberFactor;
14190 if(time_diff > 15*MINUTE)
14191 soberFactor = 0;
14192 else
14193 soberFactor = 1-time_diff/(15.0f*MINUTE);
14194 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14195 SetDrunkValue(newDrunkenValue);
14197 m_rest_bonus = fields[15].GetFloat();
14198 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14199 float bubble0 = 0.031;
14200 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14201 float bubble1 = 0.125;
14203 if((int32)fields[16].GetUInt32() > 0)
14205 float bubble = fields[17].GetUInt32() > 0
14206 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14207 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14209 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14212 m_cinematic = fields[12].GetUInt32();
14213 m_Played_time[0]= fields[13].GetUInt32();
14214 m_Played_time[1]= fields[14].GetUInt32();
14216 m_resetTalentsCost = fields[18].GetUInt32();
14217 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14219 // reserve some flags
14220 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14222 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14223 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14225 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14227 uint32 extraflags = fields[25].GetUInt32();
14229 m_stableSlots = fields[26].GetUInt32();
14230 if(m_stableSlots > MAX_PET_STABLES)
14232 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14233 m_stableSlots = MAX_PET_STABLES;
14236 m_atLoginFlags = fields[27].GetUInt32();
14238 // Honor system
14239 // Update Honor kills data
14240 m_lastHonorUpdateTime = logoutTime;
14241 UpdateHonorFields();
14243 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14244 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14245 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14247 std::string taxi_nodes = fields[31].GetCppString();
14249 delete result;
14251 // clear channel spell data (if saved at channel spell casting)
14252 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14253 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14255 // clear charm/summon related fields
14256 SetCharm(NULL);
14257 SetPet(NULL);
14258 SetCharmerGUID(0);
14259 SetOwnerGUID(0);
14260 SetCreatorGUID(0);
14262 // reset some aura modifiers before aura apply
14263 SetFarSightGUID(0);
14264 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14265 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14267 _LoadSkills();
14269 // make sure the unit is considered out of combat for proper loading
14270 ClearInCombat();
14272 // make sure the unit is considered not in duel for proper loading
14273 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14274 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14276 // remember loaded power/health values to restore after stats initialization and modifier applying
14277 uint32 savedHealth = GetHealth();
14278 uint32 savedPower[MAX_POWERS];
14279 for(uint32 i = 0; i < MAX_POWERS; ++i)
14280 savedPower[i] = GetPower(Powers(i));
14282 // reset stats before loading any modifiers
14283 InitStatsForLevel();
14284 InitTaxiNodesForLevel();
14285 InitGlyphsForLevel();
14286 InitRunes();
14288 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14290 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14291 //_LoadMail();
14293 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14294 _LoadGlyphAuras();
14296 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14297 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14298 m_deathState = DEAD;
14300 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14302 // after spell load, learn rewarded spell if need also
14303 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14304 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14306 // after spell and quest load
14307 InitTalentForLevel();
14308 learnDefaultSpells();
14310 // must be before inventory (some items required reputation check)
14311 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14313 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14315 // update items with duration and realtime
14316 UpdateItemDuration(time_diff, true);
14318 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14320 // unread mails and next delivery time, actual mails not loaded
14321 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14323 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14325 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14326 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14327 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14329 if(!HasTitle(curTitle))
14330 SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
14333 // Not finish taxi flight path
14334 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14336 // problems with taxi path loading
14337 TaxiNodesEntry const* nodeEntry = NULL;
14338 if(uint32 node_id = m_taxi.GetTaxiSource())
14339 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14341 if(!nodeEntry) // don't know taxi start node, to homebind
14343 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14344 RelocateToHomebind();
14345 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14347 else // have start node, to it
14349 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14350 SetMapId(nodeEntry->map_id);
14351 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14352 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14354 m_taxi.ClearTaxiDestinations();
14356 else if(uint32 node_id = m_taxi.GetTaxiSource())
14358 // save source node as recall coord to prevent recall and fall from sky
14359 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14360 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14361 m_recallMap = nodeEntry->map_id;
14362 m_recallX = nodeEntry->x;
14363 m_recallY = nodeEntry->y;
14364 m_recallZ = nodeEntry->z;
14366 // flight will started later
14369 // has to be called after last Relocate() in Player::LoadFromDB
14370 SetFallInformation(0, GetPositionZ());
14372 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14374 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14375 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14376 if(!isAlive())
14377 RemoveAllAurasOnDeath();
14379 //apply all stat bonuses from items and auras
14380 SetCanModifyStats(true);
14381 UpdateAllStats();
14383 // restore remembered power/health values (but not more max values)
14384 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14385 for(uint32 i = 0; i < MAX_POWERS; ++i)
14386 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14388 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14389 outDebugValues();
14391 // GM state
14392 if(GetSession()->GetSecurity() > SEC_PLAYER)
14394 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14396 default:
14397 case 0: break; // disable
14398 case 1: SetGameMaster(true); break; // enable
14399 case 2: // save state
14400 if(extraflags & PLAYER_EXTRA_GM_ON)
14401 SetGameMaster(true);
14402 break;
14405 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14407 default:
14408 case 0: SetGMVisible(false); break; // invisible
14409 case 1: break; // visible
14410 case 2: // save state
14411 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14412 SetGMVisible(false);
14413 break;
14416 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14418 default:
14419 case 0: break; // disable
14420 case 1: SetAcceptTicket(true); break; // enable
14421 case 2: // save state
14422 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14423 SetAcceptTicket(true);
14424 break;
14427 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14429 default:
14430 case 0: break; // disable
14431 case 1: SetGMChat(true); break; // enable
14432 case 2: // save state
14433 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14434 SetGMChat(true);
14435 break;
14438 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14440 default:
14441 case 0: break; // disable
14442 case 1: SetAcceptWhispers(true); break; // enable
14443 case 2: // save state
14444 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14445 SetAcceptWhispers(true);
14446 break;
14450 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14452 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14453 m_achievementMgr.CheckAllAchievementCriteria();
14455 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
14457 return true;
14460 bool Player::isAllowedToLoot(Creature* creature)
14462 if(Player* recipient = creature->GetLootRecipient())
14464 if (recipient == this)
14465 return true;
14466 if( Group* otherGroup = recipient->GetGroup())
14468 Group* thisGroup = GetGroup();
14469 if(!thisGroup)
14470 return false;
14471 return thisGroup == otherGroup;
14473 return false;
14475 else
14476 // prevent other players from looting if the recipient got disconnected
14477 return !creature->hasLootRecipient();
14480 void Player::_LoadActions(QueryResult *result)
14482 m_actionButtons.clear();
14484 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14486 if(result)
14490 Field *fields = result->Fetch();
14492 uint8 button = fields[0].GetUInt8();
14494 if(addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8()))
14495 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14496 else
14498 sLog.outError( " ...at loading, and will deleted in DB also");
14500 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14501 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14504 while( result->NextRow() );
14506 delete result;
14510 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14512 m_Auras.clear();
14513 for (int i = 0; i < TOTAL_AURAS; ++i)
14514 m_modAuras[i].clear();
14516 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14518 if(result)
14522 Field *fields = result->Fetch();
14523 uint64 caster_guid = fields[0].GetUInt64();
14524 uint32 spellid = fields[1].GetUInt32();
14525 uint32 effindex = fields[2].GetUInt32();
14526 uint32 stackcount = fields[3].GetUInt32();
14527 int32 damage = (int32)fields[4].GetUInt32();
14528 int32 maxduration = (int32)fields[5].GetUInt32();
14529 int32 remaintime = (int32)fields[6].GetUInt32();
14530 int32 remaincharges = (int32)fields[7].GetUInt32();
14532 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14533 if(!spellproto)
14535 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14536 continue;
14539 if(effindex >= 3)
14541 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14542 continue;
14545 // negative effects should continue counting down after logout
14546 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14548 if(remaintime <= int32(timediff))
14549 continue;
14551 remaintime -= timediff;
14554 // prevent wrong values of remaincharges
14555 if(spellproto->procCharges)
14557 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14558 remaincharges = spellproto->procCharges;
14560 else
14561 remaincharges = 0;
14564 for(uint32 i=0; i<stackcount; ++i)
14566 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14567 if(!damage)
14568 damage = aura->GetModifier()->m_amount;
14570 // reset stolen single target auras
14571 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14572 aura->SetIsSingleTarget(false);
14574 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14575 AddAura(aura);
14576 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14579 while( result->NextRow() );
14581 delete result;
14584 if(m_class == CLASS_WARRIOR)
14585 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14588 void Player::_LoadGlyphAuras()
14590 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14592 if (uint32 glyph = GetGlyph(i))
14594 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14596 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14598 if(gp->TypeFlags == gs->TypeFlags)
14600 CastSpell(this, gp->SpellId, true);
14601 continue;
14603 else
14604 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14606 else
14607 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14609 else
14610 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14612 // On any error remove glyph
14613 SetGlyph(i, 0);
14618 void Player::LoadCorpse()
14620 if( isAlive() )
14622 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14624 else
14626 if(Corpse *corpse = GetCorpse())
14628 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14630 else
14632 //Prevent Dead Player login without corpse
14633 ResurrectPlayer(0.5f);
14638 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14640 //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());
14641 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14642 //NOTE: the "order by `bag`" is important because it makes sure
14643 //the bagMap is filled before items in the bags are loaded
14644 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14645 //expected to be equipped before offhand items (TODO: fixme)
14647 uint32 zone = GetZoneId();
14649 if (result)
14651 std::list<Item*> problematicItems;
14653 // prevent items from being added to the queue when stored
14654 m_itemUpdateQueueBlocked = true;
14657 Field *fields = result->Fetch();
14658 uint32 bag_guid = fields[1].GetUInt32();
14659 uint8 slot = fields[2].GetUInt8();
14660 uint32 item_guid = fields[3].GetUInt32();
14661 uint32 item_id = fields[4].GetUInt32();
14663 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14665 if(!proto)
14667 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14668 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14669 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14670 continue;
14673 Item *item = NewItemOrBag(proto);
14675 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14677 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14678 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14679 item->FSetState(ITEM_REMOVED);
14680 item->SaveToDB(); // it also deletes item object !
14681 continue;
14684 // not allow have in alive state item limited to another map/zone
14685 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14687 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14688 item->FSetState(ITEM_REMOVED);
14689 item->SaveToDB(); // it also deletes item object !
14690 continue;
14693 // "Conjured items disappear if you are logged out for more than 15 minutes"
14694 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14696 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14697 item->FSetState(ITEM_REMOVED);
14698 item->SaveToDB(); // it also deletes item object !
14699 continue;
14702 bool success = true;
14704 if (!bag_guid)
14706 // the item is not in a bag
14707 item->SetContainer( NULL );
14708 item->SetSlot(slot);
14710 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14712 ItemPosCountVec dest;
14713 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14714 item = StoreItem(dest, item, true);
14715 else
14716 success = false;
14718 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14720 uint16 dest;
14721 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14722 QuickEquipItem(dest, item);
14723 else
14724 success = false;
14726 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14728 ItemPosCountVec dest;
14729 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14730 item = BankItem(dest, item, true);
14731 else
14732 success = false;
14735 if(success)
14737 // store bags that may contain items in them
14738 if(item->IsBag() && IsBagPos(item->GetPos()))
14739 bagMap[item_guid] = (Bag*)item;
14742 else
14744 item->SetSlot(NULL_SLOT);
14745 // the item is in a bag, find the bag
14746 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
14747 if(itr != bagMap.end())
14748 itr->second->StoreItem(slot, item, true );
14749 else
14750 success = false;
14753 // item's state may have changed after stored
14754 if (success)
14755 item->SetState(ITEM_UNCHANGED, this);
14756 else
14758 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);
14759 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14760 problematicItems.push_back(item);
14762 } while (result->NextRow());
14764 delete result;
14765 m_itemUpdateQueueBlocked = false;
14767 // send by mail problematic items
14768 while(!problematicItems.empty())
14770 // fill mail
14771 MailItemsInfo mi; // item list preparing
14773 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14775 Item* item = problematicItems.front();
14776 problematicItems.pop_front();
14778 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14781 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14783 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14786 //if(isAlive())
14787 _ApplyAllItemMods();
14790 // load mailed item which should receive current player
14791 void Player::_LoadMailedItems(Mail *mail)
14793 // data needs to be at first place for Item::LoadFromDB
14794 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);
14795 if(!result)
14796 return;
14800 Field *fields = result->Fetch();
14801 uint32 item_guid_low = fields[1].GetUInt32();
14802 uint32 item_template = fields[2].GetUInt32();
14804 mail->AddItem(item_guid_low, item_template);
14806 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14808 if(!proto)
14810 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);
14811 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14812 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14813 continue;
14816 Item *item = NewItemOrBag(proto);
14818 if(!item->LoadFromDB(item_guid_low, 0, result))
14820 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14821 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14822 item->FSetState(ITEM_REMOVED);
14823 item->SaveToDB(); // it also deletes item object !
14824 continue;
14827 AddMItem(item);
14828 } while (result->NextRow());
14830 delete result;
14833 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14835 //set a count of unread mails
14836 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" UI64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
14837 if (resultUnread)
14839 Field *fieldMail = resultUnread->Fetch();
14840 unReadMails = fieldMail[0].GetUInt8();
14841 delete resultUnread;
14844 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14845 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14846 if (resultDelivery)
14848 Field *fieldMail = resultDelivery->Fetch();
14849 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14850 delete resultDelivery;
14854 void Player::_LoadMail()
14856 m_mail.clear();
14857 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14858 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());
14859 if(result)
14863 Field *fields = result->Fetch();
14864 Mail *m = new Mail;
14865 m->messageID = fields[0].GetUInt32();
14866 m->messageType = fields[1].GetUInt8();
14867 m->sender = fields[2].GetUInt32();
14868 m->receiver = fields[3].GetUInt32();
14869 m->subject = fields[4].GetCppString();
14870 m->itemTextId = fields[5].GetUInt32();
14871 bool has_items = fields[6].GetBool();
14872 m->expire_time = (time_t)fields[7].GetUInt64();
14873 m->deliver_time = (time_t)fields[8].GetUInt64();
14874 m->money = fields[9].GetUInt32();
14875 m->COD = fields[10].GetUInt32();
14876 m->checked = fields[11].GetUInt32();
14877 m->stationery = fields[12].GetUInt8();
14878 m->mailTemplateId = fields[13].GetInt16();
14880 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14882 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14883 m->mailTemplateId = 0;
14886 m->state = MAIL_STATE_UNCHANGED;
14888 if (has_items)
14889 _LoadMailedItems(m);
14891 m_mail.push_back(m);
14892 } while( result->NextRow() );
14893 delete result;
14895 m_mailsLoaded = true;
14898 void Player::LoadPet()
14900 //fixme: the pet should still be loaded if the player is not in world
14901 // just not added to the map
14902 if(IsInWorld())
14904 Pet *pet = new Pet;
14905 if(!pet->LoadPetFromDB(this,0,0,true))
14906 delete pet;
14910 void Player::_LoadQuestStatus(QueryResult *result)
14912 mQuestStatus.clear();
14914 uint32 slot = 0;
14916 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14917 //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());
14919 if(result)
14923 Field *fields = result->Fetch();
14925 uint32 quest_id = fields[0].GetUInt32();
14926 // used to be new, no delete?
14927 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14928 if( pQuest )
14930 // find or create
14931 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14933 uint32 qstatus = fields[1].GetUInt32();
14934 if(qstatus < MAX_QUEST_STATUS)
14935 questStatusData.m_status = QuestStatus(qstatus);
14936 else
14938 questStatusData.m_status = QUEST_STATUS_NONE;
14939 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14942 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14943 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14945 time_t quest_time = time_t(fields[4].GetUInt64());
14947 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14949 AddTimedQuest( quest_id );
14951 if (quest_time <= sWorld.GetGameTime())
14952 questStatusData.m_timer = 1;
14953 else
14954 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
14956 else
14957 quest_time = 0;
14959 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14960 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14961 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14962 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14963 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14964 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14965 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14966 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14968 questStatusData.uState = QUEST_UNCHANGED;
14970 // add to quest log
14971 if( slot < MAX_QUEST_LOG_SIZE &&
14972 ( questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
14973 questStatusData.m_status == QUEST_STATUS_COMPLETE &&
14974 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14976 SetQuestSlot(slot, quest_id, quest_time);
14978 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14979 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
14981 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14982 if(questStatusData.m_creatureOrGOcount[idx])
14983 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
14985 ++slot;
14988 if(questStatusData.m_rewarded)
14990 // learn rewarded spell if unknown
14991 learnQuestRewardedSpells(pQuest);
14993 // set rewarded title if any
14994 if(pQuest->GetCharTitleId())
14996 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14997 SetTitle(titleEntry);
15000 if(pQuest->GetBonusTalents())
15001 m_questRewardTalentCount += pQuest->GetBonusTalents();
15004 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15007 while( result->NextRow() );
15009 delete result;
15012 // clear quest log tail
15013 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15014 SetQuestSlot(i, 0);
15017 void Player::_LoadDailyQuestStatus(QueryResult *result)
15019 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15020 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15022 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15024 if(result)
15026 uint32 quest_daily_idx = 0;
15030 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15032 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15033 break;
15036 Field *fields = result->Fetch();
15038 uint32 quest_id = fields[0].GetUInt32();
15040 // save _any_ from daily quest times (it must be after last reset anyway)
15041 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15043 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15044 if( !pQuest )
15045 continue;
15047 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15048 ++quest_daily_idx;
15050 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15052 while( result->NextRow() );
15054 delete result;
15057 m_DailyQuestChanged = false;
15060 void Player::_LoadSpells(QueryResult *result)
15062 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15064 if(result)
15068 Field *fields = result->Fetch();
15070 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
15072 while( result->NextRow() );
15074 delete result;
15078 void Player::_LoadGroup(QueryResult *result)
15080 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15081 if(result)
15083 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15084 delete result;
15085 Group* group = objmgr.GetGroupByLeader(leaderGuid);
15086 if(group)
15088 uint8 subgroup = group->GetMemberGroup(GetGUID());
15089 SetGroup(group, subgroup);
15090 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
15092 // the group leader may change the instance difficulty while the player is offline
15093 SetDifficulty(group->GetDifficulty());
15099 void Player::_LoadBoundInstances(QueryResult *result)
15101 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15102 m_boundInstances[i].clear();
15104 Group *group = GetGroup();
15106 //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));
15107 if(result)
15111 Field *fields = result->Fetch();
15112 bool perm = fields[1].GetBool();
15113 uint32 mapId = fields[2].GetUInt32();
15114 uint32 instanceId = fields[0].GetUInt32();
15115 uint8 difficulty = fields[3].GetUInt8();
15116 time_t resetTime = (time_t)fields[4].GetUInt64();
15117 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15118 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15119 // and in that case it is not used
15121 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15122 if(!mapEntry || !mapEntry->IsDungeon())
15124 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15125 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15126 continue;
15129 if(!perm && group)
15131 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);
15132 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15133 continue;
15136 // since non permanent binds are always solo bind, they can always be reset
15137 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15138 if(save) BindToInstance(save, perm, true);
15139 } while(result->NextRow());
15140 delete result;
15144 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15146 // some instances only have one difficulty
15147 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15148 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15150 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15151 if(itr != m_boundInstances[difficulty].end())
15152 return &itr->second;
15153 else
15154 return NULL;
15157 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15159 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15160 UnbindInstance(itr, difficulty, unload);
15163 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15165 if(itr != m_boundInstances[difficulty].end())
15167 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15168 itr->second.save->RemovePlayer(this); // save can become invalid
15169 m_boundInstances[difficulty].erase(itr++);
15173 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15175 if(save)
15177 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15178 if(bind.save)
15180 // update the save when the group kills a boss
15181 if(permanent != bind.perm || save != bind.save)
15182 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());
15184 else
15185 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15187 if(bind.save != save)
15189 if(bind.save) bind.save->RemovePlayer(this);
15190 save->AddPlayer(this);
15193 if(permanent) save->SetCanReset(false);
15195 bind.save = save;
15196 bind.perm = permanent;
15197 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());
15198 return &bind;
15200 else
15201 return NULL;
15204 void Player::SendRaidInfo()
15206 uint32 counter = 0;
15208 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15210 size_t p_counter = data.wpos();
15211 data << uint32(counter); // placeholder
15213 time_t now = time(NULL);
15215 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15217 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15219 if(itr->second.perm)
15221 InstanceSave *save = itr->second.save;
15222 data << uint32(save->GetMapId()); // map id
15223 data << uint32(save->GetDifficulty()); // difficulty
15224 data << uint64(save->GetInstanceId()); // instance id
15225 data << uint32(save->GetResetTime() - now); // reset time
15226 data << uint32(0); // is extended
15227 ++counter;
15231 data.put<uint32>(p_counter, counter);
15232 GetSession()->SendPacket(&data);
15236 - called on every successful teleportation to a map
15238 void Player::SendSavedInstances()
15240 bool hasBeenSaved = false;
15241 WorldPacket data;
15243 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15245 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15247 if(itr->second.perm) // only permanent binds are sent
15249 hasBeenSaved = true;
15250 break;
15255 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15256 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15257 data << uint32(hasBeenSaved);
15258 GetSession()->SendPacket(&data);
15260 if(!hasBeenSaved)
15261 return;
15263 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15265 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15267 if(itr->second.perm)
15269 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15270 data << uint32(itr->second.save->GetMapId());
15271 GetSession()->SendPacket(&data);
15277 /// convert the player's binds to the group
15278 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15280 bool has_binds = false;
15281 bool has_solo = false;
15283 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15284 assert(player_guid);
15286 // copy all binds to the group, when changing leader it's assumed the character
15287 // will not have any solo binds
15289 if(player)
15291 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15293 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15295 has_binds = true;
15296 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15297 // permanent binds are not removed
15298 if(!itr->second.perm)
15300 player->UnbindInstance(itr, i, true); // increments itr
15301 has_solo = true;
15303 else
15304 ++itr;
15309 // if the player's not online we don't know what binds it has
15310 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));
15311 // the following should not get executed when changing leaders
15312 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15315 bool Player::_LoadHomeBind(QueryResult *result)
15317 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15318 if(!info)
15320 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15321 return false;
15324 bool ok = false;
15325 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15326 if (result)
15328 Field *fields = result->Fetch();
15329 m_homebindMapId = fields[0].GetUInt32();
15330 m_homebindZoneId = fields[1].GetUInt16();
15331 m_homebindX = fields[2].GetFloat();
15332 m_homebindY = fields[3].GetFloat();
15333 m_homebindZ = fields[4].GetFloat();
15334 delete result;
15336 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15338 // accept saved data only for valid position (and non instanceable), and accessable
15339 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15340 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15342 ok = true;
15344 else
15345 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15348 if(!ok)
15350 m_homebindMapId = info->mapId;
15351 m_homebindZoneId = info->zoneId;
15352 m_homebindX = info->positionX;
15353 m_homebindY = info->positionY;
15354 m_homebindZ = info->positionZ;
15356 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);
15359 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15360 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15362 return true;
15365 /*********************************************************/
15366 /*** SAVE SYSTEM ***/
15367 /*********************************************************/
15369 void Player::SaveToDB()
15371 // delay auto save at any saves (manual, in code, or autosave)
15372 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15374 // first save/honor gain after midnight will also update the player's honor fields
15375 UpdateHonorFields();
15377 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15378 //save, far from tavern/city
15379 //save, but in tavern/city
15380 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15381 outDebugValues();
15383 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15384 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15385 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15386 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15387 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15388 uint32 tmp_displayid = GetDisplayId();
15390 // Set player sit state to standing on save, also stealth and shifted form
15391 SetByteValue(UNIT_FIELD_BYTES_1, 0, UNIT_STAND_STATE_STAND);
15392 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15393 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15394 SetDisplayId(GetNativeDisplayId());
15396 bool inworld = IsInWorld();
15398 CharacterDatabase.BeginTransaction();
15400 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15402 std::string sql_name = m_name;
15403 CharacterDatabase.escape_string(sql_name);
15405 std::ostringstream ss;
15406 ss << "INSERT INTO characters (guid,account,name,race,class,"
15407 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15408 "taximask, online, cinematic, "
15409 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15410 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15411 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15412 << GetGUIDLow() << ", "
15413 << GetSession()->GetAccountId() << ", '"
15414 << sql_name << "', "
15415 << m_race << ", "
15416 << m_class << ", ";
15418 if(!IsBeingTeleported())
15420 ss << GetMapId() << ", "
15421 << (uint32)GetDifficulty() << ", "
15422 << finiteAlways(GetPositionX()) << ", "
15423 << finiteAlways(GetPositionY()) << ", "
15424 << finiteAlways(GetPositionZ()) << ", "
15425 << finiteAlways(GetOrientation()) << ", '";
15427 else
15429 ss << GetTeleportDest().mapid << ", "
15430 << (uint32)GetDifficulty() << ", "
15431 << finiteAlways(GetTeleportDest().x) << ", "
15432 << finiteAlways(GetTeleportDest().y) << ", "
15433 << finiteAlways(GetTeleportDest().z) << ", "
15434 << finiteAlways(GetTeleportDest().o) << ", '";
15437 uint16 i;
15438 for( i = 0; i < m_valuesCount; ++i )
15440 ss << GetUInt32Value(i) << " ";
15443 ss << "', ";
15445 ss << m_taxi; // string with TaxiMaskSize numbers
15447 ss << ", ";
15448 ss << (inworld ? 1 : 0);
15450 ss << ", ";
15451 ss << m_cinematic;
15453 ss << ", ";
15454 ss << m_Played_time[0];
15455 ss << ", ";
15456 ss << m_Played_time[1];
15458 ss << ", ";
15459 ss << finiteAlways(m_rest_bonus);
15460 ss << ", ";
15461 ss << (uint64)time(NULL);
15462 ss << ", ";
15463 ss << is_save_resting;
15464 ss << ", ";
15465 ss << m_resetTalentsCost;
15466 ss << ", ";
15467 ss << (uint64)m_resetTalentsTime;
15469 ss << ", ";
15470 ss << finiteAlways(m_movementInfo.t_x);
15471 ss << ", ";
15472 ss << finiteAlways(m_movementInfo.t_y);
15473 ss << ", ";
15474 ss << finiteAlways(m_movementInfo.t_z);
15475 ss << ", ";
15476 ss << finiteAlways(m_movementInfo.t_o);
15477 ss << ", ";
15478 if (m_transport)
15479 ss << m_transport->GetGUIDLow();
15480 else
15481 ss << "0";
15483 ss << ", ";
15484 ss << m_ExtraFlags;
15486 ss << ", ";
15487 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15489 ss << ", ";
15490 ss << uint32(m_atLoginFlags);
15492 ss << ", ";
15493 ss << GetZoneId();
15495 ss << ", ";
15496 ss << (uint64)m_deathExpireTime;
15498 ss << ", '";
15499 ss << m_taxi.SaveTaxiDestinationsToString();
15500 ss << "', '0', ";
15501 ss << GetBattleGroundId();
15502 ss << ", ";
15503 ss << GetBGTeam();
15504 ss << ", ";
15505 ss << m_bgEntryPoint.mapid << ", "
15506 << finiteAlways(m_bgEntryPoint.x) << ", "
15507 << finiteAlways(m_bgEntryPoint.y) << ", "
15508 << finiteAlways(m_bgEntryPoint.z) << ", "
15509 << finiteAlways(m_bgEntryPoint.o);
15510 ss << ")";
15512 CharacterDatabase.Execute( ss.str().c_str() );
15514 if(m_mailsUpdated) //save mails only when needed
15515 _SaveMail();
15517 _SaveInventory();
15518 _SaveQuestStatus();
15519 _SaveDailyQuestStatus();
15520 _SaveSpells();
15521 _SaveSpellCooldowns();
15522 _SaveActions();
15523 _SaveAuras();
15524 m_achievementMgr.SaveToDB();
15525 m_reputationMgr.SaveToDB();
15526 _SaveEquipmentSets();
15527 GetSession()->SaveTutorialsData(); // changed only while character in game
15529 CharacterDatabase.CommitTransaction();
15531 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15532 SetDisplayId(tmp_displayid);
15533 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15534 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15535 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15536 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15538 // save pet (hunter pet level and experience and all type pets health/mana).
15539 if(Pet* pet = GetPet())
15540 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15543 // fast save function for item/money cheating preventing - save only inventory and money state
15544 void Player::SaveInventoryAndGoldToDB()
15546 _SaveInventory();
15547 //money is in data field
15548 SaveDataFieldToDB();
15551 void Player::_SaveActions()
15553 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15555 switch (itr->second.uState)
15557 case ACTIONBUTTON_NEW:
15558 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15559 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15560 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15561 ++itr;
15562 break;
15563 case ACTIONBUTTON_CHANGED:
15564 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15565 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15566 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15567 ++itr;
15568 break;
15569 case ACTIONBUTTON_DELETED:
15570 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15571 m_actionButtons.erase(itr++);
15572 break;
15573 default:
15574 ++itr;
15575 break;
15580 void Player::_SaveAuras()
15582 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15584 AuraMap const& auras = GetAuras();
15586 if (auras.empty())
15587 return;
15589 spellEffectPair lastEffectPair = auras.begin()->first;
15590 uint32 stackCounter = 1;
15592 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15594 if(itr == auras.end() || lastEffectPair != itr->first)
15596 AuraMap::const_iterator itr2 = itr;
15597 // save previous spellEffectPair to db
15598 itr2--;
15600 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15602 //skip all auras from spells that are passive or need a shapeshift
15603 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15605 //do not save single target auras (unless they were cast by the player)
15606 if (!(itr2->second->GetCasterGUID() != GetGUID() && itr2->second->IsSingleTarget()))
15608 uint8 i;
15609 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15610 for (i = 0; i < 3; ++i)
15611 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15612 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15613 break;
15615 if (i == 3)
15617 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15618 "VALUES ('%u', '" UI64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15619 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()));
15624 if(itr == auras.end())
15625 break;
15628 if (lastEffectPair == itr->first)
15629 stackCounter++;
15630 else
15632 lastEffectPair = itr->first;
15633 stackCounter = 1;
15638 void Player::_SaveInventory()
15640 // force items in buyback slots to new state
15641 // and remove those that aren't already
15642 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
15644 Item *item = m_items[i];
15645 if (!item || item->GetState() == ITEM_NEW) continue;
15646 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15647 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15648 m_items[i]->FSetState(ITEM_NEW);
15651 // update enchantment durations
15652 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15654 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15657 // if no changes
15658 if (m_itemUpdateQueue.empty()) return;
15660 // do not save if the update queue is corrupt
15661 bool error = false;
15662 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15664 Item *item = m_itemUpdateQueue[i];
15665 if(!item || item->GetState() == ITEM_REMOVED) continue;
15666 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15668 if (test == NULL)
15670 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());
15671 error = true;
15673 else if (test != item)
15675 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());
15676 error = true;
15680 if (error)
15682 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15683 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15684 return;
15687 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15689 Item *item = m_itemUpdateQueue[i];
15690 if(!item) continue;
15692 Bag *container = item->GetContainer();
15693 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15695 switch(item->GetState())
15697 case ITEM_NEW:
15698 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());
15699 break;
15700 case ITEM_CHANGED:
15701 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());
15702 break;
15703 case ITEM_REMOVED:
15704 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15705 break;
15706 case ITEM_UNCHANGED:
15707 break;
15710 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15712 m_itemUpdateQueue.clear();
15715 void Player::_SaveMail()
15717 if (!m_mailsLoaded)
15718 return;
15720 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15722 Mail *m = (*itr);
15723 if (m->state == MAIL_STATE_CHANGED)
15725 CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" UI64FMTD "', deliver_time = '" UI64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15726 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15727 if(m->removedItems.size())
15729 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15730 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15731 m->removedItems.clear();
15733 m->state = MAIL_STATE_UNCHANGED;
15735 else if (m->state == MAIL_STATE_DELETED)
15737 if (m->HasItems())
15738 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15739 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15740 if (m->itemTextId)
15741 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15742 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15743 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15747 //deallocate deleted mails...
15748 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15750 if ((*itr)->state == MAIL_STATE_DELETED)
15752 Mail* m = *itr;
15753 m_mail.erase(itr);
15754 delete m;
15755 itr = m_mail.begin();
15757 else
15758 ++itr;
15761 m_mailsUpdated = false;
15764 void Player::_SaveQuestStatus()
15766 // we don't need transactions here.
15767 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15769 switch (i->second.uState)
15771 case QUEST_NEW :
15772 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15773 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15774 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]);
15775 break;
15776 case QUEST_CHANGED :
15777 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" UI64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15778 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 );
15779 break;
15780 case QUEST_UNCHANGED:
15781 break;
15783 i->second.uState = QUEST_UNCHANGED;
15787 void Player::_SaveDailyQuestStatus()
15789 if(!m_DailyQuestChanged)
15790 return;
15792 m_DailyQuestChanged = false;
15794 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15796 // we don't need transactions here.
15797 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15798 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15799 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15800 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
15801 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15804 void Player::_SaveSpells()
15806 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15808 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15809 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15811 // add only changed/new not dependent spells
15812 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15813 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);
15815 if (itr->second->state == PLAYERSPELL_REMOVED)
15817 delete itr->second;
15818 m_spells.erase(itr++);
15820 else
15822 itr->second->state = PLAYERSPELL_UNCHANGED;
15823 ++itr;
15829 void Player::outDebugValues() const
15831 if(!sLog.IsOutDebug()) // optimize disabled debug output
15832 return;
15834 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15835 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15836 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15837 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15838 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15839 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15840 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15841 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15842 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15843 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15844 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15845 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15848 /*********************************************************/
15849 /*** FLOOD FILTER SYSTEM ***/
15850 /*********************************************************/
15852 void Player::UpdateSpeakTime()
15854 // ignore chat spam protection for GMs in any mode
15855 if(GetSession()->GetSecurity() > SEC_PLAYER)
15856 return;
15858 time_t current = time (NULL);
15859 if(m_speakTime > current)
15861 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15862 if(!max_count)
15863 return;
15865 ++m_speakCount;
15866 if(m_speakCount >= max_count)
15868 // prevent overwrite mute time, if message send just before mutes set, for example.
15869 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15870 if(GetSession()->m_muteTime < new_mute)
15871 GetSession()->m_muteTime = new_mute;
15873 m_speakCount = 0;
15876 else
15877 m_speakCount = 0;
15879 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15882 bool Player::CanSpeak() const
15884 return GetSession()->m_muteTime <= time (NULL);
15887 /*********************************************************/
15888 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15889 /*********************************************************/
15891 void Player::SendAttackSwingNotInRange()
15893 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15894 GetSession()->SendPacket( &data );
15897 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15899 std::ostringstream ss;
15900 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15901 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15902 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15903 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15904 sLog.outDebug(ss.str().c_str());
15905 CharacterDatabase.Execute(ss.str().c_str());
15908 void Player::SaveDataFieldToDB()
15910 std::ostringstream ss;
15911 ss<<"UPDATE characters SET data='";
15913 for(uint16 i = 0; i < m_valuesCount; ++i )
15915 ss << GetUInt32Value(i) << " ";
15917 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15919 CharacterDatabase.Execute(ss.str().c_str());
15922 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15924 std::ostringstream ss2;
15925 ss2<<"UPDATE characters SET data='";
15926 int i=0;
15927 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15929 ss2<<tokens[i]<<" ";
15931 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15933 return CharacterDatabase.Execute(ss2.str().c_str());
15936 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15938 char buf[11];
15939 snprintf(buf,11,"%u",value);
15941 if(index >= tokens.size())
15942 return;
15944 tokens[index] = buf;
15947 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15949 Tokens tokens;
15950 if(!LoadValuesArrayFromDB(tokens,guid))
15951 return;
15953 if(index >= tokens.size())
15954 return;
15956 char buf[11];
15957 snprintf(buf,11,"%u",value);
15958 tokens[index] = buf;
15960 SaveValuesArrayInDB(tokens,guid);
15963 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15965 uint32 temp;
15966 memcpy(&temp, &value, sizeof(value));
15967 Player::SetUInt32ValueInDB(index, temp, guid);
15970 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15972 Tokens tokens;
15973 if(!LoadValuesArrayFromDB(tokens, guid))
15974 return;
15976 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15977 uint8 race = unit_bytes0 & 0xFF;
15978 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15980 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15981 if(!info)
15982 return;
15984 unit_bytes0 &= ~(0xFF << 16);
15985 unit_bytes0 |= (gender << 16);
15986 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15988 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
15989 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
15991 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
15993 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
15994 player_bytes2 &= ~0xFF;
15995 player_bytes2 |= facialHair;
15996 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
15998 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
15999 player_bytes3 &= ~0xFF;
16000 player_bytes3 |= gender;
16001 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
16003 SaveValuesArrayInDB(tokens, guid);
16006 void Player::SendAttackSwingDeadTarget()
16008 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16009 GetSession()->SendPacket( &data );
16012 void Player::SendAttackSwingCantAttack()
16014 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16015 GetSession()->SendPacket( &data );
16018 void Player::SendAttackSwingCancelAttack()
16020 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16021 GetSession()->SendPacket( &data );
16024 void Player::SendAttackSwingBadFacingAttack()
16026 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16027 GetSession()->SendPacket( &data );
16030 void Player::SendAutoRepeatCancel()
16032 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
16033 data.append(GetPackGUID()); // may be it's target guid
16034 GetSession()->SendPacket( &data );
16037 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16039 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16040 data << Area;
16041 data << Experience;
16042 GetSession()->SendPacket(&data);
16045 void Player::SendDungeonDifficulty(bool IsInGroup)
16047 uint8 val = 0x00000001;
16048 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16049 data << (uint32)GetDifficulty();
16050 data << uint32(val);
16051 data << uint32(IsInGroup);
16052 GetSession()->SendPacket(&data);
16055 void Player::SendResetFailedNotify(uint32 mapid)
16057 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16058 data << uint32(mapid);
16059 GetSession()->SendPacket(&data);
16062 /// Reset all solo instances and optionally send a message on success for each
16063 void Player::ResetInstances(uint8 method)
16065 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16067 // we assume that when the difficulty changes, all instances that can be reset will be
16068 uint8 dif = GetDifficulty();
16070 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16072 InstanceSave *p = itr->second.save;
16073 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16074 if(!entry || !p->CanReset())
16076 ++itr;
16077 continue;
16080 if(method == INSTANCE_RESET_ALL)
16082 // the "reset all instances" method can only reset normal maps
16083 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16085 ++itr;
16086 continue;
16090 // if the map is loaded, reset it
16091 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16092 if(map && map->IsDungeon())
16093 ((InstanceMap*)map)->Reset(method);
16095 // since this is a solo instance there should not be any players inside
16096 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16097 SendResetInstanceSuccess(p->GetMapId());
16099 p->DeleteFromDB();
16100 m_boundInstances[dif].erase(itr++);
16102 // the following should remove the instance save from the manager and delete it as well
16103 p->RemovePlayer(this);
16107 void Player::SendResetInstanceSuccess(uint32 MapId)
16109 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16110 data << MapId;
16111 GetSession()->SendPacket(&data);
16114 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16116 // TODO: find what other fail reasons there are besides players in the instance
16117 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16118 data << reason;
16119 data << MapId;
16120 GetSession()->SendPacket(&data);
16123 /*********************************************************/
16124 /*** Update timers ***/
16125 /*********************************************************/
16127 ///checks the 15 afk reports per 5 minutes limit
16128 void Player::UpdateAfkReport(time_t currTime)
16130 if(m_bgAfkReportedTimer <= currTime)
16132 m_bgAfkReportedCount = 0;
16133 m_bgAfkReportedTimer = currTime+5*MINUTE;
16137 void Player::UpdateContestedPvP(uint32 diff)
16139 if(!m_contestedPvPTimer||isInCombat())
16140 return;
16141 if(m_contestedPvPTimer <= diff)
16143 ResetContestedPvP();
16145 else
16146 m_contestedPvPTimer -= diff;
16149 void Player::UpdatePvPFlag(time_t currTime)
16151 if(!IsPvP())
16152 return;
16153 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16154 return;
16156 UpdatePvP(false);
16159 void Player::UpdateDuelFlag(time_t currTime)
16161 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16162 return;
16164 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16165 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16167 duel->startTimer = 0;
16168 duel->startTime = currTime;
16169 duel->opponent->duel->startTimer = 0;
16170 duel->opponent->duel->startTime = currTime;
16173 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16175 if(!pet)
16176 pet = GetPet();
16178 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16180 //returning of reagents only for players, so best done here
16181 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16182 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16184 if(spellInfo)
16186 for(uint32 i = 0; i < 7; ++i)
16188 if(spellInfo->Reagent[i] > 0)
16190 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16191 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16192 if( msg == EQUIP_ERR_OK )
16194 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16195 if(IsInWorld())
16196 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16201 m_temporaryUnsummonedPetNumber = 0;
16204 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16205 return;
16207 // only if current pet in slot
16208 switch(pet->getPetType())
16210 case MINI_PET:
16211 m_miniPet = 0;
16212 break;
16213 case GUARDIAN_PET:
16214 RemoveGuardian(pet);
16215 break;
16216 default:
16217 if(GetPetGUID() == pet->GetGUID())
16218 SetPet(NULL);
16219 break;
16222 pet->CombatStop();
16224 if(returnreagent)
16226 switch(pet->GetEntry())
16228 //warlock pets except imp are removed(?) when logging out
16229 case 1860:
16230 case 1863:
16231 case 417:
16232 case 17252:
16233 mode = PET_SAVE_NOT_IN_SLOT;
16234 break;
16238 pet->SavePetToDB(mode);
16240 pet->CleanupsBeforeDelete();
16241 pet->AddObjectToRemoveList();
16242 pet->m_removed = true;
16244 if(pet->isControlled())
16246 WorldPacket data(SMSG_PET_SPELLS, 8);
16247 data << uint64(0);
16248 GetSession()->SendPacket(&data);
16250 if(GetGroup())
16251 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16255 void Player::RemoveMiniPet()
16257 if(Pet* pet = GetMiniPet())
16259 pet->Remove(PET_SAVE_AS_DELETED);
16260 m_miniPet = 0;
16264 Pet* Player::GetMiniPet()
16266 if(!m_miniPet)
16267 return NULL;
16268 return ObjectAccessor::GetPet(m_miniPet);
16271 void Player::Uncharm()
16273 Unit* charm = GetCharm();
16274 if(!charm)
16275 return;
16277 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16278 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16281 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16283 *data << (uint8)msgtype;
16284 *data << (uint32)language;
16285 *data << (uint64)GetGUID();
16286 *data << (uint32)language; //language 2.1.0 ?
16287 *data << (uint64)GetGUID();
16288 *data << (uint32)(text.length()+1);
16289 *data << text;
16290 *data << (uint8)chatTag();
16293 void Player::Say(const std::string& text, const uint32 language)
16295 WorldPacket data(SMSG_MESSAGECHAT, 200);
16296 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16297 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16300 void Player::Yell(const std::string& text, const uint32 language)
16302 WorldPacket data(SMSG_MESSAGECHAT, 200);
16303 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16304 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16307 void Player::TextEmote(const std::string& text)
16309 WorldPacket data(SMSG_MESSAGECHAT, 200);
16310 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16311 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16314 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16316 if (language != LANG_ADDON) // if not addon data
16317 language = LANG_UNIVERSAL; // whispers should always be readable
16319 Player *rPlayer = objmgr.GetPlayer(receiver);
16321 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16322 if(!rPlayer->isDND() || isGameMaster())
16324 WorldPacket data(SMSG_MESSAGECHAT, 200);
16325 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16326 rPlayer->GetSession()->SendPacket(&data);
16328 data.Initialize(SMSG_MESSAGECHAT, 200);
16329 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16330 GetSession()->SendPacket(&data);
16332 else
16334 // announce to player that player he is whispering to is dnd and cannot receive his message
16335 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16338 if(!isAcceptWhispers())
16340 SetAcceptWhispers(true);
16341 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16344 // announce to player that player he is whispering to is afk
16345 if(rPlayer->isAFK())
16346 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16348 // if player whisper someone, auto turn of dnd to be able to receive an answer
16349 if(isDND() && !rPlayer->isGameMaster())
16350 ToggleDND();
16353 void Player::PetSpellInitialize()
16355 Pet* pet = GetPet();
16357 if(!pet)
16358 return;
16360 sLog.outDebug("Pet Spells Groups");
16362 CharmInfo *charmInfo = pet->GetCharmInfo();
16364 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16365 data << uint64(pet->GetGUID());
16366 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16367 data << uint32(0);
16368 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16370 // action bar loop
16371 charmInfo->BuildActionBar(&data);
16373 size_t spellsCountPos = data.wpos();
16375 // spells count
16376 uint8 addlist = 0;
16377 data << uint8(addlist); // placeholder
16379 if (pet->IsPermanentPetFor(this))
16381 // spells loop
16382 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16384 if(itr->second.state == PETSPELL_REMOVED)
16385 continue;
16387 data << uint16(itr->first);
16388 data << uint16(itr->second.active); // pet spell active state isn't boolean
16389 ++addlist;
16393 data.put<uint8>(spellsCountPos, addlist);
16395 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16396 data << uint8(cooldownsCount);
16398 time_t curTime = time(NULL);
16400 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16402 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16404 data << uint32(itr->first); // spellid
16405 data << uint16(0); // spell category?
16406 data << uint32(cooldown); // cooldown
16407 data << uint32(0); // category cooldown
16410 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16412 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16414 data << uint32(itr->first); // spellid
16415 data << uint16(0); // spell category?
16416 data << uint32(0); // cooldown
16417 data << uint32(cooldown); // category cooldown
16420 GetSession()->SendPacket(&data);
16423 void Player::PossessSpellInitialize()
16425 Unit* charm = GetCharm();
16427 if(!charm)
16428 return;
16430 CharmInfo *charmInfo = charm->GetCharmInfo();
16432 if(!charmInfo)
16434 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16435 return;
16438 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16439 data << uint64(charm->GetGUID());
16440 data << uint16(0);
16441 data << uint32(0);
16442 data << uint32(0);
16444 charmInfo->BuildActionBar(&data);
16446 data << uint8(0); // spells count
16447 data << uint8(0); // cooldowns count
16449 GetSession()->SendPacket(&data);
16452 void Player::CharmSpellInitialize()
16454 Unit* charm = GetCharm();
16456 if(!charm)
16457 return;
16459 CharmInfo *charmInfo = charm->GetCharmInfo();
16460 if(!charmInfo)
16462 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16463 return;
16466 uint8 addlist = 0;
16468 if(charm->GetTypeId() != TYPEID_PLAYER)
16470 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16472 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16474 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16476 if(charmInfo->GetCharmSpell(i)->spellId)
16477 ++addlist;
16482 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
16483 data << uint64(charm->GetGUID());
16484 data << uint16(0);
16485 data << uint32(0);
16487 if(charm->GetTypeId() != TYPEID_PLAYER)
16488 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16489 else
16490 data << uint8(0) << uint8(0) << uint16(0);
16492 charmInfo->BuildActionBar(&data);
16494 data << uint8(addlist);
16496 if(addlist)
16498 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16500 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16501 if(cspell->spellId)
16503 data << uint16(cspell->spellId);
16504 data << uint16(cspell->active);
16509 data << uint8(0); // cooldowns count
16511 GetSession()->SendPacket(&data);
16514 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16516 if (!mod || !spellInfo)
16517 return false;
16519 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16521 // prevent apply to any spell except spell that trigger expire
16522 if(spell)
16524 if(mod->lastAffected != spell)
16525 return false;
16527 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16528 return false;
16531 return spellmgr.IsAffectedByMod(spellInfo, mod);
16534 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16536 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16538 for(int eff=0;eff<96;++eff)
16540 uint64 _mask = 0;
16541 uint64 _mask2= 0;
16542 if (eff<64) _mask = uint64(1) << (eff- 0);
16543 else _mask2= uint64(1) << (eff-64);
16544 if ( mod->mask & _mask || mod->mask2 & _mask2)
16546 int32 val = 0;
16547 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16549 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16550 val += (*itr)->value;
16552 val += apply ? mod->value : -(mod->value);
16553 WorldPacket data(Opcode, (1+1+4));
16554 data << uint8(eff);
16555 data << uint8(mod->op);
16556 data << int32(val);
16557 SendDirectMessage(&data);
16561 if (apply)
16562 m_spellMods[mod->op].push_back(mod);
16563 else
16565 if (mod->charges == -1)
16566 --m_SpellModRemoveCount;
16567 m_spellMods[mod->op].remove(mod);
16568 delete mod;
16572 void Player::RemoveSpellMods(Spell const* spell)
16574 if(!spell || (m_SpellModRemoveCount == 0))
16575 return;
16577 for(int i=0;i<MAX_SPELLMOD;++i)
16579 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16581 SpellModifier *mod = *itr;
16582 ++itr;
16584 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16586 RemoveAurasDueToSpell(mod->spellId);
16587 if (m_spellMods[i].empty())
16588 break;
16589 else
16590 itr = m_spellMods[i].begin();
16596 // send Proficiency
16597 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16599 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16600 data << pr1 << pr2;
16601 GetSession()->SendPacket (&data);
16604 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16606 QueryResult *result = NULL;
16607 if(type==10)
16608 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16609 else
16610 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16611 if(result)
16613 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.
16614 { // and SendPetitionQueryOpcode reads data from the DB
16615 Field *fields = result->Fetch();
16616 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16617 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16619 // send update if charter owner in game
16620 Player* owner = objmgr.GetPlayer(ownerguid);
16621 if(owner)
16622 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16624 } while ( result->NextRow() );
16626 delete result;
16628 if(type==10)
16629 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16630 else
16631 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16634 CharacterDatabase.BeginTransaction();
16635 if(type == 10)
16637 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16638 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16640 else
16642 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16643 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16645 CharacterDatabase.CommitTransaction();
16648 void Player::LeaveAllArenaTeams(uint64 guid)
16650 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));
16651 if(!result)
16652 return;
16656 Field *fields = result->Fetch();
16657 uint32 at_id = fields[0].GetUInt32();
16658 if(at_id != 0)
16660 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16661 if(at)
16662 at->DelMember(guid);
16664 } while (result->NextRow());
16666 delete result;
16669 void Player::SetRestBonus (float rest_bonus_new)
16671 // Prevent resting on max level
16672 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16673 rest_bonus_new = 0;
16675 if(rest_bonus_new < 0)
16676 rest_bonus_new = 0;
16678 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16680 if(rest_bonus_new > rest_bonus_max)
16681 m_rest_bonus = rest_bonus_max;
16682 else
16683 m_rest_bonus = rest_bonus_new;
16685 // update data for client
16686 if(m_rest_bonus>10)
16687 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16688 else if(m_rest_bonus<=1)
16689 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16691 //RestTickUpdate
16692 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16695 void Player::HandleStealthedUnitsDetection()
16697 std::list<Unit*> stealthedUnits;
16699 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16700 Cell cell(p);
16701 cell.data.Part.reserved = ALL_DISTRICT;
16702 cell.SetNoCreate();
16704 MaNGOS::AnyStealthedCheck u_check;
16705 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16707 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16708 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16710 CellLock<GridReadGuard> cell_lock(cell, p);
16711 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16712 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16714 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16716 if((*i)==this)
16718 i = stealthedUnits.erase(i);
16719 continue;
16722 if ((*i)->isVisibleForOrDetect(this,true))
16725 (*i)->SendUpdateToPlayer(this);
16726 m_clientGUIDs.insert((*i)->GetGUID());
16728 #ifdef MANGOS_DEBUG
16729 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16730 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16731 #endif
16733 // target aura duration for caster show only if target exist at caster client
16734 // send data at target visibility change (adding to client)
16735 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16736 SendAurasForTarget(*i);
16738 i = stealthedUnits.erase(i);
16739 continue;
16742 ++i;
16746 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
16748 if(nodes.size() < 2)
16749 return false;
16751 // 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
16752 if(GetSession()->isLogingOut() || isInCombat())
16754 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16755 data << uint32(ERR_TAXIPLAYERBUSY);
16756 GetSession()->SendPacket(&data);
16757 return false;
16760 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16761 return false;
16763 // taximaster case
16764 if(npc)
16766 // not let cheating with start flight mounted
16767 if(IsMounted())
16769 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16770 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16771 GetSession()->SendPacket(&data);
16772 return false;
16775 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16777 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16778 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16779 GetSession()->SendPacket(&data);
16780 return false;
16783 // 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
16784 if(IsNonMeleeSpellCasted(false))
16786 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16787 data << uint32(ERR_TAXIPLAYERBUSY);
16788 GetSession()->SendPacket(&data);
16789 return false;
16792 // cast case or scripted call case
16793 else
16795 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
16797 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16798 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
16800 if(m_currentSpells[CURRENT_GENERIC_SPELL] && m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id != spellid)
16801 InterruptSpell(CURRENT_GENERIC_SPELL,false);
16803 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
16805 if(m_currentSpells[CURRENT_CHANNELED_SPELL] && m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id != spellid)
16806 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
16809 uint32 sourcenode = nodes[0];
16811 // starting node too far away (cheat?)
16812 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16813 if (!node)
16815 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16816 data << uint32(ERR_TAXINOSUCHPATH);
16817 GetSession()->SendPacket(&data);
16818 return false;
16821 // check node starting pos data set case if provided
16822 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
16824 if (node->map_id != GetMapId() ||
16825 (node->x - GetPositionX())*(node->x - GetPositionX())+
16826 (node->y - GetPositionY())*(node->y - GetPositionY())+
16827 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16828 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
16830 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16831 data << uint32(ERR_TAXITOOFARAWAY);
16832 GetSession()->SendPacket(&data);
16833 return false;
16836 // node must have pos if taxi master case (npc != NULL)
16837 else if (npc)
16839 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16840 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16841 GetSession()->SendPacket(&data);
16842 return false;
16845 // Prepare to flight start now
16847 // stop combat at start taxi flight if any
16848 CombatStop();
16850 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16851 TradeCancel(true);
16853 // clean not finished taxi path if any
16854 m_taxi.ClearTaxiDestinations();
16856 // 0 element current node
16857 m_taxi.AddTaxiDestination(sourcenode);
16859 // fill destinations path tail
16860 uint32 sourcepath = 0;
16861 uint32 totalcost = 0;
16863 uint32 prevnode = sourcenode;
16864 uint32 lastnode = 0;
16866 for(uint32 i = 1; i < nodes.size(); ++i)
16868 uint32 path, cost;
16870 lastnode = nodes[i];
16871 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16873 if(!path)
16875 m_taxi.ClearTaxiDestinations();
16876 return false;
16879 totalcost += cost;
16881 if(prevnode == sourcenode)
16882 sourcepath = path;
16884 m_taxi.AddTaxiDestination(lastnode);
16886 prevnode = lastnode;
16889 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
16890 uint32 mount_display_id = objmgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
16892 // in spell case allow 0 model
16893 if (mount_display_id == 0 && spellid == 0 || sourcepath == 0)
16895 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16896 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16897 GetSession()->SendPacket(&data);
16898 m_taxi.ClearTaxiDestinations();
16899 return false;
16902 uint32 money = GetMoney();
16904 if (npc)
16905 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16907 if(money < totalcost)
16909 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16910 data << uint32(ERR_TAXINOTENOUGHMONEY);
16911 GetSession()->SendPacket(&data);
16912 m_taxi.ClearTaxiDestinations();
16913 return false;
16916 //Checks and preparations done, DO FLIGHT
16917 ModifyMoney(-(int32)totalcost);
16918 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
16919 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
16921 // prevent stealth flight
16922 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16924 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16925 data << uint32(ERR_TAXIOK);
16926 GetSession()->SendPacket(&data);
16928 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16930 GetSession()->SendDoFlight(mount_display_id, sourcepath);
16932 return true;
16935 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
16937 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
16938 if(!entry)
16939 return false;
16941 std::vector<uint32> nodes;
16943 nodes.resize(2);
16944 nodes[0] = entry->from;
16945 nodes[1] = entry->to;
16947 return ActivateTaxiPathTo(nodes,NULL,spellid);
16950 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16952 // last check 2.0.10
16953 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16954 data << GetGUID();
16955 data << uint8(0x0); // flags (0x1, 0x2)
16956 time_t curTime = time(NULL);
16957 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16959 if (itr->second->state == PLAYERSPELL_REMOVED)
16960 continue;
16961 uint32 unSpellId = itr->first;
16962 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16963 if (!spellInfo)
16965 ASSERT(spellInfo);
16966 continue;
16969 // Not send cooldown for this spells
16970 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16971 continue;
16973 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16975 data << uint32(unSpellId);
16976 data << uint32(unTimeMs); // in m.secs
16977 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
16980 GetSession()->SendPacket(&data);
16983 void Player::InitDataForForm(bool reapplyMods)
16985 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16986 if(ssEntry && ssEntry->attackSpeed)
16988 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16989 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16990 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16992 else
16993 SetRegularAttackTime();
16995 switch(m_form)
16997 case FORM_CAT:
16999 if(getPowerType()!=POWER_ENERGY)
17000 setPowerType(POWER_ENERGY);
17001 break;
17003 case FORM_BEAR:
17004 case FORM_DIREBEAR:
17006 if(getPowerType()!=POWER_RAGE)
17007 setPowerType(POWER_RAGE);
17008 break;
17010 default: // 0, for example
17012 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17013 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17014 setPowerType(Powers(cEntry->powerType));
17015 break;
17019 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17020 if (!reapplyMods)
17021 UpdateEquipSpellsAtFormChange();
17023 UpdateAttackPowerAndDamage();
17024 UpdateAttackPowerAndDamage(true);
17027 // Return true is the bought item has a max count to force refresh of window by caller
17028 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
17030 // cheating attempt
17031 if(count < 1) count = 1;
17033 if(!isAlive())
17034 return false;
17036 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
17037 if( !pProto )
17039 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17040 return false;
17043 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
17044 if (!pCreature)
17046 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17047 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17048 return false;
17051 VendorItemData const* vItems = pCreature->GetVendorItems();
17052 if(!vItems || vItems->Empty())
17054 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17055 return false;
17058 size_t vendor_slot = vItems->FindItemSlot(item);
17059 if(vendor_slot >= vItems->GetItemCount())
17061 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17062 return false;
17065 VendorItem const* crItem = vItems->m_items[vendor_slot];
17067 // check current item amount if it limited
17068 if( crItem->maxcount != 0 )
17070 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17072 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17073 return false;
17077 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17079 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17080 return false;
17083 if(crItem->ExtendedCost)
17085 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17086 if(!iece)
17088 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17089 return false;
17092 // honor points price
17093 if(GetHonorPoints() < (iece->reqhonorpoints * count))
17095 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17096 return false;
17099 // arena points price
17100 if(GetArenaPoints() < (iece->reqarenapoints * count))
17102 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17103 return false;
17106 // item base price
17107 for (uint8 i = 0; i < 5; ++i)
17109 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17111 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17112 return false;
17116 // check for personal arena rating requirement
17117 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17119 // probably not the proper equip err
17120 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17121 return false;
17125 uint32 price = pProto->BuyPrice * count;
17127 // reputation discount
17128 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17130 if( GetMoney() < price )
17132 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17133 return false;
17136 uint8 bag = 0; // init for case invalid bagGUID
17138 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17140 Bag *pBag;
17141 if( bagguid == GetGUID() )
17143 bag = INVENTORY_SLOT_BAG_0;
17145 else
17147 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;++i)
17149 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17150 if( pBag )
17152 if( bagguid == pBag->GetGUID() )
17154 bag = i;
17155 break;
17162 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17164 ItemPosCountVec dest;
17165 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17166 if( msg != EQUIP_ERR_OK )
17168 SendEquipError( msg, NULL, NULL );
17169 return false;
17172 ModifyMoney( -(int32)price );
17173 if(crItem->ExtendedCost) // case for new honor system
17175 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17176 if(iece->reqhonorpoints)
17177 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17178 if(iece->reqarenapoints)
17179 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17180 for (uint8 i = 0; i < 5; ++i)
17182 if(iece->reqitem[i])
17183 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17187 if(Item *it = StoreNewItem( dest, item, true ))
17189 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17191 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17192 data << pCreature->GetGUID();
17193 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17194 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17195 data << (uint32)count;
17196 GetSession()->SendPacket(&data);
17198 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17201 else if( IsEquipmentPos( bag, slot ) )
17203 if(pProto->BuyCount * count != 1)
17205 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17206 return false;
17209 uint16 dest;
17210 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17211 if( msg != EQUIP_ERR_OK )
17213 SendEquipError( msg, NULL, NULL );
17214 return false;
17217 ModifyMoney( -(int32)price );
17218 if(crItem->ExtendedCost) // case for new honor system
17220 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17221 if(iece->reqhonorpoints)
17222 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17223 if(iece->reqarenapoints)
17224 ModifyArenaPoints( - int32(iece->reqarenapoints));
17225 for (uint8 i = 0; i < 5; ++i)
17227 if(iece->reqitem[i])
17228 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17232 if(Item *it = EquipNewItem( dest, item, true ))
17234 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17236 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17237 data << pCreature->GetGUID();
17238 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17239 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17240 data << (uint32)count;
17241 GetSession()->SendPacket(&data);
17243 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17245 AutoUnequipOffhandIfNeed();
17248 else
17250 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17251 return false;
17254 return crItem->maxcount!=0;
17257 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17259 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17260 // the personal rating of the arena team must match the required limit as well
17261 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17262 uint32 max_personal_rating = 0;
17263 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17265 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17267 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17268 uint32 t_rating = at->GetRating();
17269 p_rating = p_rating<t_rating? p_rating : t_rating;
17270 if(max_personal_rating < p_rating)
17271 max_personal_rating = p_rating;
17274 return max_personal_rating;
17277 void Player::UpdateHomebindTime(uint32 time)
17279 // GMs never get homebind timer online
17280 if (m_InstanceValid || isGameMaster())
17282 if(m_HomebindTimer) // instance valid, but timer not reset
17284 // hide reminder
17285 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17286 data << uint32(0);
17287 data << uint32(0);
17288 GetSession()->SendPacket(&data);
17290 // instance is valid, reset homebind timer
17291 m_HomebindTimer = 0;
17293 else if (m_HomebindTimer > 0)
17295 if (time >= m_HomebindTimer)
17297 // teleport to nearest graveyard
17298 RepopAtGraveyard();
17300 else
17301 m_HomebindTimer -= time;
17303 else
17305 // instance is invalid, start homebind timer
17306 m_HomebindTimer = 60000;
17307 // send message to player
17308 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17309 data << m_HomebindTimer;
17310 data << uint32(1);
17311 GetSession()->SendPacket(&data);
17312 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17316 void Player::UpdatePvP(bool state, bool ovrride)
17318 if(!state || ovrride)
17320 SetPvP(state);
17321 pvpInfo.endTimer = 0;
17323 else
17325 if(pvpInfo.endTimer != 0)
17326 pvpInfo.endTimer = time(NULL);
17327 else
17328 SetPvP(state);
17332 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17334 // init cooldown values
17335 uint32 cat = 0;
17336 int32 rec = -1;
17337 int32 catrec = -1;
17339 // some special item spells without correct cooldown in SpellInfo
17340 // cooldown information stored in item prototype
17341 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17343 if(itemId)
17345 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17347 for(int idx = 0; idx < 5; ++idx)
17349 if(proto->Spells[idx].SpellId == spellInfo->Id)
17351 cat = proto->Spells[idx].SpellCategory;
17352 rec = proto->Spells[idx].SpellCooldown;
17353 catrec = proto->Spells[idx].SpellCategoryCooldown;
17354 break;
17360 // if no cooldown found above then base at DBC data
17361 if(rec < 0 && catrec < 0)
17363 cat = spellInfo->Category;
17364 rec = spellInfo->RecoveryTime;
17365 catrec = spellInfo->CategoryRecoveryTime;
17368 time_t curTime = time(NULL);
17370 time_t catrecTime;
17371 time_t recTime;
17373 // overwrite time for selected category
17374 if(infinityCooldown)
17376 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17377 // but not allow ignore until reset or re-login
17378 catrecTime = catrec > 0 ? curTime+MONTH : 0;
17379 recTime = rec > 0 ? curTime+MONTH : catrecTime;
17381 else
17383 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17384 // prevent 0 cooldowns set by another way
17385 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17386 rec = GetAttackTime(RANGED_ATTACK);
17388 // Now we have cooldown data (if found any), time to apply mods
17389 if(rec > 0)
17390 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17392 if(catrec > 0)
17393 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17395 // replace negative cooldowns by 0
17396 if (rec < 0) rec = 0;
17397 if (catrec < 0) catrec = 0;
17399 // no cooldown after applying spell mods
17400 if( rec == 0 && catrec == 0)
17401 return;
17403 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17404 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17407 // self spell cooldown
17408 if(recTime > 0)
17409 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17411 // category spells
17412 if (cat && catrec > 0)
17414 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17415 if(i_scstore != sSpellCategoryStore.end())
17417 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17419 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17420 continue;
17422 AddSpellCooldown(*i_scset, itemId, catrecTime);
17428 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17430 SpellCooldown sc;
17431 sc.end = end_time;
17432 sc.itemid = itemid;
17433 m_spellCooldowns[spellid] = sc;
17436 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17438 // start cooldowns at server side, if any
17439 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17441 // Send activate cooldown timer (possible 0) at client side
17442 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17443 data << spellInfo->Id;
17444 data << GetGUID();
17445 SendDirectMessage(&data);
17448 void Player::UpdatePotionCooldown(Spell* spell)
17450 // no potion used i combat or still in combat
17451 if(!m_lastPotionId || isInCombat())
17452 return;
17454 // Call not from spell cast, send cooldown event for item spells if no in combat
17455 if(!spell)
17457 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17458 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17459 for(int idx = 0; idx < 5; ++idx)
17460 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17461 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17462 SendCooldownEvent(spellInfo,m_lastPotionId);
17464 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17465 else
17466 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17468 m_lastPotionId = 0;
17471 //slot to be excluded while counting
17472 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17474 if(!enchantmentcondition)
17475 return true;
17477 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17479 if(!Condition)
17480 return true;
17482 uint8 curcount[4] = {0, 0, 0, 0};
17484 //counting current equipped gem colors
17485 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17487 if(i == slot)
17488 continue;
17489 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17490 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17492 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17494 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17495 if(!enchant_id)
17496 continue;
17498 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17499 if(!enchantEntry)
17500 continue;
17502 uint32 gemid = enchantEntry->GemID;
17503 if(!gemid)
17504 continue;
17506 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17507 if(!gemProto)
17508 continue;
17510 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17511 if(!gemProperty)
17512 continue;
17514 uint8 GemColor = gemProperty->color;
17516 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17518 if(tmpcolormask & GemColor)
17519 ++curcount[b];
17525 bool activate = true;
17527 for(int i = 0; i < 5; ++i)
17529 if(!Condition->Color[i])
17530 continue;
17532 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17534 // if have <CompareColor> use them as count, else use <value> from Condition
17535 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17537 switch(Condition->Comparator[i])
17539 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17540 activate &= (_cur_gem < _cmp_gem) ? true : false;
17541 break;
17542 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17543 activate &= (_cur_gem > _cmp_gem) ? true : false;
17544 break;
17545 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17546 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17547 break;
17551 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");
17553 return activate;
17556 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17558 //cycle all equipped items
17559 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17561 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17562 if(slot == exceptslot)
17563 continue;
17565 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17567 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17568 continue;
17570 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17572 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17573 if(!enchant_id)
17574 continue;
17576 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17577 if(!enchantEntry)
17578 continue;
17580 uint32 condition = enchantEntry->EnchantmentCondition;
17581 if(condition)
17583 //was enchant active with/without item?
17584 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17585 //should it now be?
17586 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17588 // ignore item gem conditions
17589 //if state changed, (dis)apply enchant
17590 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17597 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17598 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17600 //cycle all equipped items
17601 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17603 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17604 if(slot == exceptslot)
17605 continue;
17607 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17609 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17610 continue;
17612 //cycle all (gem)enchants
17613 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17615 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17616 if(!enchant_id) //if no enchant go to next enchant(slot)
17617 continue;
17619 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17620 if(!enchantEntry)
17621 continue;
17623 //only metagems to be (de)activated, so only enchants with condition
17624 uint32 condition = enchantEntry->EnchantmentCondition;
17625 if(condition)
17626 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17631 void Player::LeaveBattleground(bool teleportToEntryPoint)
17633 if(BattleGround *bg = GetBattleGround())
17635 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17637 // call after remove to be sure that player resurrected for correct cast
17638 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17640 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17641 CastSpell(this, 26013, true); // Deserter
17646 bool Player::CanJoinToBattleground() const
17648 // check Deserter debuff
17649 if(GetDummyAura(26013))
17650 return false;
17652 return true;
17655 bool Player::CanReportAfkDueToLimit()
17657 // a player can complain about 15 people per 5 minutes
17658 if(m_bgAfkReportedCount >= 15)
17659 return false;
17660 ++m_bgAfkReportedCount;
17661 return true;
17664 ///This player has been blamed to be inactive in a battleground
17665 void Player::ReportedAfkBy(Player* reporter)
17667 BattleGround *bg = GetBattleGround();
17668 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17669 return;
17671 // check if player has 'Idle' or 'Inactive' debuff
17672 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17674 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17675 // 3 players have to complain to apply debuff
17676 if(m_bgAfkReporter.size() >= 3)
17678 // cast 'Idle' spell
17679 CastSpell(this, 43680, true);
17680 m_bgAfkReporter.clear();
17685 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17687 // gamemaster in GM mode see all, including ghosts
17688 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17689 return true;
17691 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17692 if (InBattleGround())
17694 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17695 return false;
17696 return true;
17699 // Live player see live player or dead player with not realized corpse
17700 if(pl->isAlive() || pl->m_deathTimer > 0)
17702 return isAlive() || m_deathTimer > 0;
17705 // Ghost see other friendly ghosts, that's for sure
17706 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17707 return true;
17709 // Dead player see live players near own corpse
17710 if(isAlive())
17712 Corpse *corpse = pl->GetCorpse();
17713 if(corpse)
17715 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17716 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17717 return true;
17721 // and not see any other
17722 return false;
17725 bool Player::IsVisibleGloballyFor( Player* u ) const
17727 if(!u)
17728 return false;
17730 // Always can see self
17731 if (u==this)
17732 return true;
17734 // Visible units, always are visible for all players
17735 if (GetVisibility() == VISIBILITY_ON)
17736 return true;
17738 // GMs are visible for higher gms (or players are visible for gms)
17739 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17740 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17742 // non faction visibility non-breakable for non-GMs
17743 if (GetVisibility() == VISIBILITY_OFF)
17744 return false;
17746 // non-gm stealth/invisibility not hide from global player lists
17747 return true;
17750 void Player::UpdateVisibilityOf(WorldObject* target)
17752 if(HaveAtClient(target))
17754 if(!target->isVisibleForInState(this,true))
17756 target->DestroyForPlayer(this);
17757 m_clientGUIDs.erase(target->GetGUID());
17759 #ifdef MANGOS_DEBUG
17760 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17761 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17762 #endif
17765 else
17767 if(target->isVisibleForInState(this,false))
17769 target->SendUpdateToPlayer(this);
17770 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17771 m_clientGUIDs.insert(target->GetGUID());
17773 #ifdef MANGOS_DEBUG
17774 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17775 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17776 #endif
17778 // target aura duration for caster show only if target exist at caster client
17779 // send data at target visibility change (adding to client)
17780 if(target!=this && target->isType(TYPEMASK_UNIT))
17781 SendAurasForTarget((Unit*)target);
17783 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17784 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17789 template<class T>
17790 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17792 s64.insert(target->GetGUID());
17795 template<>
17796 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17798 if(!target->IsTransport())
17799 s64.insert(target->GetGUID());
17802 template<class T>
17803 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17805 if(HaveAtClient(target))
17807 if(!target->isVisibleForInState(this,true))
17809 target->BuildOutOfRangeUpdateBlock(&data);
17810 m_clientGUIDs.erase(target->GetGUID());
17812 #ifdef MANGOS_DEBUG
17813 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17814 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));
17815 #endif
17818 else
17820 if(target->isVisibleForInState(this,false))
17822 visibleNow.insert(target);
17823 target->BuildUpdate(data_updates);
17824 target->BuildCreateUpdateBlockForPlayer(&data, this);
17825 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17827 #ifdef MANGOS_DEBUG
17828 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17829 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));
17830 #endif
17835 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17836 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17837 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17838 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17839 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17841 void Player::InitPrimaryProfessions()
17843 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17846 void Player::SendComboPoints()
17848 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17849 if (combotarget)
17851 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17852 data.append(combotarget->GetPackGUID());
17853 data << uint8(m_comboPoints);
17854 GetSession()->SendPacket(&data);
17858 void Player::AddComboPoints(Unit* target, int8 count)
17860 if(!count)
17861 return;
17863 // without combo points lost (duration checked in aura)
17864 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17866 if(target->GetGUID() == m_comboTarget)
17868 m_comboPoints += count;
17870 else
17872 if(m_comboTarget)
17873 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
17874 target2->RemoveComboPointHolder(GetGUIDLow());
17876 m_comboTarget = target->GetGUID();
17877 m_comboPoints = count;
17879 target->AddComboPointHolder(GetGUIDLow());
17882 if (m_comboPoints > 5) m_comboPoints = 5;
17883 if (m_comboPoints < 0) m_comboPoints = 0;
17885 SendComboPoints();
17888 void Player::ClearComboPoints()
17890 if(!m_comboTarget)
17891 return;
17893 // without combopoints lost (duration checked in aura)
17894 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17896 m_comboPoints = 0;
17898 SendComboPoints();
17900 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17901 target->RemoveComboPointHolder(GetGUIDLow());
17903 m_comboTarget = 0;
17906 void Player::SetGroup(Group *group, int8 subgroup)
17908 if(group == NULL)
17909 m_group.unlink();
17910 else
17912 // never use SetGroup without a subgroup unless you specify NULL for group
17913 assert(subgroup >= 0);
17914 m_group.link(group, this);
17915 m_group.setSubGroup((uint8)subgroup);
17919 void Player::SendInitialPacketsBeforeAddToMap()
17921 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17922 data << uint32(0); // unknown, may be rest state time or experience
17923 GetSession()->SendPacket(&data);
17925 GetSocial()->SendSocialList();
17927 // Homebind
17928 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17929 data << m_homebindX << m_homebindY << m_homebindZ;
17930 data << (uint32) m_homebindMapId;
17931 data << (uint32) m_homebindZoneId;
17932 GetSession()->SendPacket(&data);
17934 // SMSG_SET_PROFICIENCY
17935 // SMSG_UPDATE_AURA_DURATION
17937 SendTalentsInfoData(false);
17938 SendInitialSpells();
17940 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17941 data << uint32(0); // count, for(count) uint32;
17942 GetSession()->SendPacket(&data);
17944 SendInitialActionButtons();
17945 m_reputationMgr.SendInitialReputations();
17946 m_achievementMgr.SendAllAchievementData();
17948 // update zone
17949 uint32 newzone, newarea;
17950 GetZoneAndAreaId(newzone,newarea);
17951 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
17953 SendEquipmentSetList();
17955 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
17956 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17957 data << (float)0.01666667f; // game speed
17958 data << uint32(0); // added in 3.1.2
17959 GetSession()->SendPacket( &data );
17961 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17962 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17963 m_movementInfo.flags |= MOVEMENTFLAG_FLYING2;
17965 m_mover = this;
17968 void Player::SendInitialPacketsAfterAddToMap()
17970 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17971 data << uint32(0x00000000); // on blizz it increments periodically
17972 GetSession()->SendPacket(&data);
17974 CastSpell(this, 836, true); // LOGINEFFECT
17976 // set some aura effects that send packet to player client after add player to map
17977 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17978 // same auras state lost at far teleport, send it one more time in this case also
17979 static const AuraType auratypes[] =
17981 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17982 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17983 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17985 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17987 Unit::AuraList const& auraList = GetAurasByType(*itr);
17988 if(!auraList.empty())
17989 auraList.front()->ApplyModifier(true,true);
17992 if(HasAuraType(SPELL_AURA_MOD_STUN))
17993 SetMovement(MOVE_ROOT);
17995 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17996 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17998 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
17999 data2.append(GetPackGUID());
18000 data2 << (uint32)2;
18001 SendMessageToSet(&data2,true);
18004 SendAurasForTarget(this);
18005 SendEnchantmentDurations(); // must be after add to map
18006 SendItemDurations(); // must be after add to map
18009 void Player::SendUpdateToOutOfRangeGroupMembers()
18011 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18012 return;
18013 if(Group* group = GetGroup())
18014 group->UpdatePlayerOutOfRange(this);
18016 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18017 m_auraUpdateMask = 0;
18018 if(Pet *pet = GetPet())
18019 pet->ResetAuraUpdateMask();
18022 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18024 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18025 data << uint32(mapid);
18026 data << uint8(reason); // transfer abort reason
18027 switch(reason)
18029 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18030 case TRANSFER_ABORT_DIFFICULTY:
18031 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18032 data << uint8(arg);
18033 break;
18035 GetSession()->SendPacket(&data);
18038 void Player::SendInstanceResetWarning( uint32 mapid, uint32 difficulty, uint32 time )
18040 // type of warning, based on the time remaining until reset
18041 uint32 type;
18042 if(time > 3600)
18043 type = RAID_INSTANCE_WELCOME;
18044 else if(time > 900 && time <= 3600)
18045 type = RAID_INSTANCE_WARNING_HOURS;
18046 else if(time > 300 && time <= 900)
18047 type = RAID_INSTANCE_WARNING_MIN;
18048 else
18049 type = RAID_INSTANCE_WARNING_MIN_SOON;
18051 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
18052 data << uint32(type);
18053 data << uint32(mapid);
18054 data << uint32(difficulty); // difficulty
18055 data << uint32(time);
18056 if(type == RAID_INSTANCE_WELCOME)
18058 data << uint8(0); // is your (1)
18059 data << uint8(0); // is extended (1), ignored if prev field is 0
18061 GetSession()->SendPacket(&data);
18064 void Player::ApplyEquipCooldown( Item * pItem )
18066 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
18068 _Spell const& spellData = pItem->GetProto()->Spells[i];
18070 // no spell
18071 if( !spellData.SpellId )
18072 continue;
18074 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18075 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18076 continue;
18078 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18080 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18081 data << pItem->GetGUID();
18082 data << uint32(spellData.SpellId);
18083 GetSession()->SendPacket(&data);
18087 void Player::resetSpells()
18089 // not need after this call
18090 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18092 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
18093 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
18096 // make full copy of map (spells removed and marked as deleted at another spell remove
18097 // and we can't use original map for safe iterative with visit each spell at loop end
18098 PlayerSpellMap smap = GetSpellMap();
18100 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18101 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
18103 learnDefaultSpells();
18104 learnQuestRewardedSpells();
18107 void Player::learnDefaultSpells()
18109 // learn default race/class spells
18110 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18111 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18113 uint32 tspell = *itr;
18114 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18115 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18116 addSpell(tspell,true,true,true,false);
18117 else // but send in normal spell in game learn case
18118 learnSpell(tspell,true);
18122 void Player::learnQuestRewardedSpells(Quest const* quest)
18124 uint32 spell_id = quest->GetRewSpellCast();
18126 // skip quests without rewarded spell
18127 if( !spell_id )
18128 return;
18130 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18131 if(!spellInfo)
18132 return;
18134 // check learned spells state
18135 bool found = false;
18136 for(int i=0; i < 3; ++i)
18138 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18140 found = true;
18141 break;
18145 // skip quests with not teaching spell or already known spell
18146 if(!found)
18147 return;
18149 // prevent learn non first rank unknown profession and second specialization for same profession)
18150 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18151 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18153 // not have first rank learned (unlearned prof?)
18154 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18155 if( !HasSpell(first_spell) )
18156 return;
18158 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18159 if(!learnedInfo)
18160 return;
18162 // specialization
18163 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18165 // search other specialization for same prof
18166 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18168 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18169 continue;
18171 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18172 if(!itrInfo)
18173 return;
18175 // compare only specializations
18176 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18177 continue;
18179 // compare same chain spells
18180 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18181 continue;
18183 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18184 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18185 return;
18190 CastSpell( this, spell_id, true);
18193 void Player::learnQuestRewardedSpells()
18195 // learn spells received from quest completing
18196 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18198 // skip no rewarded quests
18199 if(!itr->second.m_rewarded)
18200 continue;
18202 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18203 if( !quest )
18204 continue;
18206 learnQuestRewardedSpells(quest);
18210 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18212 uint32 raceMask = getRaceMask();
18213 uint32 classMask = getClassMask();
18214 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18216 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18217 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18218 continue;
18219 // Check race if set
18220 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18221 continue;
18222 // Check class if set
18223 if (pAbility->classmask && !(pAbility->classmask & classMask))
18224 continue;
18226 if (sSpellStore.LookupEntry(pAbility->spellId))
18228 // need unlearn spell
18229 if (skill_value < pAbility->req_skill_value)
18230 removeSpell(pAbility->spellId);
18231 // need learn
18232 else if (!IsInWorld())
18233 addSpell(pAbility->spellId,true,true,true,false);
18234 else
18235 learnSpell(pAbility->spellId,true);
18240 void Player::SendAurasForTarget(Unit *target)
18242 if(target->GetVisibleAuras()->empty()) // speedup things
18243 return;
18245 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18246 data.append(target->GetPackGUID());
18248 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18249 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18251 for(uint32 j = 0; j < 3; ++j)
18253 if(Aura *aura = target->GetAura(itr->second, j))
18255 data << uint8(aura->GetAuraSlot());
18256 data << uint32(aura->GetId());
18258 if(aura->GetId())
18260 uint8 auraFlags = aura->GetAuraFlags();
18261 // flags
18262 data << uint8(auraFlags);
18263 // level
18264 data << uint8(aura->GetAuraLevel());
18265 // charges
18266 data << uint8(aura->GetAuraCharges());
18268 if(!(auraFlags & AFLAG_NOT_CASTER))
18270 data << uint8(0); // packed GUID of someone (caster?)
18273 if(auraFlags & AFLAG_DURATION) // include aura duration
18275 data << uint32(aura->GetAuraMaxDuration());
18276 data << uint32(aura->GetAuraDuration());
18279 break;
18284 GetSession()->SendPacket(&data);
18287 void Player::SetDailyQuestStatus( uint32 quest_id )
18289 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18291 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18293 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18294 m_lastDailyQuestTime = time(NULL); // last daily quest time
18295 m_DailyQuestChanged = true;
18296 break;
18301 void Player::ResetDailyQuestStatus()
18303 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18304 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18306 // DB data deleted in caller
18307 m_DailyQuestChanged = false;
18308 m_lastDailyQuestTime = 0;
18311 BattleGround* Player::GetBattleGround() const
18313 if(GetBattleGroundId()==0)
18314 return NULL;
18316 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
18319 bool Player::InArena() const
18321 BattleGround *bg = GetBattleGround();
18322 if(!bg || !bg->isArena())
18323 return false;
18325 return true;
18328 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18330 // get a template bg instead of running one
18331 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18332 if(!bg)
18333 return false;
18335 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18336 return false;
18338 return true;
18341 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18343 //returned to hardcoded version of this function, because there is no way to code it dynamic
18344 uint32 level = getLevel();
18345 if( bgTypeId == BATTLEGROUND_AV )
18346 level--;
18348 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18349 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18351 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18352 return QUEUE_ID_MAX_LEVEL_80;
18354 return BGQueueIdBasedOnLevel(queue_id);
18357 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18359 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18360 if(!vendor_faction || !vendor_faction->faction)
18361 return 1.0f;
18363 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18364 if(rank <= REP_NEUTRAL)
18365 return 1.0f;
18367 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18370 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18372 uint32 racemask = getRaceMask();
18373 uint32 classmask = getClassMask();
18375 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18376 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18377 if(lower==upper)
18378 return true;
18380 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18382 // skip wrong race skills
18383 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18384 continue;
18386 // skip wrong class skills
18387 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18388 continue;
18390 return true;
18393 return false;
18396 bool Player::HasQuestForGO(int32 GOId) const
18398 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18400 uint32 questid = GetQuestSlotQuestId(i);
18401 if ( questid == 0 )
18402 continue;
18404 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18405 if(qs_itr == mQuestStatus.end())
18406 continue;
18408 QuestStatusData const& qs = qs_itr->second;
18410 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18412 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18413 if(!qinfo)
18414 continue;
18416 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18417 continue;
18419 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
18421 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18422 continue;
18424 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18425 return true;
18429 return false;
18432 void Player::UpdateForQuestWorldObjects()
18434 if(m_clientGUIDs.empty())
18435 return;
18437 UpdateData udata;
18438 WorldPacket packet;
18439 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18441 if(IS_GAMEOBJECT_GUID(*itr))
18443 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18444 if(obj)
18445 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18447 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
18449 Creature *obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
18450 if(!obj)
18451 continue;
18453 // check if this unit requires quest specific flags
18454 if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
18455 continue;
18457 SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(obj->GetEntry());
18458 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
18460 if(itr->second.questStart || itr->second.questEnd)
18462 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
18463 break;
18468 udata.BuildPacket(&packet);
18469 GetSession()->SendPacket(&packet);
18472 void Player::SummonIfPossible(bool agree)
18474 if(!agree)
18476 m_summon_expire = 0;
18477 return;
18480 // expire and auto declined
18481 if(m_summon_expire < time(NULL))
18482 return;
18484 // stop taxi flight at summon
18485 if(isInFlight())
18487 GetMotionMaster()->MovementExpired();
18488 m_taxi.ClearTaxiDestinations();
18491 // drop flag at summon
18492 // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
18493 if(BattleGround *bg = GetBattleGround())
18494 bg->EventPlayerDroppedFlag(this);
18496 m_summon_expire = 0;
18498 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
18500 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18503 void Player::RemoveItemDurations( Item *item )
18505 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18507 if(*itr==item)
18509 m_itemDuration.erase(itr);
18510 break;
18515 void Player::AddItemDurations( Item *item )
18517 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18519 m_itemDuration.push_back(item);
18520 item->SendTimeUpdate(this);
18524 void Player::AutoUnequipOffhandIfNeed()
18526 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18527 if(!offItem)
18528 return;
18530 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18531 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18532 return;
18534 ItemPosCountVec off_dest;
18535 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18536 if( off_msg == EQUIP_ERR_OK )
18538 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18539 StoreItem( off_dest, offItem, true );
18541 else
18543 MailItemsInfo mi;
18544 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18545 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18546 CharacterDatabase.BeginTransaction();
18547 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18548 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18549 CharacterDatabase.CommitTransaction();
18551 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18552 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18556 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18558 if(spellInfo->EquippedItemClass < 0)
18559 return true;
18561 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18562 // for optimize check 2 used cases only
18563 switch(spellInfo->EquippedItemClass)
18565 case ITEM_CLASS_WEAPON:
18567 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18568 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18569 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18570 return true;
18571 break;
18573 case ITEM_CLASS_ARMOR:
18575 // tabard not have dependent spells
18576 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18577 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18578 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18579 return true;
18581 // shields can be equipped to offhand slot
18582 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18583 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18584 return true;
18586 // ranged slot can have some armor subclasses
18587 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18588 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18589 return true;
18591 break;
18593 default:
18594 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18595 break;
18598 return false;
18601 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18603 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18604 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18605 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18606 return true;
18608 // Check no reagent use mask
18609 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18610 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18611 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18612 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18613 return true;
18615 return false;
18618 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18620 AuraMap& auras = GetAuras();
18621 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
18623 Aura* aura = itr->second;
18625 // skip passive (passive item dependent spells work in another way) and not self applied auras
18626 SpellEntry const* spellInfo = aura->GetSpellProto();
18627 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18629 ++itr;
18630 continue;
18633 // skip if not item dependent or have alternative item
18634 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18636 ++itr;
18637 continue;
18640 // no alt item, remove aura, restart check
18641 RemoveAurasDueToSpell(aura->GetId());
18642 itr = auras.begin();
18645 // currently casted spells can be dependent from item
18646 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
18648 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18649 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18650 InterruptSpell(i);
18654 uint32 Player::GetResurrectionSpellId()
18656 // search priceless resurrection possibilities
18657 uint32 prio = 0;
18658 uint32 spell_id = 0;
18659 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18660 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18662 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18663 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18665 switch((*itr)->GetId())
18667 case 20707: spell_id = 3026; break; // rank 1
18668 case 20762: spell_id = 20758; break; // rank 2
18669 case 20763: spell_id = 20759; break; // rank 3
18670 case 20764: spell_id = 20760; break; // rank 4
18671 case 20765: spell_id = 20761; break; // rank 5
18672 case 27239: spell_id = 27240; break; // rank 6
18673 case 47883: spell_id = 47882; break; // rank 7
18674 default:
18675 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
18676 continue;
18679 prio = 3;
18681 // Twisting Nether // prio: 2 (max)
18682 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18684 prio = 2;
18685 spell_id = 23700;
18689 // Reincarnation (passive spell) // prio: 1
18690 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18691 spell_id = 21169;
18693 return spell_id;
18696 // Used in triggers for check "Only to targets that grant experience or honor" req
18697 bool Player::isHonorOrXPTarget(Unit* pVictim)
18699 uint32 v_level = pVictim->getLevel();
18700 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18702 // Victim level less gray level
18703 if(v_level<=k_grey)
18704 return false;
18706 if(pVictim->GetTypeId() == TYPEID_UNIT)
18708 if (((Creature*)pVictim)->isTotem() ||
18709 ((Creature*)pVictim)->isPet() ||
18710 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18711 return false;
18713 return true;
18716 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18718 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18720 // prepare data for near group iteration (PvP and !PvP cases)
18721 uint32 xp = 0;
18722 bool honored_kill = false;
18724 if(Group *pGroup = GetGroup())
18726 uint32 count = 0;
18727 uint32 sum_level = 0;
18728 Player* member_with_max_level = NULL;
18729 Player* not_gray_member_with_max_level = NULL;
18731 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18733 if(member_with_max_level)
18735 /// not get Xp in PvP or no not gray players in group
18736 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18738 /// skip in check PvP case (for speed, not used)
18739 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18740 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18741 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18743 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18745 Player* pGroupGuy = itr->getSource();
18746 if(!pGroupGuy)
18747 continue;
18749 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18750 continue; // member (alive or dead) or his corpse at req. distance
18752 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18753 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18754 honored_kill = true;
18756 // xp and reputation only in !PvP case
18757 if(!PvP)
18759 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18761 // if is in dungeon then all receive full reputation at kill
18762 // rewarded any alive/dead/near_corpse group member
18763 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18765 // XP updated only for alive group member
18766 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18767 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18769 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18771 pGroupGuy->GiveXP(itr_xp, pVictim);
18772 if(Pet* pet = pGroupGuy->GetPet())
18773 pet->GivePetXP(itr_xp/2);
18776 // quest objectives updated only for alive group member or dead but with not released body
18777 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18779 // normal creature (not pet/etc) can be only in !PvP case
18780 if(pVictim->GetTypeId()==TYPEID_UNIT)
18781 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18787 else // if (!pGroup)
18789 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18791 // honor can be in PvP and !PvP (racial leader) cases
18792 if(RewardHonor(pVictim,1))
18793 honored_kill = true;
18795 // xp and reputation only in !PvP case
18796 if(!PvP)
18798 RewardReputation(pVictim,1);
18799 GiveXP(xp, pVictim);
18801 if(Pet* pet = GetPet())
18802 pet->GivePetXP(xp);
18804 // normal creature (not pet/etc) can be only in !PvP case
18805 if(pVictim->GetTypeId()==TYPEID_UNIT)
18806 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18809 return xp || honored_kill;
18812 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
18814 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
18816 // prepare data for near group iteration
18817 if(Group *pGroup = GetGroup())
18819 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18821 Player* pGroupGuy = itr->getSource();
18822 if(!pGroupGuy)
18823 continue;
18825 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
18826 continue; // member (alive or dead) or his corpse at req. distance
18828 // quest objectives updated only for alive group member or dead but with not released body
18829 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18830 pGroupGuy->KilledMonster(creature_id, creature_guid);
18833 else // if (!pGroup)
18834 KilledMonster(creature_id, creature_guid);
18837 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18839 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
18840 return true;
18842 if (isAlive())
18843 return false;
18845 Corpse* corpse = GetCorpse();
18846 if (!corpse)
18847 return false;
18849 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
18852 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18854 Item* item = GetWeaponForAttack(attType,true);
18856 // unarmed only with base attack
18857 if(attType != BASE_ATTACK && !item)
18858 return 0;
18860 // weapon skill or (unarmed for base attack)
18861 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
18862 return GetBaseSkillValue(skill);
18865 void Player::ResurectUsingRequestData()
18867 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
18868 if(IS_PLAYER_GUID(m_resurrectGUID))
18869 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18871 ResurrectPlayer(0.0f,false);
18873 if(GetMaxHealth() > m_resurrectHealth)
18874 SetHealth( m_resurrectHealth );
18875 else
18876 SetHealth( GetMaxHealth() );
18878 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18879 SetPower(POWER_MANA, m_resurrectMana );
18880 else
18881 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18883 SetPower(POWER_RAGE, 0 );
18885 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18887 SpawnCorpseBones();
18890 void Player::SetClientControl(Unit* target, uint8 allowMove)
18892 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18893 data.append(target->GetPackGUID());
18894 data << uint8(allowMove);
18895 GetSession()->SendPacket(&data);
18898 void Player::UpdateZoneDependentAuras( uint32 newZone )
18900 // remove new continent flight forms
18901 if( !IsAllowUseFlyMountsHere() )
18903 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18904 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18907 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18908 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
18909 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18910 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
18911 if( !HasAura(itr->second->spellId,0) )
18912 CastSpell(this,itr->second->spellId,true);
18915 void Player::UpdateAreaDependentAuras( uint32 newArea )
18917 // remove auras from spells with area limitations
18918 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18920 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18921 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
18922 RemoveAura(iter);
18923 else
18924 ++iter;
18927 // some auras applied at subzone enter
18928 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
18929 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18930 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
18931 if( !HasAura(itr->second->spellId,0) )
18932 CastSpell(this,itr->second->spellId,true);
18935 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18937 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18938 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18940 return copseReclaimDelay[0];
18943 time_t now = time(NULL);
18944 // 0..2 full period
18945 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18946 return copseReclaimDelay[count];
18949 void Player::UpdateCorpseReclaimDelay()
18951 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18953 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18954 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18955 return;
18957 time_t now = time(NULL);
18958 if(now < m_deathExpireTime)
18960 // full and partly periods 1..3
18961 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18962 if(count < MAX_DEATH_COUNT)
18963 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18964 else
18965 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18967 else
18968 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18971 void Player::SendCorpseReclaimDelay(bool load)
18973 Corpse* corpse = GetCorpse();
18974 if(!corpse)
18975 return;
18977 uint32 delay;
18978 if(load)
18980 if(corpse->GetGhostTime() > m_deathExpireTime)
18981 return;
18983 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18985 uint32 count;
18986 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18987 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18989 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18990 if(count>=MAX_DEATH_COUNT)
18991 count = MAX_DEATH_COUNT-1;
18993 else
18994 count=0;
18996 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18998 time_t now = time(NULL);
18999 if(now >= expected_time)
19000 return;
19002 delay = expected_time-now;
19004 else
19005 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19007 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19008 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19009 data << uint32(delay*IN_MILISECONDS);
19010 GetSession()->SendPacket( &data );
19013 Player* Player::GetNextRandomRaidMember(float radius)
19015 Group *pGroup = GetGroup();
19016 if(!pGroup)
19017 return NULL;
19019 std::vector<Player*> nearMembers;
19020 nearMembers.reserve(pGroup->GetMembersCount());
19022 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19024 Player* Target = itr->getSource();
19026 // IsHostileTo check duel and controlled by enemy
19027 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19028 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19029 nearMembers.push_back(Target);
19032 if (nearMembers.empty())
19033 return NULL;
19035 uint32 randTarget = urand(0,nearMembers.size()-1);
19036 return nearMembers[randTarget];
19039 PartyResult Player::CanUninviteFromGroup() const
19041 const Group* grp = GetGroup();
19042 if(!grp)
19043 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19045 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19046 return PARTY_RESULT_YOU_NOT_LEADER;
19048 if(InBattleGround())
19049 return PARTY_RESULT_INVITE_RESTRICTED;
19051 return PARTY_RESULT_OK;
19054 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
19056 //we must move references from m_group to m_originalGroup
19057 SetOriginalGroup(GetGroup(), GetSubGroup());
19059 m_group.unlink();
19060 m_group.link(group, this);
19061 m_group.setSubGroup((uint8)subgroup);
19064 void Player::RemoveFromBattleGroundRaid()
19066 //remove existing reference
19067 m_group.unlink();
19068 if( Group* group = GetOriginalGroup() )
19070 m_group.link(group, this);
19071 m_group.setSubGroup(GetOriginalSubGroup());
19073 SetOriginalGroup(NULL);
19076 void Player::SetOriginalGroup(Group *group, int8 subgroup)
19078 if( group == NULL )
19079 m_originalGroup.unlink();
19080 else
19082 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19083 assert(subgroup >= 0);
19084 m_originalGroup.link(group, this);
19085 m_originalGroup.setSubGroup((uint8)subgroup);
19089 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19091 LiquidData liquid_status;
19092 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
19093 if (!res)
19095 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
19096 // Small hack for enable breath in WMO
19097 if (IsInWater())
19098 m_MirrorTimerFlags|=UNDERWATER_INWATER;
19099 return;
19102 // All liquids type - check under water position
19103 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
19105 if ( res & LIQUID_MAP_UNDER_WATER)
19106 m_MirrorTimerFlags |= UNDERWATER_INWATER;
19107 else
19108 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
19111 // Allow travel in dark water on taxi or transport
19112 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
19113 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
19114 else
19115 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
19117 // in lava check, anywhere in lava level
19118 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
19120 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19121 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
19122 else
19123 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
19125 // in slime check, anywhere in slime level
19126 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
19128 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19129 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
19130 else
19131 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
19135 void Player::SetCanParry( bool value )
19137 if(m_canParry==value)
19138 return;
19140 m_canParry = value;
19141 UpdateParryPercentage();
19144 void Player::SetCanBlock( bool value )
19146 if(m_canBlock==value)
19147 return;
19149 m_canBlock = value;
19150 UpdateBlockPercentage();
19153 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19155 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19156 if(itr->pos == pos)
19157 return true;
19159 return false;
19162 bool Player::CanUseBattleGroundObject()
19164 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19165 // maybe gameobject code should handle that ForceReaction usage
19166 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19167 return ( //InBattleGround() && // in battleground - not need, check in other cases
19168 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19169 //player cannot use object when he is invulnerable (immune)
19170 !isTotalImmune() && // not totally immune
19171 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19172 !HasStealthAura() && // not stealthed
19173 !HasInvisibilityAura() && // not invisible
19174 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19175 isAlive() // live player
19179 bool Player::CanCaptureTowerPoint()
19181 return ( !HasStealthAura() && // not stealthed
19182 !HasInvisibilityAura() && // not invisible
19183 isAlive() // live player
19187 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19189 uint32 level = getLevel();
19191 if(level > GT_MAX_LEVEL)
19192 level = GT_MAX_LEVEL; // max level in this dbc
19194 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19195 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19196 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19198 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19199 return 0;
19201 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19203 if(!bsc) // shouldn't happen
19204 return 0xFFFFFFFF;
19206 float cost = 0;
19208 if(hairstyle != newhairstyle)
19209 cost += bsc->cost; // full price
19211 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19212 cost += bsc->cost * 0.5f; // +1/2 of price
19214 if(facialhair != newfacialhair)
19215 cost += bsc->cost * 0.75f; // +3/4 of price
19217 return uint32(cost);
19220 void Player::InitGlyphsForLevel()
19222 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19223 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19224 if(gs->Order)
19225 SetGlyphSlot(gs->Order - 1, gs->Id);
19227 uint32 level = getLevel();
19228 uint32 value = 0;
19230 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19231 if(level >= 15)
19232 value |= (0x01 | 0x02);
19233 if(level >= 30)
19234 value |= 0x08;
19235 if(level >= 50)
19236 value |= 0x04;
19237 if(level >= 70)
19238 value |= 0x10;
19239 if(level >= 80)
19240 value |= 0x20;
19242 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19245 void Player::EnterVehicle(Vehicle *vehicle)
19247 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19248 if(!ve)
19249 return;
19251 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19252 if(!veSeat)
19253 return;
19255 vehicle->SetCharmerGUID(GetGUID());
19256 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19257 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19258 vehicle->setFaction(getFaction());
19260 SetCharm(vehicle); // charm
19261 SetFarSightGUID(vehicle->GetGUID()); // set view
19263 SetClientControl(vehicle, 1); // redirect controls to vehicle
19265 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19266 GetSession()->SendPacket(&data);
19268 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19269 data.append(GetPackGUID());
19270 data << uint32(0); // counter?
19271 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19272 data << uint16(0); // special flags
19273 data << uint32(getMSTime()); // time
19274 data << vehicle->GetPositionX(); // x
19275 data << vehicle->GetPositionY(); // y
19276 data << vehicle->GetPositionZ(); // z
19277 data << vehicle->GetOrientation(); // o
19278 // transport part, TODO: load/calculate seat offsets
19279 data << uint64(vehicle->GetGUID()); // transport guid
19280 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19281 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19282 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19283 data << float(0); // transport orientation
19284 data << uint32(getMSTime()); // transport time
19285 data << uint8(0); // seat
19286 // end of transport part
19287 data << uint32(0); // fall time
19288 GetSession()->SendPacket(&data);
19290 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
19291 data << uint64(vehicle->GetGUID());
19292 data << uint16(0);
19293 data << uint32(0);
19294 data << uint32(0x00000101);
19296 for(uint32 i = 0; i < 10; ++i)
19297 data << uint16(0) << uint8(0) << uint8(i+8);
19299 data << uint8(0);
19300 data << uint8(0);
19301 GetSession()->SendPacket(&data);
19304 void Player::ExitVehicle(Vehicle *vehicle)
19306 vehicle->SetCharmerGUID(0);
19307 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19308 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19309 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19311 SetCharm(NULL);
19312 SetFarSightGUID(0);
19314 SetClientControl(vehicle, 0);
19316 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19317 data.append(GetPackGUID());
19318 data << uint32(0); // counter?
19319 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19320 data << uint16(0x40); // special flags
19321 data << uint32(getMSTime()); // time
19322 data << vehicle->GetPositionX(); // x
19323 data << vehicle->GetPositionY(); // y
19324 data << vehicle->GetPositionZ(); // z
19325 data << vehicle->GetOrientation(); // o
19326 data << uint32(0); // fall time
19327 GetSession()->SendPacket(&data);
19329 data.Initialize(SMSG_PET_SPELLS, 8);
19330 data << uint64(0);
19331 GetSession()->SendPacket(&data);
19333 // maybe called at dummy aura remove?
19334 // CastSpell(this, 45472, true); // Parachute
19337 bool Player::isTotalImmune()
19339 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19341 uint32 immuneMask = 0;
19342 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19344 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19345 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19346 return true;
19348 return false;
19351 bool Player::HasTitle(uint32 bitIndex)
19353 if (bitIndex > 192)
19354 return false;
19356 uint32 fieldIndexOffset = bitIndex / 32;
19357 uint32 flag = 1 << (bitIndex % 32);
19358 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19361 void Player::SetTitle(CharTitlesEntry const* title)
19363 uint32 fieldIndexOffset = title->bit_index / 32;
19364 uint32 flag = 1 << (title->bit_index % 32);
19365 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19368 void Player::ConvertRune(uint8 index, uint8 newType)
19370 SetCurrentRune(index, newType);
19372 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19373 data << uint8(index);
19374 data << uint8(newType);
19375 GetSession()->SendPacket(&data);
19378 void Player::ResyncRunes(uint8 count)
19380 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19381 for(uint32 i = 0; i < count; ++i)
19383 data << uint8(GetCurrentRune(i)); // rune type
19384 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19386 GetSession()->SendPacket(&data);
19389 void Player::AddRunePower(uint8 index)
19391 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19392 data << uint32(1 << index); // mask (0x00-0x3F probably)
19393 GetSession()->SendPacket(&data);
19396 void Player::InitRunes()
19398 if(getClass() != CLASS_DEATH_KNIGHT)
19399 return;
19401 m_runes = new Runes;
19403 m_runes->runeState = 0;
19405 for(uint32 i = 0; i < MAX_RUNES; ++i)
19407 SetBaseRune(i, i / 2); // init base types
19408 SetCurrentRune(i, i / 2); // init current types
19409 SetRuneCooldown(i, 0); // reset cooldowns
19410 m_runes->SetRuneState(i);
19413 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19414 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19417 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19419 Loot loot;
19420 loot.FillLoot (loot_id,store,this,true);
19422 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19423 for(uint32 i = 0; i < max_slot; ++i)
19425 LootItem* lootItem = loot.LootItemInSlot(i,this);
19427 ItemPosCountVec dest;
19428 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19429 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19430 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19431 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19432 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19433 if(msg != EQUIP_ERR_OK)
19435 SendEquipError( msg, NULL, NULL );
19436 continue;
19439 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19440 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19444 uint32 Player::CalculateTalentsPoints() const
19446 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19448 if(getClass() != CLASS_DEATH_KNIGHT)
19449 return base_talent;
19451 uint32 talentPointsForLevel =
19452 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19453 + m_questRewardTalentCount;
19455 if(talentPointsForLevel > base_talent)
19456 talentPointsForLevel = base_talent;
19458 return talentPointsForLevel;
19461 bool Player::IsAllowUseFlyMountsHere() const
19463 if (isGameMaster())
19464 return true;
19466 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19467 return v_map == 530 || v_map == 571 && HasSpell(54197);
19470 void Player::learnSpellHighRank(uint32 spellid)
19472 learnSpell(spellid,false);
19474 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19475 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19476 learnSpellHighRank(itr->second);
19479 void Player::_LoadSkills()
19481 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19483 // reset skill modifiers and set correct unlearn flags
19484 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
19486 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19488 // set correct unlearn bit
19489 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19490 if(!id) continue;
19492 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19493 if(!pSkill) continue;
19495 // enable unlearn button for primary professions only
19496 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19497 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19498 else
19499 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19501 // set fixed skill ranges
19502 switch(GetSkillRangeType(pSkill,false))
19504 case SKILL_RANGE_LANGUAGE: // 300..300
19505 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19506 break;
19507 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19508 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19509 break;
19510 default:
19511 break;
19514 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19515 learnSkillRewardedSpells(id, vskill);
19518 // special settings
19519 if(getClass()==CLASS_DEATH_KNIGHT)
19521 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19522 if(base_level < 1)
19523 base_level = 1;
19524 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19525 if(base_skill < 1)
19526 base_skill = 1; // skill mast be known and then > 0 in any case
19528 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19529 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19530 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19531 SetSkill(SKILL_AXES, base_skill,base_skill);
19532 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19533 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19534 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19535 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19536 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19537 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19538 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19539 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19540 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19541 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19542 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19543 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19547 uint32 Player::GetPhaseMaskForSpawn() const
19549 uint32 phase = PHASEMASK_NORMAL;
19550 if(!isGameMaster())
19551 phase = GetPhaseMask();
19552 else
19554 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19555 if(!phases.empty())
19556 phase = phases.front()->GetMiscValue();
19559 // some aura phases include 1 normal map in addition to phase itself
19560 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19561 return n_phase;
19563 return PHASEMASK_NORMAL;
19566 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19568 ItemPrototype const* pProto = pItem->GetProto();
19570 // proto based limitations
19571 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19572 return res;
19574 // check unique-equipped on gems
19575 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19577 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19578 if(!enchant_id)
19579 continue;
19580 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19581 if(!enchantEntry)
19582 continue;
19584 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19585 if(!pGem)
19586 continue;
19588 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19589 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19590 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19592 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19593 return res;
19596 return EQUIP_ERR_OK;
19599 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19601 // check unique-equipped on item
19602 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19604 // there is an equip limit on this item
19605 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19606 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19609 // check unique-equipped limit
19610 if (itemProto->ItemLimitCategory)
19612 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19613 if(!limitEntry)
19614 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19616 if(limit_count > limitEntry->maxCount)
19617 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19619 // there is an equip limit on this item
19620 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19621 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19624 return EQUIP_ERR_OK;
19627 void Player::HandleFall(MovementInfo const& movementInfo)
19629 // calculate total z distance of the fall
19630 float z_diff = m_lastFallZ - movementInfo.z;
19631 sLog.outDebug("zDiff = %f", z_diff);
19633 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19634 // 14.57 can be calculated by resolving damageperc formula below to 0
19635 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19636 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19637 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19639 //Safe fall, fall height reduction
19640 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19642 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19644 if(damageperc >0 )
19646 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19648 float height = movementInfo.z;
19649 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19651 if (damage > 0)
19653 //Prevent fall damage from being more than the player maximum health
19654 if (damage > GetMaxHealth())
19655 damage = GetMaxHealth();
19657 // Gust of Wind
19658 if (GetDummyAura(43621))
19659 damage = GetMaxHealth()/2;
19661 EnvironmentalDamage(DAMAGE_FALL, damage);
19663 // recheck alive, might have died of EnvironmentalDamage
19664 if (isAlive())
19665 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19668 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19669 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.z, height, GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall);
19674 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19676 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
19679 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
19681 uint32 CurTalentPoints = GetFreeTalentPoints();
19683 if(CurTalentPoints == 0)
19684 return;
19686 if (talentRank >= MAX_TALENT_RANK)
19687 return;
19689 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
19691 if(!talentInfo)
19692 return;
19694 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
19696 if(!talentTabInfo)
19697 return;
19699 // prevent learn talent for different class (cheating)
19700 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
19701 return;
19703 // find current max talent rank
19704 int32 curtalent_maxrank = 0;
19705 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19707 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19709 curtalent_maxrank = k + 1;
19710 break;
19714 // we already have same or higher talent rank learned
19715 if(curtalent_maxrank >= (talentRank + 1))
19716 return;
19718 // check if we have enough talent points
19719 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19720 return;
19722 // Check if it requires another talent
19723 if (talentInfo->DependsOn > 0)
19725 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19727 bool hasEnoughRank = false;
19728 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19730 if (depTalentInfo->RankID[i] != 0)
19731 if (HasSpell(depTalentInfo->RankID[i]))
19732 hasEnoughRank = true;
19734 if (!hasEnoughRank)
19735 return;
19739 // Find out how many points we have in this field
19740 uint32 spentPoints = 0;
19742 uint32 tTab = talentInfo->TalentTab;
19743 if (talentInfo->Row > 0)
19745 unsigned int numRows = sTalentStore.GetNumRows();
19746 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19748 // Someday, someone needs to revamp
19749 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19750 if (tmpTalent) // the way talents are tracked
19752 if (tmpTalent->TalentTab == tTab)
19754 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19756 if (tmpTalent->RankID[j] != 0)
19758 if (HasSpell(tmpTalent->RankID[j]))
19760 spentPoints += j + 1;
19769 // not have required min points spent in talent tree
19770 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
19771 return;
19773 // spell not set in talent.dbc
19774 uint32 spellid = talentInfo->RankID[talentRank];
19775 if( spellid == 0 )
19777 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19778 return;
19781 // already known
19782 if(HasSpell(spellid))
19783 return;
19785 // learn! (other talent ranks will unlearned at learning)
19786 learnSpell(spellid, false);
19787 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19789 // update free talent points
19790 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19793 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
19795 Pet *pet = GetPet();
19797 if(!pet)
19798 return;
19800 if(petGuid != pet->GetGUID())
19801 return;
19803 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
19805 if(CurTalentPoints == 0)
19806 return;
19808 if (talentRank >= MAX_PET_TALENT_RANK)
19809 return;
19811 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
19813 if(!talentInfo)
19814 return;
19816 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
19818 if(!talentTabInfo)
19819 return;
19821 CreatureInfo const *ci = pet->GetCreatureInfo();
19823 if(!ci)
19824 return;
19826 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19828 if(!pet_family)
19829 return;
19831 if(pet_family->petTalentType < 0) // not hunter pet
19832 return;
19834 // prevent learn talent for different family (cheating)
19835 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19836 return;
19838 // find current max talent rank
19839 int32 curtalent_maxrank = 0;
19840 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19842 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
19844 curtalent_maxrank = k + 1;
19845 break;
19849 // we already have same or higher talent rank learned
19850 if(curtalent_maxrank >= (talentRank + 1))
19851 return;
19853 // check if we have enough talent points
19854 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19855 return;
19857 // Check if it requires another talent
19858 if (talentInfo->DependsOn > 0)
19860 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19862 bool hasEnoughRank = false;
19863 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19865 if (depTalentInfo->RankID[i] != 0)
19866 if (pet->HasSpell(depTalentInfo->RankID[i]))
19867 hasEnoughRank = true;
19869 if (!hasEnoughRank)
19870 return;
19874 // Find out how many points we have in this field
19875 uint32 spentPoints = 0;
19877 uint32 tTab = talentInfo->TalentTab;
19878 if (talentInfo->Row > 0)
19880 unsigned int numRows = sTalentStore.GetNumRows();
19881 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19883 // Someday, someone needs to revamp
19884 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19885 if (tmpTalent) // the way talents are tracked
19887 if (tmpTalent->TalentTab == tTab)
19889 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19891 if (tmpTalent->RankID[j] != 0)
19893 if (pet->HasSpell(tmpTalent->RankID[j]))
19895 spentPoints += j + 1;
19904 // not have required min points spent in talent tree
19905 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
19906 return;
19908 // spell not set in talent.dbc
19909 uint32 spellid = talentInfo->RankID[talentRank];
19910 if( spellid == 0 )
19912 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19913 return;
19916 // already known
19917 if(pet->HasSpell(spellid))
19918 return;
19920 // learn! (other talent ranks will unlearned at learning)
19921 pet->learnSpell(spellid);
19922 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19924 // update free talent points
19925 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19928 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
19930 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
19932 if(apply)
19933 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
19934 else
19935 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
19939 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
19941 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
19942 SetFallInformation(minfo.fallTime, minfo.z);
19945 void Player::UnsummonPetTemporaryIfAny()
19947 Pet* pet = GetPet();
19948 if(!pet)
19949 return;
19951 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
19953 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
19954 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
19957 RemovePet(pet, PET_SAVE_AS_CURRENT);
19960 void Player::ResummonPetTemporaryUnSummonedIfAny()
19962 if(!m_temporaryUnsummonedPetNumber)
19963 return;
19965 // not resummon in not appropriate state
19966 if(IsPetNeedBeTemporaryUnsummoned())
19967 return;
19969 if(GetPetGUID())
19970 return;
19972 Pet* NewPet = new Pet;
19973 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
19974 delete NewPet;
19976 m_temporaryUnsummonedPetNumber = 0;
19979 bool Player::canSeeSpellClickOn(Creature const *c) const
19981 if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
19982 return false;
19984 SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(c->GetEntry());
19985 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
19986 if(itr->second.IsFitToRequirements(this))
19987 return true;
19989 return false;
19992 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
19994 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
19995 uint8 talentGroupCount = 1;
19996 *data << uint8(talentGroupCount); // talent group count (0, 1 or 2)
19997 *data << uint8(0); // talent group index (0 or 1)
19999 if(talentGroupCount)
20001 // loop through all specs (only 1 for now)
20002 for(uint32 groups = 0; groups < talentGroupCount; ++groups)
20004 uint8 talentIdCount = 0;
20005 size_t pos = data->wpos();
20006 *data << uint8(talentIdCount); // [PH], talentIdCount
20008 // find class talent tabs (all players have 3 talent tabs)
20009 uint32 const* talentTabIds = GetTalentTabPages(getClass());
20011 for(uint32 i = 0; i < 3; ++i)
20013 uint32 talentTabId = talentTabIds[i];
20015 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20017 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20018 if(!talentInfo)
20019 continue;
20021 // skip another tab talents
20022 if(talentInfo->TalentTab != talentTabId)
20023 continue;
20025 // find max talent rank
20026 int32 curtalent_maxrank = -1;
20027 for(int32 k = 4; k > -1; --k)
20029 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20031 curtalent_maxrank = k;
20032 break;
20036 // not learned talent
20037 if(curtalent_maxrank < 0)
20038 continue;
20040 *data << uint32(talentInfo->TalentID); // Talent.dbc
20041 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20043 ++talentIdCount;
20047 data->put<uint8>(pos, talentIdCount); // put real count
20049 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
20051 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
20052 *data << uint16(GetGlyph(i)); // GlyphProperties.dbc
20057 void Player::BuildPetTalentsInfoData(WorldPacket *data)
20059 uint32 unspentTalentPoints = 0;
20060 size_t pointsPos = data->wpos();
20061 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
20063 uint8 talentIdCount = 0;
20064 size_t countPos = data->wpos();
20065 *data << uint8(talentIdCount); // [PH], talentIdCount
20067 Pet *pet = GetPet();
20068 if(!pet)
20069 return;
20071 unspentTalentPoints = pet->GetFreeTalentPoints();
20073 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
20075 CreatureInfo const *ci = pet->GetCreatureInfo();
20076 if(!ci)
20077 return;
20079 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20080 if(!pet_family || pet_family->petTalentType < 0)
20081 return;
20083 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
20085 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
20086 if(!talentTabInfo)
20087 continue;
20089 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20090 continue;
20092 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20094 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20095 if(!talentInfo)
20096 continue;
20098 // skip another tab talents
20099 if(talentInfo->TalentTab != talentTabId)
20100 continue;
20102 // find max talent rank
20103 int32 curtalent_maxrank = -1;
20104 for(int32 k = 4; k > -1; --k)
20106 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20108 curtalent_maxrank = k;
20109 break;
20113 // not learned talent
20114 if(curtalent_maxrank < 0)
20115 continue;
20117 *data << uint32(talentInfo->TalentID); // Talent.dbc
20118 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20120 ++talentIdCount;
20123 data->put<uint8>(countPos, talentIdCount); // put real count
20125 break;
20129 void Player::SendTalentsInfoData(bool pet)
20131 WorldPacket data(SMSG_TALENTS_INFO, 50);
20132 data << uint8(pet ? 1 : 0);
20133 if(pet)
20134 BuildPetTalentsInfoData(&data);
20135 else
20136 BuildPlayerTalentsInfoData(&data);
20137 GetSession()->SendPacket(&data);
20140 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
20142 uint32 slotUsedMask = 0;
20143 size_t slotUsedMaskPos = data->wpos();
20144 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
20146 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20148 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
20150 if(!item)
20151 continue;
20153 slotUsedMask |= (1 << i);
20155 *data << uint32(item->GetEntry()); // item entry
20157 uint16 enchantmentMask = 0;
20158 size_t enchantmentMaskPos = data->wpos();
20159 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
20161 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
20163 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
20165 if(!enchId)
20166 continue;
20168 enchantmentMask |= (1 << j);
20170 *data << uint16(enchId); // enchantmentId?
20173 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
20175 *data << uint16(0); // ?
20176 *data << uint8(0); // PGUID!
20177 *data << uint32(0); // seed?
20180 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
20183 void Player::SendEquipmentSetList()
20185 uint32 count = 0;
20186 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
20187 size_t count_pos = data.wpos();
20188 data << uint32(count); // count placeholder
20189 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20191 if(itr->second.state==EQUIPMENT_SET_DELETED)
20192 continue;
20193 data.appendPackGUID(itr->second.Guid);
20194 data << uint32(itr->first);
20195 data << itr->second.Name;
20196 data << itr->second.IconName;
20197 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20198 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
20200 ++count; // client have limit but it checked at loading and set
20202 data.put<uint32>(count_pos, count);
20203 GetSession()->SendPacket(&data);
20206 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
20208 if(eqset.Guid != 0)
20210 bool found = false;
20212 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20214 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
20216 found = true;
20217 break;
20221 if(!found) // something wrong...
20223 sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
20224 return;
20228 EquipmentSet& eqslot = m_EquipmentSets[index];
20230 EquipmentSetUpdateState old_state = eqslot.state;
20232 eqslot = eqset;
20234 if(eqset.Guid == 0)
20236 eqslot.Guid = objmgr.GenerateEquipmentSetGuid();
20238 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
20239 data << uint32(index);
20240 data.appendPackGUID(eqslot.Guid);
20241 GetSession()->SendPacket(&data);
20244 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
20247 void Player::_SaveEquipmentSets()
20249 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
20251 uint32 index = itr->first;
20252 EquipmentSet& eqset = itr->second;
20253 switch(eqset.state)
20255 case EQUIPMENT_SET_UNCHANGED:
20256 ++itr;
20257 break; // nothing do
20258 case EQUIPMENT_SET_CHANGED:
20259 CharacterDatabase.PExecute("UPDATE character_equipmentsets SET name='%s', iconname='%s', item0='%u', item1='%u', item2='%u', item3='%u', item4='%u', item5='%u', item6='%u', item7='%u', item8='%u', item9='%u', item10='%u', item11='%u', item12='%u', item13='%u', item14='%u', item15='%u', item16='%u', item17='%u', item18='%u' WHERE guid='%u' AND setguid='"UI64FMTD"' AND setindex='%u'",
20260 eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
20261 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18], GetGUIDLow(), eqset.Guid, index);
20262 eqset.state = EQUIPMENT_SET_UNCHANGED;
20263 ++itr;
20264 break;
20265 case EQUIPMENT_SET_NEW:
20266 CharacterDatabase.PExecute("INSERT INTO character_equipmentsets VALUES ('%u', '"UI64FMTD"', '%u', '%s', '%s', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
20267 GetGUIDLow(), eqset.Guid, index, eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
20268 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18]);
20269 eqset.state = EQUIPMENT_SET_UNCHANGED;
20270 ++itr;
20271 break;
20272 case EQUIPMENT_SET_DELETED:
20273 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
20274 m_EquipmentSets.erase(itr++);
20275 break;
20280 void Player::DeleteEquipmentSet(uint64 setGuid)
20282 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20284 if(itr->second.Guid == setGuid)
20286 if(itr->second.state == EQUIPMENT_SET_NEW)
20287 m_EquipmentSets.erase(itr);
20288 else
20289 itr->second.state = EQUIPMENT_SET_DELETED;
20290 break;
20295 void Player::ActivateSpec(uint32 specNum)
20297 if(GetActiveSpec() == specNum)
20298 return;
20300 resetTalents(true);