[8450] Prevented using of plaintext passwords in sql queries
[getmangos.git] / src / game / Player.cpp
blob65247bce1ba3dab7b60b960b7797c96272e6cd1a
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 m_DelayedOperations = 0;
342 m_bCanDelayTeleport = false;
343 m_bHasDelayedTeleport = false;
344 m_teleport_options = 0;
346 pTrader = 0;
347 ClearTrade();
349 m_cinematic = 0;
351 PlayerTalkClass = new PlayerMenu( GetSession() );
352 m_currentBuybackSlot = BUYBACK_SLOT_START;
354 m_DailyQuestChanged = false;
355 m_lastDailyQuestTime = 0;
357 for (int i=0; i<MAX_TIMERS; ++i)
358 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
360 m_MirrorTimerFlags = UNDERWATER_NONE;
361 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
362 m_isInWater = false;
363 m_drunkTimer = 0;
364 m_drunk = 0;
365 m_restTime = 0;
366 m_deathTimer = 0;
367 m_deathExpireTime = 0;
369 m_swingErrorMsg = 0;
371 m_DetectInvTimer = 1*IN_MILISECONDS;
373 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
375 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
376 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
379 m_logintime = time(NULL);
380 m_Last_tick = m_logintime;
381 m_WeaponProficiency = 0;
382 m_ArmorProficiency = 0;
383 m_canParry = false;
384 m_canBlock = false;
385 m_canDualWield = false;
386 m_canTitanGrip = false;
387 m_ammoDPS = 0.0f;
389 m_temporaryUnsummonedPetNumber = 0;
390 //cache for UNIT_CREATED_BY_SPELL to allow
391 //returning reagents for temporarily removed pets
392 //when dying/logging out
393 m_oldpetspell = 0;
395 ////////////////////Rest System/////////////////////
396 time_inn_enter=0;
397 inn_pos_mapid=0;
398 inn_pos_x=0;
399 inn_pos_y=0;
400 inn_pos_z=0;
401 m_rest_bonus=0;
402 rest_type=REST_TYPE_NO;
403 ////////////////////Rest System/////////////////////
405 m_mailsLoaded = false;
406 m_mailsUpdated = false;
407 unReadMails = 0;
408 m_nextMailDelivereTime = 0;
410 m_resetTalentsCost = 0;
411 m_resetTalentsTime = 0;
412 m_itemUpdateQueueBlocked = false;
414 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
415 m_forced_speed_changes[i] = 0;
417 m_stableSlots = 0;
419 /////////////////// Instance System /////////////////////
421 m_HomebindTimer = 0;
422 m_InstanceValid = true;
423 m_dungeonDifficulty = DIFFICULTY_NORMAL;
425 m_lastPotionId = 0;
427 m_activeSpec = 0;
428 m_specsCount = 1;
430 for (int i = 0; i < BASEMOD_END; ++i)
432 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
433 m_auraBaseMod[i][PCT_MOD] = 1.0f;
436 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
437 m_baseRatingValue[i] = 0;
439 m_baseSpellPower = 0;
440 m_baseFeralAP = 0;
441 m_baseManaRegen = 0;
443 // Honor System
444 m_lastHonorUpdateTime = time(NULL);
446 // Player summoning
447 m_summon_expire = 0;
448 m_summon_mapid = 0;
449 m_summon_x = 0.0f;
450 m_summon_y = 0.0f;
451 m_summon_z = 0.0f;
453 m_mover = this;
455 m_miniPet = 0;
456 m_contestedPvPTimer = 0;
458 m_declinedname = NULL;
459 m_runes = NULL;
461 m_lastFallTime = 0;
462 m_lastFallZ = 0;
465 Player::~Player ()
467 CleanupsBeforeDelete();
469 // it must be unloaded already in PlayerLogout and accessed only for loggined player
470 //m_social = NULL;
472 // Note: buy back item already deleted from DB when player was saved
473 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
475 if(m_items[i])
476 delete m_items[i];
478 CleanupChannels();
480 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
481 delete itr->second;
483 //all mailed items should be deleted, also all mail should be deallocated
484 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
485 delete *itr;
487 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
488 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
490 delete PlayerTalkClass;
492 if (m_transport)
494 m_transport->RemovePassenger(this);
497 for(size_t x = 0; x < ItemSetEff.size(); x++)
498 if(ItemSetEff[x])
499 delete ItemSetEff[x];
501 // clean up player-instance binds, may unload some instance saves
502 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
503 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
504 itr->second.save->RemovePlayer(this);
506 delete m_declinedname;
507 delete m_runes;
510 void Player::CleanupsBeforeDelete()
512 if(m_uint32Values) // only for fully created Object
514 TradeCancel(false);
515 DuelComplete(DUEL_INTERUPTED);
517 Unit::CleanupsBeforeDelete();
520 bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 outfitId )
522 //FIXME: outfitId not used in player creating
524 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
526 m_name = name;
528 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
529 if(!info)
531 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
532 return false;
535 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
536 m_items[i] = NULL;
538 SetLocationMapId(info->mapId);
539 Relocate(info->positionX,info->positionY,info->positionZ);
541 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
542 if(!cEntry)
544 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
545 return false;
548 SetMap(MapManager::Instance().CreateMap(info->mapId, this));
550 uint8 powertype = cEntry->powerType;
552 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
553 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
555 setFactionForRace(race);
557 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
559 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
560 InitDisplayIds();
561 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
562 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
563 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
564 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
565 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
567 // -1 is default value
568 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
570 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
571 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
572 SetByteValue(PLAYER_BYTES_3, 0, gender);
574 SetUInt32Value( PLAYER_GUILDID, 0 );
575 SetUInt32Value( PLAYER_GUILDRANK, 0 );
576 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
578 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
579 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
580 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 0 ); // 0=disabled
581 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
582 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
583 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
584 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
585 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
587 // set starting level
588 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
589 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
590 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
592 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
594 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
595 if(gm_level > start_level)
596 start_level = gm_level;
599 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
601 InitRunes();
603 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
604 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
605 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
607 // Played time
608 m_Last_tick = time(NULL);
609 m_Played_time[PLAYED_TIME_TOTAL] = 0;
610 m_Played_time[PLAYED_TIME_LEVEL] = 0;
612 // base stats and related field values
613 InitStatsForLevel();
614 InitTaxiNodesForLevel();
615 InitGlyphsForLevel();
616 InitTalentForLevel();
617 InitPrimaryProfessions(); // to max set before any spell added
619 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
620 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
621 SetHealth(GetMaxHealth());
622 if (getPowerType()==POWER_MANA)
624 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
625 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
628 if(getPowerType() == POWER_RUNIC_POWER)
630 SetPower(POWER_RUNE, 8);
631 SetMaxPower(POWER_RUNE, 8);
632 SetPower(POWER_RUNIC_POWER, 0);
633 SetMaxPower(POWER_RUNIC_POWER, 1000);
636 // original spells
637 learnDefaultSpells();
639 // original action bar
640 for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
641 addActionButton(action_itr->button,action_itr->action,action_itr->type);
643 // original items
644 CharStartOutfitEntry const* oEntry = NULL;
645 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
647 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
649 if(entry->RaceClassGender == RaceClassGender)
651 oEntry = entry;
652 break;
657 if(oEntry)
659 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
661 if(oEntry->ItemId[j] <= 0)
662 continue;
664 uint32 item_id = oEntry->ItemId[j];
666 // Hack for not existed item id in dbc 3.0.3
667 if(item_id==40582)
668 continue;
670 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
671 if(!iProto)
673 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
674 continue;
677 // BuyCount by default
678 uint32 count = iProto->BuyCount;
680 // special amount for foor/drink
681 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
683 switch(iProto->Spells[0].SpellCategory)
685 case 11: // food
686 count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4;
687 break;
688 case 59: // drink
689 count = 2;
690 break;
692 if(iProto->Stackable < count)
693 count = iProto->Stackable;
696 StoreNewItemInBestSlots(item_id, count);
700 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
701 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
703 // bags and main-hand weapon must equipped at this moment
704 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
705 // or ammo not equipped in special bag
706 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
708 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
710 uint16 eDest;
711 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
712 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
713 if( msg == EQUIP_ERR_OK )
715 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
716 EquipItem( eDest, pItem, true);
718 // move other items to more appropriate slots (ammo not equipped in special bag)
719 else
721 ItemPosCountVec sDest;
722 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
723 if( msg == EQUIP_ERR_OK )
725 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
726 pItem = StoreItem( sDest, pItem, true);
729 // if this is ammo then use it
730 msg = CanUseAmmo( pItem->GetEntry() );
731 if( msg == EQUIP_ERR_OK )
732 SetAmmo( pItem->GetEntry() );
736 // all item positions resolved
738 return true;
741 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
743 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
745 // attempt equip by one
746 while(titem_amount > 0)
748 uint16 eDest;
749 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
750 if( msg != EQUIP_ERR_OK )
751 break;
753 EquipNewItem( eDest, titem_id, true);
754 AutoUnequipOffhandIfNeed();
755 --titem_amount;
758 if(titem_amount == 0)
759 return true; // equipped
761 // attempt store
762 ItemPosCountVec sDest;
763 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
764 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
765 if( msg == EQUIP_ERR_OK )
767 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
768 return true; // stored
771 // item can't be added
772 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
773 return false;
776 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
778 if (MaxValue == DISABLED_MIRROR_TIMER)
780 if (CurrentValue!=DISABLED_MIRROR_TIMER)
781 StopMirrorTimer(Type);
782 return;
784 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
785 data << (uint32)Type;
786 data << CurrentValue;
787 data << MaxValue;
788 data << Regen;
789 data << (uint8)0;
790 data << (uint32)0; // spell id
791 GetSession()->SendPacket( &data );
794 void Player::StopMirrorTimer(MirrorTimerType Type)
796 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
797 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
798 data << (uint32)Type;
799 GetSession()->SendPacket( &data );
802 uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
804 if(!isAlive() || isGameMaster())
805 return 0;
807 // Absorb, resist some environmental damage type
808 uint32 absorb = 0;
809 uint32 resist = 0;
810 if (type == DAMAGE_LAVA)
811 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
812 else if (type == DAMAGE_SLIME)
813 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
815 damage-=absorb+resist;
817 DealDamageMods(this,damage,&absorb);
819 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
820 data << uint64(GetGUID());
821 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
822 data << uint32(damage);
823 data << uint32(absorb);
824 data << uint32(resist);
825 SendMessageToSet(&data, true);
827 uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
829 if(!isAlive())
831 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
833 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
834 DurabilityLossAll(0.10f,false);
835 // durability lost message
836 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
837 GetSession()->SendPacket(&data2);
840 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
843 return final_damage;
846 int32 Player::getMaxTimer(MirrorTimerType timer)
848 switch (timer)
850 case FATIGUE_TIMER:
851 return MINUTE*IN_MILISECONDS;
852 case BREATH_TIMER:
854 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
855 return DISABLED_MIRROR_TIMER;
856 int32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS;
857 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
858 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
859 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
860 return UnderWaterTime;
862 case FIRE_TIMER:
864 if (!isAlive())
865 return DISABLED_MIRROR_TIMER;
866 return 1*IN_MILISECONDS;
868 default:
869 return 0;
871 return 0;
874 void Player::UpdateMirrorTimers()
876 // Desync flags for update on next HandleDrowning
877 if (m_MirrorTimerFlags)
878 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
881 void Player::HandleDrowning(uint32 time_diff)
883 if (!m_MirrorTimerFlags)
884 return;
886 // In water
887 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
889 // Breath timer not activated - activate it
890 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
892 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
893 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
895 else // If activated - do tick
897 m_MirrorTimer[BREATH_TIMER]-=time_diff;
898 // Timer limit - need deal damage
899 if (m_MirrorTimer[BREATH_TIMER] < 0)
901 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
902 // Calculate and deal damage
903 // TODO: Check this formula
904 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
905 EnvironmentalDamage(DAMAGE_DROWNING, damage);
907 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
908 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
911 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
913 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
914 // Need breath regen
915 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
916 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
917 StopMirrorTimer(BREATH_TIMER);
918 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
919 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
922 // In dark water
923 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
925 // Fatigue timer not activated - activate it
926 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
928 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
929 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
931 else
933 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
934 // Timer limit - need deal damage or teleport ghost to graveyard
935 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
937 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
938 if (isAlive()) // Calculate and deal damage
940 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
941 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
943 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
944 RepopAtGraveyard();
946 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
947 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
950 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
952 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
953 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
954 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
955 StopMirrorTimer(FATIGUE_TIMER);
956 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
957 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
960 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
962 // Breath timer not activated - activate it
963 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
964 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
965 else
967 m_MirrorTimer[FIRE_TIMER]-=time_diff;
968 if (m_MirrorTimer[FIRE_TIMER] < 0)
970 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
971 // Calculate and deal damage
972 // TODO: Check this formula
973 uint32 damage = urand(600, 700);
974 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
975 EnvironmentalDamage(DAMAGE_LAVA, damage);
976 else
977 EnvironmentalDamage(DAMAGE_SLIME, damage);
981 else
982 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
984 // Recheck timers flag
985 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
986 for (int i = 0; i< MAX_TIMERS; ++i)
987 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
989 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
990 break;
992 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
995 ///The player sobers by 256 every 10 seconds
996 void Player::HandleSobering()
998 m_drunkTimer = 0;
1000 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1001 SetDrunkValue(drunk);
1004 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1006 if(value >= 23000)
1007 return DRUNKEN_SMASHED;
1008 if(value >= 12800)
1009 return DRUNKEN_DRUNK;
1010 if(value & 0xFFFE)
1011 return DRUNKEN_TIPSY;
1012 return DRUNKEN_SOBER;
1015 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1017 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1019 m_drunk = newDrunkenValue;
1020 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1022 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1024 // special drunk invisibility detection
1025 if(newDrunkenState >= DRUNKEN_DRUNK)
1026 m_detectInvisibilityMask |= (1<<6);
1027 else
1028 m_detectInvisibilityMask &= ~(1<<6);
1030 if(newDrunkenState == oldDrunkenState)
1031 return;
1033 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1034 data << uint64(GetGUID());
1035 data << uint32(newDrunkenState);
1036 data << uint32(itemId);
1038 SendMessageToSet(&data, true);
1041 void Player::Update( uint32 p_time )
1043 if(!IsInWorld())
1044 return;
1046 // undelivered mail
1047 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1049 SendNewMail();
1050 ++unReadMails;
1052 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1053 m_nextMailDelivereTime = 0;
1056 //used to implement delayed far teleports
1057 SetCanDelayTeleport(true);
1058 Unit::Update( p_time );
1059 SetCanDelayTeleport(false);
1061 // update player only attacks
1062 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1064 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1067 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1069 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1072 time_t now = time (NULL);
1074 UpdatePvPFlag(now);
1076 UpdateContestedPvP(p_time);
1078 UpdateDuelFlag(now);
1080 CheckDuelDistance(now);
1082 UpdateAfkReport(now);
1084 // Update items that have just a limited lifetime
1085 if (now>m_Last_tick)
1086 UpdateItemDuration(uint32(now- m_Last_tick));
1088 if (!m_timedquests.empty())
1090 std::set<uint32>::iterator iter = m_timedquests.begin();
1091 while (iter != m_timedquests.end())
1093 QuestStatusData& q_status = mQuestStatus[*iter];
1094 if( q_status.m_timer <= p_time )
1096 uint32 quest_id = *iter;
1097 ++iter; // current iter will be removed in FailQuest
1098 FailQuest(quest_id);
1100 else
1102 q_status.m_timer -= p_time;
1103 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1104 ++iter;
1109 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1111 Unit *pVictim = getVictim();
1112 if (pVictim && !IsNonMeleeSpellCasted(false))
1114 // default combat reach 10
1115 // TODO add weapon,skill check
1117 float pldistance = ATTACK_DISTANCE;
1119 if (isAttackReady(BASE_ATTACK))
1121 if(!IsWithinDistInMap(pVictim, pldistance))
1123 setAttackTimer(BASE_ATTACK,100);
1124 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1126 SendAttackSwingNotInRange();
1127 m_swingErrorMsg = 1;
1130 //120 degrees of radiant range
1131 else if( !HasInArc( 2*M_PI/3, pVictim ))
1133 setAttackTimer(BASE_ATTACK,100);
1134 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1136 SendAttackSwingBadFacingAttack();
1137 m_swingErrorMsg = 2;
1140 else
1142 m_swingErrorMsg = 0; // reset swing error state
1144 // prevent base and off attack in same time, delay attack at 0.2 sec
1145 if(haveOffhandWeapon())
1147 uint32 off_att = getAttackTimer(OFF_ATTACK);
1148 if(off_att < ATTACK_DISPLAY_DELAY)
1149 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1151 AttackerStateUpdate(pVictim, BASE_ATTACK);
1152 resetAttackTimer(BASE_ATTACK);
1156 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1158 if(!IsWithinDistInMap(pVictim, pldistance))
1160 setAttackTimer(OFF_ATTACK,100);
1162 else if( !HasInArc( 2*M_PI/3, pVictim ))
1164 setAttackTimer(OFF_ATTACK,100);
1166 else
1168 // prevent base and off attack in same time, delay attack at 0.2 sec
1169 uint32 base_att = getAttackTimer(BASE_ATTACK);
1170 if(base_att < ATTACK_DISPLAY_DELAY)
1171 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1172 // do attack
1173 AttackerStateUpdate(pVictim, OFF_ATTACK);
1174 resetAttackTimer(OFF_ATTACK);
1178 Unit *owner = pVictim->GetOwner();
1179 Unit *u = owner ? owner : pVictim;
1180 if(u->IsPvP() && (!duel || duel->opponent != u))
1182 UpdatePvP(true);
1183 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1188 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1190 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1192 int time_inn = time(NULL)-GetTimeInnEnter();
1193 if (time_inn >= 10) //freeze update
1195 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1196 //speed collect rest bonus (section/in hour)
1197 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1198 UpdateInnerTime(time(NULL));
1203 if(m_regenTimer > 0)
1205 if(p_time >= m_regenTimer)
1206 m_regenTimer = 0;
1207 else
1208 m_regenTimer -= p_time;
1211 if (m_weaponChangeTimer > 0)
1213 if(p_time >= m_weaponChangeTimer)
1214 m_weaponChangeTimer = 0;
1215 else
1216 m_weaponChangeTimer -= p_time;
1219 if (m_zoneUpdateTimer > 0)
1221 if(p_time >= m_zoneUpdateTimer)
1223 uint32 newzone, newarea;
1224 GetZoneAndAreaId(newzone,newarea);
1226 if( m_zoneUpdateId != newzone )
1227 UpdateZone(newzone,newarea); // also update area
1228 else
1230 // use area updates as well
1231 // needed for free far all arenas for example
1232 if( m_areaUpdateId != newarea )
1233 UpdateArea(newarea);
1235 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1238 else
1239 m_zoneUpdateTimer -= p_time;
1242 if (isAlive())
1244 RegenerateAll();
1247 if (m_deathState == JUST_DIED)
1249 KillPlayer();
1252 if(m_nextSave > 0)
1254 if(p_time >= m_nextSave)
1256 // m_nextSave reseted in SaveToDB call
1257 SaveToDB();
1258 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1260 else
1262 m_nextSave -= p_time;
1266 //Handle Water/drowning
1267 HandleDrowning(p_time);
1269 //Handle detect stealth players
1270 if (m_DetectInvTimer > 0)
1272 if (p_time >= m_DetectInvTimer)
1274 HandleStealthedUnitsDetection();
1275 m_DetectInvTimer = 3000;
1277 else
1278 m_DetectInvTimer -= p_time;
1281 // Played time
1282 if (now > m_Last_tick)
1284 uint32 elapsed = uint32(now - m_Last_tick);
1285 m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
1286 m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
1287 m_Last_tick = now;
1290 if (m_drunk)
1292 m_drunkTimer += p_time;
1294 if (m_drunkTimer > 10*IN_MILISECONDS)
1295 HandleSobering();
1298 // not auto-free ghost from body in instances
1299 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1301 if(p_time >= m_deathTimer)
1303 m_deathTimer = 0;
1304 BuildPlayerRepop();
1305 RepopAtGraveyard();
1307 else
1308 m_deathTimer -= p_time;
1311 UpdateEnchantTime(p_time);
1312 UpdateHomebindTime(p_time);
1314 // group update
1315 SendUpdateToOutOfRangeGroupMembers();
1317 Pet* pet = GetPet();
1318 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1320 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1323 //we should execute delayed teleports only for alive(!) players
1324 //because we don't want player's ghost teleported from graveyard
1325 if(IsHasDelayedTeleport() && isAlive())
1326 TeleportTo(m_teleport_dest, m_teleport_options);
1329 void Player::setDeathState(DeathState s)
1331 uint32 ressSpellId = 0;
1333 bool cur = isAlive();
1335 if(s == JUST_DIED && cur)
1337 // drunken state is cleared on death
1338 SetDrunkValue(0);
1339 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1340 ClearComboPoints();
1342 clearResurrectRequestData();
1344 // remove form before other mods to prevent incorrect stats calculation
1345 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1347 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1348 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1350 // remove uncontrolled pets
1351 RemoveMiniPet();
1353 // save value before aura remove in Unit::setDeathState
1354 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1356 // passive spell
1357 if(!ressSpellId)
1358 ressSpellId = GetResurrectionSpellId();
1359 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1360 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1361 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1363 Unit::setDeathState(s);
1365 // restore resurrection spell id for player after aura remove
1366 if(s == JUST_DIED && cur && ressSpellId)
1367 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1369 if(isAlive() && !cur)
1371 //clear aura case after resurrection by another way (spells will be applied before next death)
1372 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1374 // restore default warrior stance
1375 if(getClass()== CLASS_WARRIOR)
1376 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1380 bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1382 // 0 1 2 3 4 5 6 7
1383 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
1384 // 8 9 10 11 12 13 14
1385 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
1386 // 15 16 17 18 19 20
1387 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive "
1389 Field *fields = result->Fetch();
1391 uint32 guid = fields[0].GetUInt32();
1392 uint8 pRace = fields[2].GetUInt8();
1393 uint8 pClass = fields[3].GetUInt8();
1395 PlayerInfo const *info = objmgr.GetPlayerInfo(pRace, pClass);
1396 if(!info)
1398 sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
1399 return false;
1402 *p_data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
1403 *p_data << fields[1].GetString(); // name
1404 *p_data << uint8(pRace); // race
1405 *p_data << uint8(pClass); // class
1406 *p_data << uint8(fields[4].GetUInt8()); // gender
1408 uint32 playerBytes = fields[5].GetUInt32();
1409 *p_data << uint8(playerBytes); // skin
1410 *p_data << uint8(playerBytes >> 8); // face
1411 *p_data << uint8(playerBytes >> 16); // hair style
1412 *p_data << uint8(playerBytes >> 24); // hair color
1414 uint32 playerBytes2 = fields[6].GetUInt32();
1415 *p_data << uint8(playerBytes2 & 0xFF); // facial hair
1417 *p_data << uint8(fields[7].GetUInt8()); // level
1418 *p_data << uint32(fields[8].GetUInt32()); // zone
1419 *p_data << uint32(fields[9].GetUInt32()); // map
1421 *p_data << fields[10].GetFloat(); // x
1422 *p_data << fields[11].GetFloat(); // y
1423 *p_data << fields[12].GetFloat(); // z
1425 *p_data << uint32(fields[13].GetUInt32()); // guild id
1427 uint32 char_flags = 0;
1428 uint32 playerFlags = fields[14].GetUInt32();
1429 uint32 atLoginFlags = fields[15].GetUInt32();
1430 if(playerFlags & PLAYER_FLAGS_HIDE_HELM)
1431 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1432 if(playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
1433 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1434 if(playerFlags & PLAYER_FLAGS_GHOST)
1435 char_flags |= CHARACTER_FLAG_GHOST;
1436 if(atLoginFlags & AT_LOGIN_RENAME)
1437 char_flags |= CHARACTER_FLAG_RENAME;
1438 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
1440 if(!fields[20].GetCppString().empty())
1441 char_flags |= CHARACTER_FLAG_DECLINED;
1443 else
1444 char_flags |= CHARACTER_FLAG_DECLINED;
1446 *p_data << uint32(char_flags); // character flags
1447 // character customize (flags?)
1448 *p_data << uint32(atLoginFlags & AT_LOGIN_CUSTOMIZE ? 1 : 0);
1449 *p_data << uint8(1); // unknown
1451 // Pets info
1453 uint32 petDisplayId = 0;
1454 uint32 petLevel = 0;
1455 uint32 petFamily = 0;
1457 // show pet at selection character in character list only for non-ghost character
1458 if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1460 uint32 entry = fields[16].GetUInt32();
1461 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1462 if(cInfo)
1464 petDisplayId = fields[17].GetUInt32();
1465 petLevel = fields[18].GetUInt32();
1466 petFamily = cInfo->family;
1470 *p_data << uint32(petDisplayId);
1471 *p_data << uint32(petLevel);
1472 *p_data << uint32(petFamily);
1475 // TODO: do not access data field here
1476 Tokens data = StrSplit(fields[19].GetCppString(), " ");
1478 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1480 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1481 uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
1482 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1483 if(!proto)
1485 *p_data << uint32(0);
1486 *p_data << uint8(0);
1487 *p_data << uint32(0);
1488 continue;
1491 SpellItemEnchantmentEntry const *enchant = NULL;
1493 uint32 enchants = GetUInt32ValueFromArray(data, visualbase + 1);
1494 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1496 // values stored in 2 uint16
1497 uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16);
1498 if(!enchantId)
1499 continue;
1501 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1502 break;
1505 *p_data << uint32(proto->DisplayInfoID);
1506 *p_data << uint8(proto->InventoryType);
1507 *p_data << uint32(enchant ? enchant->aura_id : 0);
1509 *p_data << uint32(0); // first bag display id
1510 *p_data << uint8(0); // first bag inventory type
1511 *p_data << uint32(0); // enchant?
1513 return true;
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.SetMovementFlags(MOVEMENTFLAG_NONE);
1613 if ((GetMapId() == mapid) && (!m_transport))
1615 //lets reset far teleport flag if it wasn't reset during chained teleports
1616 SetSemaphoreTeleportFar(false);
1617 //setup delayed teleport flag
1618 SetDelayedTeleportFlag(IsCanDelayTeleport());
1619 //if teleport spell is casted in Unit::Update() func
1620 //then we need to delay it until update process will be finished
1621 if(IsHasDelayedTeleport())
1623 SetSemaphoreTeleportNear(true);
1624 //lets save teleport destination for player
1625 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1626 m_teleport_options = options;
1627 return true;
1630 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1632 //same map, only remove pet if out of range for new position
1633 if(pet && !pet->IsWithinDist3d(x,y,z, OWNER_MAX_DISTANCE))
1634 UnsummonPetTemporaryIfAny();
1637 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1638 CombatStop();
1640 // this will be used instead of the current location in SaveToDB
1641 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1642 SetFallInformation(0, z);
1644 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1645 // at client packet MSG_MOVE_TELEPORT_ACK
1646 SetSemaphoreTeleportNear(true);
1647 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1648 if(!GetSession()->PlayerLogout())
1650 WorldPacket data;
1651 BuildTeleportAckMsg(&data, x, y, z, orientation);
1652 GetSession()->SendPacket(&data);
1655 else
1657 // far teleport to another map
1658 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1659 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1661 // Check enter rights before map getting to avoid creating instance copy for player
1662 // this check not dependent from map instance copy and same for all instance copies of selected map
1663 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1664 return false;
1666 // If the map is not created, assume it is possible to enter it.
1667 // It will be created in the WorldPortAck.
1668 Map *map = MapManager::Instance().FindMap(mapid);
1669 if (!map || map->CanEnter(this))
1671 //lets reset near teleport flag if it wasn't reset during chained teleports
1672 SetSemaphoreTeleportNear(false);
1673 //setup delayed teleport flag
1674 SetDelayedTeleportFlag(IsCanDelayTeleport());
1675 //if teleport spell is casted in Unit::Update() func
1676 //then we need to delay it until update process will be finished
1677 if(IsHasDelayedTeleport())
1679 SetSemaphoreTeleportFar(true);
1680 //lets save teleport destination for player
1681 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1682 m_teleport_options = options;
1683 return true;
1686 SetSelection(0);
1688 CombatStop();
1690 ResetContestedPvP();
1692 // remove player from battleground on far teleport (when changing maps)
1693 if(BattleGround const* bg = GetBattleGround())
1695 // Note: at battleground join battleground id set before teleport
1696 // and we already will found "current" battleground
1697 // just need check that this is targeted map or leave
1698 if(bg->GetMapId() != mapid)
1699 LeaveBattleground(false); // don't teleport to entry point
1702 // remove pet on map change
1703 if (pet)
1704 UnsummonPetTemporaryIfAny();
1706 // remove all dyn objects
1707 RemoveAllDynObjects();
1709 // stop spellcasting
1710 // not attempt interrupt teleportation spell at caster teleport
1711 if(!(options & TELE_TO_SPELL))
1712 if(IsNonMeleeSpellCasted(true))
1713 InterruptNonMeleeSpells(true);
1715 //remove auras before removing from map...
1716 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1718 if(!GetSession()->PlayerLogout())
1720 // send transfer packets
1721 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1722 data << uint32(mapid);
1723 if (m_transport)
1725 data << m_transport->GetEntry() << GetMapId();
1727 GetSession()->SendPacket(&data);
1729 data.Initialize(SMSG_NEW_WORLD, (20));
1730 if (m_transport)
1732 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1734 else
1736 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1738 GetSession()->SendPacket( &data );
1739 SendSavedInstances();
1741 // remove from old map now
1742 if(oldmap) oldmap->Remove(this, false);
1745 // new final coordinates
1746 float final_x = x;
1747 float final_y = y;
1748 float final_z = z;
1749 float final_o = orientation;
1751 if(m_transport)
1753 final_x += m_movementInfo.t_x;
1754 final_y += m_movementInfo.t_y;
1755 final_z += m_movementInfo.t_z;
1756 final_o += m_movementInfo.t_o;
1759 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1760 SetFallInformation(0, final_z);
1761 // if the player is saved before worldportack (at logout for example)
1762 // this will be used instead of the current location in SaveToDB
1764 // move packet sent by client always after far teleport
1765 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1766 SetSemaphoreTeleportFar(true);
1768 else
1769 return false;
1771 return true;
1774 bool Player::TeleportToBGEntryPoint()
1776 ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
1777 ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
1778 return TeleportTo(m_bgData.joinPos);
1781 void Player::ProcessDelayedOperations()
1783 if(m_DelayedOperations == 0)
1784 return;
1786 if(m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
1788 ResurrectPlayer(0.0f, false);
1790 if(GetMaxHealth() > m_resurrectHealth)
1791 SetHealth( m_resurrectHealth );
1792 else
1793 SetHealth( GetMaxHealth() );
1795 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
1796 SetPower(POWER_MANA, m_resurrectMana );
1797 else
1798 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
1800 SetPower(POWER_RAGE, 0 );
1801 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
1803 SpawnCorpseBones();
1806 if(m_DelayedOperations & DELAYED_SAVE_PLAYER)
1808 SaveToDB();
1811 if(m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
1813 CastSpell(this, 26013, true); // Deserter
1816 if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
1818 if (m_bgData.mountSpell)
1820 CastSpell(this, m_bgData.mountSpell, true);
1821 m_bgData.mountSpell = 0;
1825 if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
1827 if (m_bgData.HasTaxiPath())
1829 m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
1830 m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
1831 m_bgData.ClearTaxiPath();
1833 ContinueTaxiFlight();
1837 //we have executed ALL delayed ops, so clear the flag
1838 m_DelayedOperations = 0;
1841 void Player::AddToWorld()
1843 ///- Do not add/remove the player from the object storage
1844 ///- It will crash when updating the ObjectAccessor
1845 ///- The player should only be added when logging in
1846 Unit::AddToWorld();
1848 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1850 if(m_items[i])
1851 m_items[i]->AddToWorld();
1855 void Player::RemoveFromWorld()
1857 // cleanup
1858 if(IsInWorld())
1860 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1861 Uncharm();
1862 UnsummonAllTotems();
1863 RemoveMiniPet();
1866 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1868 if(m_items[i])
1869 m_items[i]->RemoveFromWorld();
1872 ///- Do not add/remove the player from the object storage
1873 ///- It will crash when updating the ObjectAccessor
1874 ///- The player should only be removed when logging out
1875 Unit::RemoveFromWorld();
1878 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1880 float addRage;
1882 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1884 if(attacker)
1886 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1888 // talent who gave more rage on attack
1889 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1891 else
1893 addRage = damage/rageconversion*2.5;
1895 // Berserker Rage effect
1896 if(HasAura(18499,0))
1897 addRage *= 1.3;
1900 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1902 ModifyPower(POWER_RAGE, uint32(addRage*10));
1905 void Player::RegenerateAll()
1907 if (m_regenTimer != 0)
1908 return;
1909 uint32 regenDelay = 2000;
1911 // Not in combat or they have regeneration
1912 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1913 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1915 RegenerateHealth();
1916 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1918 Regenerate(POWER_RAGE);
1919 if(getClass() == CLASS_DEATH_KNIGHT)
1920 Regenerate(POWER_RUNIC_POWER);
1924 Regenerate( POWER_ENERGY );
1926 Regenerate( POWER_MANA );
1928 if(getClass() == CLASS_DEATH_KNIGHT)
1929 Regenerate( POWER_RUNE );
1931 m_regenTimer = regenDelay;
1934 void Player::Regenerate(Powers power)
1936 uint32 curValue = GetPower(power);
1937 uint32 maxValue = GetMaxPower(power);
1939 float addvalue = 0.0f;
1941 switch (power)
1943 case POWER_MANA:
1945 bool recentCast = IsUnderLastManaUseEffect();
1946 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1947 if (recentCast)
1949 // Mangos Updates Mana in intervals of 2s, which is correct
1950 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1952 else
1954 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1956 } break;
1957 case POWER_RAGE: // Regenerate rage
1959 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1960 addvalue = 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
1961 } break;
1962 case POWER_ENERGY: // Regenerate energy (rogue)
1963 addvalue = 20;
1964 break;
1965 case POWER_RUNIC_POWER:
1967 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1968 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1969 } break;
1970 case POWER_RUNE:
1972 for(uint32 i = 0; i < MAX_RUNES; ++i)
1973 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1974 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1975 } break;
1976 case POWER_FOCUS:
1977 case POWER_HAPPINESS:
1978 case POWER_HEALTH:
1979 break;
1982 // Mana regen calculated in Player::UpdateManaRegen()
1983 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1984 if(power != POWER_MANA)
1986 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1987 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1988 if ((*i)->GetModifier()->m_miscvalue == power)
1989 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1992 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1994 curValue += uint32(addvalue);
1995 if (curValue > maxValue)
1996 curValue = maxValue;
1998 else
2000 if(curValue <= uint32(addvalue))
2001 curValue = 0;
2002 else
2003 curValue -= uint32(addvalue);
2005 SetPower(power, curValue);
2008 void Player::RegenerateHealth()
2010 uint32 curValue = GetHealth();
2011 uint32 maxValue = GetMaxHealth();
2013 if (curValue >= maxValue) return;
2015 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
2017 float addvalue = 0.0f;
2019 // polymorphed case
2020 if ( IsPolymorphed() )
2021 addvalue = GetMaxHealth()/3;
2022 // normal regen case (maybe partly in combat case)
2023 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
2025 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
2026 if (!isInCombat())
2028 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
2029 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
2030 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
2032 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
2033 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
2035 if(!IsStandState())
2036 addvalue *= 1.5;
2039 // always regeneration bonus (including combat)
2040 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
2042 if(addvalue < 0)
2043 addvalue = 0;
2045 ModifyHealth(int32(addvalue));
2048 bool Player::CanInteractWithNPCs(bool alive) const
2050 if(alive && !isAlive())
2051 return false;
2052 if(isInFlight())
2053 return false;
2055 return true;
2058 Creature*
2059 Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
2061 // unit checks
2062 if (!guid)
2063 return NULL;
2065 if(!IsInWorld())
2066 return NULL;
2068 // exist (we need look pets also for some interaction (quest/etc)
2069 Creature *unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
2070 if (!unit)
2071 return NULL;
2073 // player check
2074 if(!CanInteractWithNPCs(!unit->isSpiritService()))
2075 return NULL;
2077 // appropriate npc type
2078 if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
2079 return NULL;
2081 // alive or spirit healer
2082 if(!unit->isAlive() && (!unit->isSpiritService() || isAlive() ))
2083 return NULL;
2085 // not allow interaction under control, but allow with own pets
2086 if(unit->GetCharmerGUID())
2087 return NULL;
2089 // not enemy
2090 if( unit->IsHostileTo(this))
2091 return NULL;
2093 // not unfriendly
2094 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
2095 if(factionTemplate->faction)
2096 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
2097 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
2098 return NULL;
2100 // not too far
2101 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
2102 return NULL;
2104 return unit;
2107 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
2109 if(GameObject *go = GetMap()->GetGameObject(guid))
2111 if(go->GetGoType() == type)
2113 float maxdist;
2114 switch(type)
2116 // TODO: find out how the client calculates the maximal usage distance to spellless working
2117 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2118 case GAMEOBJECT_TYPE_GUILD_BANK:
2119 case GAMEOBJECT_TYPE_MAILBOX:
2120 maxdist = 10.0f;
2121 break;
2122 case GAMEOBJECT_TYPE_FISHINGHOLE:
2123 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2124 break;
2125 default:
2126 maxdist = INTERACTION_DISTANCE;
2127 break;
2130 if (go->IsWithinDistInMap(this, maxdist))
2131 return go;
2133 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,
2134 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2137 return NULL;
2140 bool Player::IsUnderWater() const
2142 return IsInWater() &&
2143 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2146 void Player::SetInWater(bool apply)
2148 if(m_isInWater==apply)
2149 return;
2151 //define player in water by opcodes
2152 //move player's guid into HateOfflineList of those mobs
2153 //which can't swim and move guid back into ThreatList when
2154 //on surface.
2155 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2156 m_isInWater = apply;
2158 // remove auras that need water/land
2159 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2161 getHostilRefManager().updateThreatTables();
2164 void Player::SetGameMaster(bool on)
2166 if(on)
2168 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2169 setFaction(35);
2170 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2172 if (Pet* pet = GetPet())
2174 pet->setFaction(35);
2175 pet->getHostilRefManager().setOnlineOfflineState(false);
2178 for (int8 i = 0; i < MAX_TOTEM; ++i)
2179 if(m_TotemSlot[i])
2180 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2181 totem->setFaction(35);
2183 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2184 ResetContestedPvP();
2186 getHostilRefManager().setOnlineOfflineState(false);
2187 CombatStopWithPets();
2189 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2191 else
2193 // restore phase
2194 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2195 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2197 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2198 setFactionForRace(getRace());
2199 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2201 if (Pet* pet = GetPet())
2203 pet->setFaction(getFaction());
2204 pet->getHostilRefManager().setOnlineOfflineState(true);
2207 for (int8 i = 0; i < MAX_TOTEM; ++i)
2208 if(m_TotemSlot[i])
2209 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2210 totem->setFaction(getFaction());
2212 // restore FFA PvP Server state
2213 if(sWorld.IsFFAPvPRealm())
2214 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2216 // restore FFA PvP area state, remove not allowed for GM mounts
2217 UpdateArea(m_areaUpdateId);
2219 getHostilRefManager().setOnlineOfflineState(true);
2222 ObjectAccessor::UpdateVisibilityForPlayer(this);
2225 void Player::SetGMVisible(bool on)
2227 if(on)
2229 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2231 // Reapply stealth/invisibility if active or show if not any
2232 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2233 SetVisibility(VISIBILITY_GROUP_STEALTH);
2234 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2235 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2236 else
2237 SetVisibility(VISIBILITY_ON);
2239 else
2241 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2243 SetAcceptWhispers(false);
2244 SetGameMaster(true);
2246 SetVisibility(VISIBILITY_OFF);
2250 bool Player::IsGroupVisibleFor(Player* p) const
2252 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2254 default: return IsInSameGroupWith(p);
2255 case 1: return IsInSameRaidWith(p);
2256 case 2: return GetTeam()==p->GetTeam();
2260 bool Player::IsInSameGroupWith(Player const* p) const
2262 return p==this || GetGroup() != NULL &&
2263 GetGroup() == p->GetGroup() &&
2264 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2267 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2268 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2269 void Player::UninviteFromGroup()
2271 Group* group = GetGroupInvite();
2272 if(!group)
2273 return;
2275 group->RemoveInvite(this);
2277 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2279 if(group->IsCreated())
2281 group->Disband(true);
2282 objmgr.RemoveGroup(group);
2284 else
2285 group->RemoveAllInvites();
2287 delete group;
2291 void Player::RemoveFromGroup(Group* group, uint64 guid)
2293 if(group)
2295 if (group->RemoveMember(guid, 0) <= 1)
2297 // group->Disband(); already disbanded in RemoveMember
2298 objmgr.RemoveGroup(group);
2299 delete group;
2300 // removemember sets the player's group pointer to NULL
2305 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2307 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2308 data << uint64(victim ? victim->GetGUID() : 0); // guid
2309 data << uint32(GivenXP+RestXP); // given experience
2310 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2311 if(victim)
2313 data << uint32(GivenXP); // experience without rested bonus
2314 data << float(1); // 1 - none 0 - 100% group bonus output
2316 data << uint8(0); // new 2.4.0
2317 GetSession()->SendPacket(&data);
2320 void Player::GiveXP(uint32 xp, Unit* victim)
2322 if ( xp < 1 )
2323 return;
2325 if(!isAlive())
2326 return;
2328 uint32 level = getLevel();
2330 // XP to money conversion processed in Player::RewardQuest
2331 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2332 return;
2334 // handle SPELL_AURA_MOD_XP_PCT auras
2335 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2336 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2337 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2339 // XP resting bonus for kill
2340 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2342 SendLogXPGain(xp,victim,rested_bonus_xp);
2344 uint32 curXP = GetUInt32Value(PLAYER_XP);
2345 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2346 uint32 newXP = curXP + xp + rested_bonus_xp;
2348 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2350 newXP -= nextLvlXP;
2352 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2353 GiveLevel(level + 1);
2355 level = getLevel();
2356 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2359 SetUInt32Value(PLAYER_XP, newXP);
2362 // Update player to next level
2363 // Current player experience not update (must be update by caller)
2364 void Player::GiveLevel(uint32 level)
2366 if ( level == getLevel() )
2367 return;
2369 PlayerLevelInfo info;
2370 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2372 PlayerClassLevelInfo classInfo;
2373 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2375 // send levelup info to client
2376 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2377 data << uint32(level);
2378 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2379 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2380 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2381 data << uint32(0);
2382 data << uint32(0);
2383 data << uint32(0);
2384 data << uint32(0);
2385 data << uint32(0);
2386 data << uint32(0);
2387 // end for
2388 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2389 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2391 GetSession()->SendPacket(&data);
2393 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2395 //update level, max level of skills
2396 m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
2398 _ApplyAllLevelScaleItemMods(false);
2400 SetLevel(level);
2402 UpdateSkillsForLevel ();
2404 // save base values (bonuses already included in stored stats
2405 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2406 SetCreateStat(Stats(i), info.stats[i]);
2408 SetCreateHealth(classInfo.basehealth);
2409 SetCreateMana(classInfo.basemana);
2411 InitTalentForLevel();
2412 InitTaxiNodesForLevel();
2413 InitGlyphsForLevel();
2415 UpdateAllStats();
2417 // set current level health and mana/energy to maximum after applying all mods.
2418 SetHealth(GetMaxHealth());
2419 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2420 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2421 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2422 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2423 SetPower(POWER_FOCUS, 0);
2424 SetPower(POWER_HAPPINESS, 0);
2426 _ApplyAllLevelScaleItemMods(true);
2428 // update level to hunter/summon pet
2429 if (Pet* pet = GetPet())
2430 pet->SynchronizeLevelWithOwner();
2432 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2435 void Player::InitTalentForLevel()
2437 uint32 level = getLevel();
2438 // talents base at level diff ( talents = level - 9 but some can be used already)
2439 if(level < 10)
2441 // Remove all talent points
2442 if(m_usedTalentCount > 0) // Free any used talents
2444 resetTalents(true);
2445 SetFreeTalentPoints(0);
2448 else
2450 uint32 talentPointsForLevel = CalculateTalentsPoints();
2452 // if used more that have then reset
2453 if(m_usedTalentCount > talentPointsForLevel)
2455 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2456 resetTalents(true);
2457 else
2458 SetFreeTalentPoints(0);
2460 // else update amount of free points
2461 else
2462 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2465 if(!GetSession()->PlayerLoading())
2466 SendTalentsInfoData(false); // update at client
2469 void Player::InitStatsForLevel(bool reapplyMods)
2471 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2472 _RemoveAllStatBonuses();
2474 PlayerClassLevelInfo classInfo;
2475 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2477 PlayerLevelInfo info;
2478 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2480 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2481 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2483 UpdateSkillsForLevel ();
2485 // set default cast time multiplier
2486 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2488 // reset size before reapply auras
2489 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2491 // save base values (bonuses already included in stored stats
2492 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2493 SetCreateStat(Stats(i), info.stats[i]);
2495 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2496 SetStat(Stats(i), info.stats[i]);
2498 SetCreateHealth(classInfo.basehealth);
2500 //set create powers
2501 SetCreateMana(classInfo.basemana);
2503 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2505 InitStatBuffMods();
2507 //reset rating fields values
2508 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2509 SetUInt32Value(index, 0);
2511 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2512 for (int i = 0; i < 7; ++i)
2514 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2515 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2516 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2519 //reset attack power, damage and attack speed fields
2520 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2521 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2522 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2524 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2525 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2526 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2527 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2528 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2529 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2531 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2532 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2533 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2534 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2535 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2536 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2538 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2539 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2540 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2541 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2543 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2544 for (uint8 i = 0; i < 7; ++i)
2545 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2547 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2548 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2549 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2551 // Dodge percentage
2552 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2554 // set armor (resistance 0) to original value (create_agility*2)
2555 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2556 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2557 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2558 // set other resistance to original value (0)
2559 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2561 SetResistance(SpellSchools(i), 0);
2562 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2563 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2566 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2567 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2568 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2570 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2571 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2573 // Reset no reagent cost field
2574 for(int i = 0; i < 3; ++i)
2575 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2576 // Init data for form but skip reapply item mods for form
2577 InitDataForForm(reapplyMods);
2579 // save new stats
2580 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2581 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2583 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2585 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2586 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2588 // cleanup unit flags (will be re-applied if need at aura load).
2589 RemoveFlag( UNIT_FIELD_FLAGS,
2590 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2591 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2592 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2593 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2594 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2595 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2597 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2599 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2600 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2602 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2603 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2605 // restore if need some important flags
2606 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2608 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2609 _ApplyAllStatBonuses();
2611 // set current level health and mana/energy to maximum after applying all mods.
2612 SetHealth(GetMaxHealth());
2613 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2614 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2615 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2616 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2617 SetPower(POWER_FOCUS, 0);
2618 SetPower(POWER_HAPPINESS, 0);
2619 SetPower(POWER_RUNIC_POWER, 0);
2621 // update level to hunter/summon pet
2622 if (Pet* pet = GetPet())
2623 pet->SynchronizeLevelWithOwner();
2626 void Player::SendInitialSpells()
2628 time_t curTime = time(NULL);
2629 time_t infTime = curTime + infinityCooldownDelayCheck;
2631 uint16 spellCount = 0;
2633 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2634 data << uint8(0);
2636 size_t countPos = data.wpos();
2637 data << uint16(spellCount); // spell count placeholder
2639 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2641 if(itr->second->state == PLAYERSPELL_REMOVED)
2642 continue;
2644 if(!itr->second->active || itr->second->disabled)
2645 continue;
2647 data << uint32(itr->first);
2648 data << uint16(0); // it's not slot id
2650 spellCount +=1;
2653 data.put<uint16>(countPos,spellCount); // write real count value
2655 uint16 spellCooldowns = m_spellCooldowns.size();
2656 data << uint16(spellCooldowns);
2657 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2659 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2660 if(!sEntry)
2661 continue;
2663 data << uint32(itr->first);
2665 data << uint16(itr->second.itemid); // cast item id
2666 data << uint16(sEntry->Category); // spell category
2668 // send infinity cooldown in special format
2669 if(itr->second.end >= infTime)
2671 data << uint32(1); // cooldown
2672 data << uint32(0x80000000); // category cooldown
2673 continue;
2676 time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILISECONDS : 0;
2678 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2680 data << uint32(0); // cooldown
2681 data << uint32(cooldown); // category cooldown
2683 else
2685 data << uint32(cooldown); // cooldown
2686 data << uint32(0); // category cooldown
2690 GetSession()->SendPacket(&data);
2692 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2695 void Player::RemoveMail(uint32 id)
2697 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2699 if ((*itr)->messageID == id)
2701 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2702 m_mail.erase(itr);
2703 return;
2708 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2710 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2711 data << (uint32) mailId;
2712 data << (uint32) mailAction;
2713 data << (uint32) mailError;
2714 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2715 data << (uint32) equipError;
2716 else if( mailAction == MAIL_ITEM_TAKEN )
2718 data << (uint32) item_guid; // item guid low?
2719 data << (uint32) item_count; // item count?
2721 GetSession()->SendPacket(&data);
2724 void Player::SendNewMail()
2726 // deliver undelivered mail
2727 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2728 data << (uint32) 0;
2729 GetSession()->SendPacket(&data);
2732 void Player::UpdateNextMailTimeAndUnreads()
2734 // calculate next delivery time (min. from non-delivered mails
2735 // and recalculate unReadMail
2736 time_t cTime = time(NULL);
2737 m_nextMailDelivereTime = 0;
2738 unReadMails = 0;
2739 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2741 if((*itr)->deliver_time > cTime)
2743 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2744 m_nextMailDelivereTime = (*itr)->deliver_time;
2746 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2747 ++unReadMails;
2751 void Player::AddNewMailDeliverTime(time_t deliver_time)
2753 if(deliver_time <= time(NULL)) // ready now
2755 ++unReadMails;
2756 SendNewMail();
2758 else // not ready and no have ready mails
2760 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2761 m_nextMailDelivereTime = deliver_time;
2765 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2767 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2768 if (!spellInfo)
2770 // do character spell book cleanup (all characters)
2771 if(!IsInWorld() && !learning) // spell load case
2773 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2774 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2776 else
2777 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2779 return false;
2782 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2784 // do character spell book cleanup (all characters)
2785 if(!IsInWorld() && !learning) // spell load case
2787 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2788 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2790 else
2791 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2793 return false;
2796 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2798 bool dependent_set = false;
2799 bool disabled_case = false;
2800 bool superceded_old = false;
2802 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2803 if (itr != m_spells.end())
2805 uint32 next_active_spell_id = 0;
2806 // fix activate state for non-stackable low rank (and find next spell for !active case)
2807 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2809 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2810 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2812 if(HasSpell(next_itr->second))
2814 // high rank already known so this must !active
2815 active = false;
2816 next_active_spell_id = next_itr->second;
2817 break;
2822 // not do anything if already known in expected state
2823 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2824 itr->second->dependent == dependent && itr->second->disabled == disabled)
2826 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2827 itr->second->state = PLAYERSPELL_UNCHANGED;
2829 return false;
2832 // dependent spell known as not dependent, overwrite state
2833 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2835 itr->second->dependent = dependent;
2836 if (itr->second->state != PLAYERSPELL_NEW)
2837 itr->second->state = PLAYERSPELL_CHANGED;
2838 dependent_set = true;
2841 // update active state for known spell
2842 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2844 itr->second->active = active;
2846 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2847 itr->second->state = PLAYERSPELL_UNCHANGED;
2848 else if(itr->second->state != PLAYERSPELL_NEW)
2849 itr->second->state = PLAYERSPELL_CHANGED;
2851 if(active)
2853 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2854 CastSpell (this,spell_id,true);
2856 else if(IsInWorld())
2858 if(next_active_spell_id)
2860 // update spell ranks in spellbook and action bar
2861 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2862 data << uint32(spell_id);
2863 data << uint32(next_active_spell_id);
2864 GetSession()->SendPacket( &data );
2866 else
2868 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2869 data << uint32(spell_id);
2870 GetSession()->SendPacket(&data);
2874 return active; // learn (show in spell book if active now)
2877 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2879 if(itr->second->state != PLAYERSPELL_NEW)
2880 itr->second->state = PLAYERSPELL_CHANGED;
2881 itr->second->disabled = disabled;
2883 if(disabled)
2884 return false;
2886 disabled_case = true;
2888 else switch(itr->second->state)
2890 case PLAYERSPELL_UNCHANGED: // known saved spell
2891 return false;
2892 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2894 delete itr->second;
2895 m_spells.erase(itr);
2896 state = PLAYERSPELL_CHANGED;
2897 break; // need re-add
2899 default: // known not saved yet spell (new or modified)
2901 // can be in case spell loading but learned at some previous spell loading
2902 if(!IsInWorld() && !learning && !dependent_set)
2903 itr->second->state = PLAYERSPELL_UNCHANGED;
2905 return false;
2910 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2912 // talent: unlearn all other talent ranks (high and low)
2913 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2915 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2917 for(int i=0; i < MAX_TALENT_RANK; ++i)
2919 // skip learning spell and no rank spell case
2920 uint32 rankSpellId = talentInfo->RankID[i];
2921 if(!rankSpellId || rankSpellId==spell_id)
2922 continue;
2924 removeSpell(rankSpellId,false,false);
2928 // non talent spell: learn low ranks (recursive call)
2929 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2931 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2932 addSpell(prev_spell,active,true,true,disabled);
2933 else // at normal learning
2934 learnSpell(prev_spell,true);
2937 PlayerSpell *newspell = new PlayerSpell;
2938 newspell->state = state;
2939 newspell->active = active;
2940 newspell->dependent = dependent;
2941 newspell->disabled = disabled;
2943 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2944 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2946 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
2948 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
2949 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
2950 if(!i_spellInfo) continue;
2952 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
2954 if(itr2->second->active)
2956 if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
2958 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2960 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2961 data << uint32(itr2->first);
2962 data << uint32(spell_id);
2963 GetSession()->SendPacket( &data );
2966 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2967 itr2->second->active = false;
2968 if(itr2->second->state != PLAYERSPELL_NEW)
2969 itr2->second->state = PLAYERSPELL_CHANGED;
2970 superceded_old = true; // new spell replace old in action bars and spell book.
2972 else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
2974 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2976 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2977 data << uint32(spell_id);
2978 data << uint32(itr2->first);
2979 GetSession()->SendPacket( &data );
2982 // mark new spell as disable (not learned yet for client and will not learned)
2983 newspell->active = false;
2984 if(newspell->state != PLAYERSPELL_NEW)
2985 newspell->state = PLAYERSPELL_CHANGED;
2992 m_spells[spell_id] = newspell;
2994 // return false if spell disabled
2995 if (newspell->disabled)
2996 return false;
2999 uint32 talentCost = GetTalentSpellCost(spell_id);
3001 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3002 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3003 if (talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
3005 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3006 CastSpell(this, spell_id, true);
3008 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3009 else if (IsPassiveSpell(spell_id))
3011 if (IsNeedCastPassiveSpellAtLearn(spellInfo))
3012 CastSpell(this, spell_id, true);
3014 else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
3016 CastSpell(this, spell_id, true);
3017 return false;
3020 // update used talent points count
3021 m_usedTalentCount += talentCost;
3023 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3024 if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
3026 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3027 SetFreePrimaryProfessions(freeProfs-1);
3030 // add dependent skills
3031 uint16 maxskill = GetMaxSkillValueForLevel();
3033 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3035 SkillLineAbilityMapBounds skill_bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
3037 if (spellLearnSkill)
3039 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
3040 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
3042 if (skill_value < spellLearnSkill->value)
3043 skill_value = spellLearnSkill->value;
3045 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
3047 if (skill_max_value < new_skill_max_value)
3048 skill_max_value = new_skill_max_value;
3050 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
3052 else
3054 // not ranked skills
3055 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3057 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3058 if (!pSkill)
3059 continue;
3061 if (HasSkill(pSkill->id))
3062 continue;
3064 if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3065 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3066 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
3068 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
3070 case SKILL_RANGE_LANGUAGE:
3071 SetSkill(pSkill->id, 300, 300 );
3072 break;
3073 case SKILL_RANGE_LEVEL:
3074 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
3075 break;
3076 case SKILL_RANGE_MONO:
3077 SetSkill(pSkill->id, 1, 1 );
3078 break;
3079 default:
3080 break;
3086 // learn dependent spells
3087 SpellLearnSpellMapBounds spell_bounds = spellmgr.GetSpellLearnSpellMapBounds(spell_id);
3089 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3091 if (!itr2->second.autoLearned)
3093 if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
3094 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
3095 else // at normal learning
3096 learnSpell(itr2->second.spell,true);
3100 if (!GetSession()->PlayerLoading())
3102 // not ranked skills
3103 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3105 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3106 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3109 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3112 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3113 return active && !disabled && !superceded_old;
3116 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3118 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3119 // talent dependent passives activated at form apply have proper stance data
3120 bool need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1)));
3122 //Check CasterAuraStates
3123 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3126 void Player::learnSpell(uint32 spell_id, bool dependent)
3128 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3130 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3131 bool active = disabled ? itr->second->active : true;
3133 bool learning = addSpell(spell_id,active,true,dependent,false);
3135 // learn all disabled higher ranks (recursive)
3136 if(disabled)
3138 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3139 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3141 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3142 if (iter != m_spells.end() && iter->second->disabled)
3143 learnSpell(i->second,false);
3147 // prevent duplicated entires in spell book, also not send if not in world (loading)
3148 if(!learning || !IsInWorld ())
3149 return;
3151 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3152 data << uint32(spell_id);
3153 GetSession()->SendPacket(&data);
3156 void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank)
3158 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3159 if (itr == m_spells.end())
3160 return;
3162 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
3163 return;
3165 // unlearn non talent higher ranks (recursive)
3166 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3167 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3168 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3169 removeSpell(itr2->second,disabled,false);
3171 // re-search, it can be corrupted in prev loop
3172 itr = m_spells.find(spell_id);
3173 if (itr == m_spells.end())
3174 return; // already unleared
3176 bool cur_active = itr->second->active;
3177 bool cur_dependent = itr->second->dependent;
3179 if (disabled)
3181 itr->second->disabled = disabled;
3182 if(itr->second->state != PLAYERSPELL_NEW)
3183 itr->second->state = PLAYERSPELL_CHANGED;
3185 else
3187 if(itr->second->state == PLAYERSPELL_NEW)
3189 delete itr->second;
3190 m_spells.erase(itr);
3192 else
3193 itr->second->state = PLAYERSPELL_REMOVED;
3196 RemoveAurasDueToSpell(spell_id);
3198 // remove pet auras
3199 for(int i = 0; i < 3; ++i)
3200 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id, i))
3201 RemovePetAura(petSpell);
3203 // free talent points
3204 uint32 talentCosts = GetTalentSpellCost(spell_id);
3205 if(talentCosts > 0)
3207 if(talentCosts < m_usedTalentCount)
3208 m_usedTalentCount -= talentCosts;
3209 else
3210 m_usedTalentCount = 0;
3213 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3214 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3216 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3217 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3218 SetFreePrimaryProfessions(freeProfs);
3221 // remove dependent skill
3222 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3223 if(spellLearnSkill)
3225 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3226 if(!prev_spell) // first rank, remove skill
3227 SetSkill(spellLearnSkill->skill,0,0);
3228 else
3230 // search prev. skill setting by spell ranks chain
3231 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3232 while(!prevSkill && prev_spell)
3234 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3235 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3238 if (!prevSkill) // not found prev skill setting, remove skill
3239 SetSkill(spellLearnSkill->skill,0,0);
3240 else // set to prev. skill setting values
3242 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3243 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3245 if (skill_value > prevSkill->value)
3246 skill_value = prevSkill->value;
3248 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3250 if (skill_max_value > new_skill_max_value)
3251 skill_max_value = new_skill_max_value;
3253 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3258 else
3260 // not ranked skills
3261 SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
3263 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
3265 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3266 if (!pSkill)
3267 continue;
3269 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
3270 pSkill->categoryId != SKILL_CATEGORY_CLASS ||// not unlearn class skills (spellbook/talent pages)
3271 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3272 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
3274 // not reset skills for professions and racial abilities
3275 if ((pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3276 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0))
3277 continue;
3279 SetSkill(pSkill->id, 0, 0 );
3284 // remove dependent spells
3285 SpellLearnSpellMapBounds spell_bounds = spellmgr.GetSpellLearnSpellMapBounds(spell_id);
3287 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3288 removeSpell(itr2->second.spell, disabled);
3290 // activate lesser rank in spellbook/action bar, and cast it if need
3291 bool prev_activate = false;
3293 if (uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3295 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3297 // if talent then lesser rank also talent and need learn
3298 if (talentCosts)
3300 if(learn_low_rank)
3301 learnSpell (prev_id,false);
3303 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3304 else if (cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3306 // need manually update dependence state (learn spell ignore like attempts)
3307 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3308 if (prev_itr != m_spells.end())
3310 if (prev_itr->second->dependent != cur_dependent)
3312 prev_itr->second->dependent = cur_dependent;
3313 if (prev_itr->second->state != PLAYERSPELL_NEW)
3314 prev_itr->second->state = PLAYERSPELL_CHANGED;
3317 // now re-learn if need re-activate
3318 if (cur_active && !prev_itr->second->active && learn_low_rank)
3320 if (addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3322 // downgrade spell ranks in spellbook and action bar
3323 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3324 data << uint32(spell_id);
3325 data << uint32(prev_id);
3326 GetSession()->SendPacket( &data );
3327 prev_activate = true;
3334 // remove from spell book if not replaced by lesser rank
3335 if(!prev_activate)
3337 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3338 data << uint32(spell_id);
3339 GetSession()->SendPacket(&data);
3343 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3345 m_spellCooldowns.erase(spell_id);
3347 if(update)
3348 SendClearCooldown(spell_id, this);
3351 void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
3353 SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
3354 if (ct == sSpellCategoryStore.end())
3355 return;
3357 const SpellCategorySet& ct_set = ct->second;
3358 for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
3360 if (ct_set.find(i->first) != ct_set.end())
3361 RemoveSpellCooldown((i++)->first, update);
3362 else
3363 ++i;
3367 void Player::RemoveArenaSpellCooldowns()
3369 // remove cooldowns on spells that has < 15 min CD
3370 SpellCooldowns::iterator itr, next;
3371 // iterate spell cooldowns
3372 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3374 next = itr;
3375 ++next;
3376 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3377 // check if spellentry is present and if the cooldown is less than 15 mins
3378 if( entry &&
3379 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3380 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3382 // remove & notify
3383 RemoveSpellCooldown(itr->first, true);
3388 void Player::RemoveAllSpellCooldown()
3390 if(!m_spellCooldowns.empty())
3392 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3393 SendClearCooldown(itr->first, this);
3395 m_spellCooldowns.clear();
3399 void Player::_LoadSpellCooldowns(QueryResult *result)
3401 // some cooldowns can be already set at aura loading...
3403 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3405 if(result)
3407 time_t curTime = time(NULL);
3411 Field *fields = result->Fetch();
3413 uint32 spell_id = fields[0].GetUInt32();
3414 uint32 item_id = fields[1].GetUInt32();
3415 time_t db_time = (time_t)fields[2].GetUInt64();
3417 if(!sSpellStore.LookupEntry(spell_id))
3419 sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3420 continue;
3423 // skip outdated cooldown
3424 if(db_time <= curTime)
3425 continue;
3427 AddSpellCooldown(spell_id, item_id, db_time);
3429 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3431 while( result->NextRow() );
3433 delete result;
3437 void Player::_SaveSpellCooldowns()
3439 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3441 time_t curTime = time(NULL);
3442 time_t infTime = curTime + infinityCooldownDelayCheck;
3444 // remove outdated and save active
3445 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3447 if(itr->second.end <= curTime)
3448 m_spellCooldowns.erase(itr++);
3449 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3451 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));
3452 ++itr;
3454 else
3455 ++itr;
3459 uint32 Player::resetTalentsCost() const
3461 // The first time reset costs 1 gold
3462 if(m_resetTalentsCost < 1*GOLD)
3463 return 1*GOLD;
3464 // then 5 gold
3465 else if(m_resetTalentsCost < 5*GOLD)
3466 return 5*GOLD;
3467 // After that it increases in increments of 5 gold
3468 else if(m_resetTalentsCost < 10*GOLD)
3469 return 10*GOLD;
3470 else
3472 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3473 if(months > 0)
3475 // This cost will be reduced by a rate of 5 gold per month
3476 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3477 // to a minimum of 10 gold.
3478 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3480 else
3482 // After that it increases in increments of 5 gold
3483 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3484 // until it hits a cap of 50 gold.
3485 if(new_cost > 50*GOLD)
3486 new_cost = 50*GOLD;
3487 return new_cost;
3492 bool Player::resetTalents(bool no_cost)
3494 // not need after this call
3495 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3496 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
3498 uint32 talentPointsForLevel = CalculateTalentsPoints();
3500 if (m_usedTalentCount == 0)
3502 SetFreeTalentPoints(talentPointsForLevel);
3503 return false;
3506 uint32 cost = 0;
3508 if(!no_cost)
3510 cost = resetTalentsCost();
3512 if (GetMoney() < cost)
3514 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3515 return false;
3519 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3521 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3523 if (!talentInfo) continue;
3525 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3527 if(!talentTabInfo)
3528 continue;
3530 // unlearn only talents for character class
3531 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3532 // to prevent unexpected lost normal learned spell skip another class talents
3533 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3534 continue;
3536 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3538 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3540 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3542 ++itr;
3543 continue;
3546 // remove learned spells (all ranks)
3547 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3549 // unlearn if first rank is talent or learned by talent
3550 if (itrFirstId == talentInfo->RankID[j])
3552 removeSpell(itr->first,!IsPassiveSpell(itr->first),false);
3553 itr = GetSpellMap().begin();
3554 continue;
3556 else if (spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3558 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3559 itr = GetSpellMap().begin();
3560 continue;
3562 else
3563 ++itr;
3568 SetFreeTalentPoints(talentPointsForLevel);
3570 if(!no_cost)
3572 ModifyMoney(-(int32)cost);
3573 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3574 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3576 m_resetTalentsCost = cost;
3577 m_resetTalentsTime = time(NULL);
3580 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3581 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3582 /* when prev line will dropped use next line
3583 if(Pet* pet = GetPet())
3585 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3586 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3591 if(m_canTitanGrip)
3593 m_canTitanGrip = false;
3594 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3595 AutoUnequipOffhandIfNeed();
3598 return true;
3601 Mail* Player::GetMail(uint32 id)
3603 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3605 if ((*itr)->messageID == id)
3607 return (*itr);
3610 return NULL;
3613 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3615 if(target == this)
3617 Object::_SetCreateBits(updateMask, target);
3619 else
3621 for(uint16 index = 0; index < m_valuesCount; index++)
3623 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3624 updateMask->SetBit(index);
3629 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3631 if(target == this)
3633 Object::_SetUpdateBits(updateMask, target);
3635 else
3637 Object::_SetUpdateBits(updateMask, target);
3638 *updateMask &= updateVisualBits;
3642 void Player::InitVisibleBits()
3644 updateVisualBits.SetCount(PLAYER_END);
3646 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3647 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3648 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3649 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3650 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3651 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3652 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3653 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3654 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3655 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3656 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3657 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3658 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3659 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3660 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3661 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3662 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3663 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3664 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3665 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3666 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3667 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3668 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3669 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3670 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3671 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3672 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3673 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3674 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3675 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3676 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3677 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3678 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3679 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3680 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3681 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3682 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3683 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3684 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3685 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3686 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3687 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3688 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3689 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3690 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3691 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3692 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3693 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3694 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3695 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3696 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3697 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3698 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3699 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3700 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3702 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3703 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3704 updateVisualBits.SetBit(PLAYER_FLAGS);
3705 updateVisualBits.SetBit(PLAYER_GUILDID);
3706 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3707 updateVisualBits.SetBit(PLAYER_BYTES);
3708 updateVisualBits.SetBit(PLAYER_BYTES_2);
3709 updateVisualBits.SetBit(PLAYER_BYTES_3);
3710 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3711 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3713 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3714 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3715 updateVisualBits.SetBit(i);
3717 // Players visible items are not inventory stuff
3718 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3720 uint32 offset = i * 2;
3722 // item entry
3723 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3724 // enchant
3725 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3728 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3731 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3733 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3735 if(m_items[i] == NULL)
3736 continue;
3738 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3741 if(target == this)
3743 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3745 if(m_items[i] == NULL)
3746 continue;
3748 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3750 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3752 if(m_items[i] == NULL)
3753 continue;
3755 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3759 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3762 void Player::DestroyForPlayer( Player *target, bool anim ) const
3764 Unit::DestroyForPlayer( target, anim );
3766 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3768 if(m_items[i] == NULL)
3769 continue;
3771 m_items[i]->DestroyForPlayer( target );
3774 if(target == this)
3776 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3778 if(m_items[i] == NULL)
3779 continue;
3781 m_items[i]->DestroyForPlayer( target );
3783 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3785 if(m_items[i] == NULL)
3786 continue;
3788 m_items[i]->DestroyForPlayer( target );
3793 bool Player::HasSpell(uint32 spell) const
3795 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3796 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3797 !itr->second->disabled);
3800 bool Player::HasActiveSpell(uint32 spell) const
3802 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3803 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3804 itr->second->active && !itr->second->disabled);
3807 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3809 if (!trainer_spell)
3810 return TRAINER_SPELL_RED;
3812 if (!trainer_spell->learnedSpell)
3813 return TRAINER_SPELL_RED;
3815 // known spell
3816 if(HasSpell(trainer_spell->learnedSpell))
3817 return TRAINER_SPELL_GRAY;
3819 // check race/class requirement
3820 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3821 return TRAINER_SPELL_RED;
3823 // check level requirement
3824 if(getLevel() < trainer_spell->reqLevel)
3825 return TRAINER_SPELL_RED;
3827 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3829 // check prev.rank requirement
3830 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3831 return TRAINER_SPELL_RED;
3833 // check additional spell requirement
3834 if(spell_chain->req && !HasSpell(spell_chain->req))
3835 return TRAINER_SPELL_RED;
3838 // check skill requirement
3839 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3840 return TRAINER_SPELL_RED;
3842 // exist, already checked at loading
3843 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3845 // secondary prof. or not prof. spell
3846 uint32 skill = spell->EffectMiscValue[1];
3848 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3849 return TRAINER_SPELL_GREEN;
3851 // check primary prof. limit
3852 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
3853 return TRAINER_SPELL_GREEN_DISABLED;
3855 return TRAINER_SPELL_GREEN;
3858 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3860 uint32 guid = GUID_LOPART(playerguid);
3862 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3863 // bones will be deleted by corpse/bones deleting thread shortly
3864 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3866 // remove from guild
3867 uint32 guildId = GetGuildIdFromDB(playerguid);
3868 if(guildId != 0)
3870 Guild* guild = objmgr.GetGuildById(guildId);
3871 if(guild)
3872 guild->DelMember(guid);
3875 // remove from arena teams
3876 LeaveAllArenaTeams(playerguid);
3878 // the player was uninvited already on logout so just remove from group
3879 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3880 if(resultGroup)
3882 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3883 delete resultGroup;
3884 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3885 if(group)
3887 RemoveFromGroup(group, playerguid);
3891 // remove signs from petitions (also remove petitions if owner);
3892 RemovePetitionsAndSigns(playerguid, 10);
3894 // return back all mails with COD and Item 0 1 2 3 4 5 6
3895 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);
3896 if(resultMail)
3900 Field *fields = resultMail->Fetch();
3902 uint32 mail_id = fields[0].GetUInt32();
3903 uint16 mailTemplateId= fields[1].GetUInt16();
3904 uint32 sender = fields[2].GetUInt32();
3905 std::string subject = fields[3].GetCppString();
3906 uint32 itemTextId = fields[4].GetUInt32();
3907 uint32 money = fields[5].GetUInt32();
3908 bool has_items = fields[6].GetBool();
3910 //we can return mail now
3911 //so firstly delete the old one
3912 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3914 MailItemsInfo mi;
3915 if(has_items)
3917 // data needs to be at first place for Item::LoadFromDB
3918 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);
3919 if(resultItems)
3923 Field *fields2 = resultItems->Fetch();
3925 uint32 item_guidlow = fields2[1].GetUInt32();
3926 uint32 item_template = fields2[2].GetUInt32();
3928 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3929 if(!itemProto)
3931 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3932 continue;
3935 Item *pItem = NewItemOrBag(itemProto);
3936 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3938 pItem->FSetState(ITEM_REMOVED);
3939 pItem->SaveToDB(); // it also deletes item object !
3940 continue;
3943 mi.AddItem(item_guidlow, item_template, pItem);
3945 while (resultItems->NextRow());
3947 delete resultItems;
3951 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3953 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3955 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3957 while (resultMail->NextRow());
3959 delete resultMail;
3962 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3963 // Get guids of character's pets, will deleted in transaction
3964 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3966 // NOW we can finally clear other DB data related to character
3967 CharacterDatabase.BeginTransaction();
3968 if (resultPets)
3972 Field *fields3 = resultPets->Fetch();
3973 uint32 petguidlow = fields3[0].GetUInt32();
3974 Pet::DeleteFromDB(petguidlow);
3975 } while (resultPets->NextRow());
3976 delete resultPets;
3979 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3980 CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid);
3981 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3982 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3983 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3984 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3985 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3986 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3987 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3988 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3989 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3990 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3991 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3992 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3993 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3994 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3995 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3996 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3997 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3998 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3999 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
4000 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
4001 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
4002 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
4003 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u'",guid);
4004 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid);
4005 CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid);
4006 CharacterDatabase.CommitTransaction();
4008 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4009 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
4012 void Player::SetMovement(PlayerMovementType pType)
4014 WorldPacket data;
4015 switch(pType)
4017 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
4018 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
4019 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
4020 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
4021 default:
4022 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
4023 return;
4025 data.append(GetPackGUID());
4026 data << uint32(0);
4027 GetSession()->SendPacket( &data );
4030 /* Preconditions:
4031 - a resurrectable corpse must not be loaded for the player (only bones)
4032 - the player must be in world
4034 void Player::BuildPlayerRepop()
4036 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
4037 data.append(GetPackGUID());
4038 GetSession()->SendPacket(&data);
4040 if(getRace() == RACE_NIGHTELF)
4041 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)
4042 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4044 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4045 // there must be SMSG.STOP_MIRROR_TIMER
4046 // there we must send 888 opcode
4048 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4049 if(GetCorpse())
4051 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4052 assert(false);
4055 // create a corpse and place it at the player's location
4056 CreateCorpse();
4057 Corpse *corpse = GetCorpse();
4058 if(!corpse)
4060 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4061 return;
4063 GetMap()->Add(corpse);
4065 // convert player body to ghost
4066 SetHealth( 1 );
4068 SetMovement(MOVE_WATER_WALK);
4069 if(!GetSession()->isLogingOut())
4070 SetMovement(MOVE_UNROOT);
4072 // BG - remove insignia related
4073 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
4075 SendCorpseReclaimDelay();
4077 // to prevent cheating
4078 corpse->ResetGhostTime();
4080 StopMirrorTimers(); //disable timers(bars)
4082 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
4084 // set and clear other
4085 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
4088 void Player::SendDelayResponse(const uint32 ml_seconds)
4090 //FIXME: is this delay time arg really need? 50msec by default in code
4091 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
4092 data << (uint32)time(NULL);
4093 data << (uint32)0;
4094 GetSession()->SendPacket( &data );
4097 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
4099 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
4100 data << uint32(-1);
4101 data << float(0);
4102 data << float(0);
4103 data << float(0);
4104 GetSession()->SendPacket(&data);
4106 // speed change, land walk
4108 // remove death flag + set aura
4109 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4110 if(getRace() == RACE_NIGHTELF)
4111 RemoveAurasDueToSpell(20584); // speed bonuses
4112 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4114 setDeathState(ALIVE);
4116 SetMovement(MOVE_LAND_WALK);
4117 SetMovement(MOVE_UNROOT);
4119 m_deathTimer = 0;
4121 // set health/powers (0- will be set in caller)
4122 if(restore_percent>0.0f)
4124 SetHealth(uint32(GetMaxHealth()*restore_percent));
4125 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4126 SetPower(POWER_RAGE, 0);
4127 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4130 // trigger update zone for alive state zone updates
4131 uint32 newzone, newarea;
4132 GetZoneAndAreaId(newzone,newarea);
4133 UpdateZone(newzone,newarea);
4135 // update visibility
4136 ObjectAccessor::UpdateVisibilityForPlayer(this);
4138 if(!applySickness)
4139 return;
4141 //Characters from level 1-10 are not affected by resurrection sickness.
4142 //Characters from level 11-19 will suffer from one minute of sickness
4143 //for each level they are above 10.
4144 //Characters level 20 and up suffer from ten minutes of sickness.
4145 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
4147 if(int32(getLevel()) >= startLevel)
4149 // set resurrection sickness
4150 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4152 // not full duration
4153 if(int32(getLevel()) < startLevel+9)
4155 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4157 for(int i =0; i < 3; ++i)
4159 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4161 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4162 Aur->SendAuraUpdate(false);
4169 void Player::KillPlayer()
4171 SetMovement(MOVE_ROOT);
4173 StopMirrorTimers(); //disable timers(bars)
4175 setDeathState(CORPSE);
4176 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4178 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4179 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4181 // 6 minutes until repop at graveyard
4182 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4184 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4186 // don't create corpse at this moment, player might be falling
4188 // update visibility
4189 ObjectAccessor::UpdateObjectVisibility(this);
4192 void Player::CreateCorpse()
4194 // prevent existence 2 corpse for player
4195 SpawnCorpseBones();
4197 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4199 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4200 SetPvPDeath(false);
4202 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4204 delete corpse;
4205 return;
4208 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4209 _pb = GetUInt32Value(PLAYER_BYTES);
4210 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4212 uint8 race = (uint8)(_uf);
4213 uint8 skin = (uint8)(_pb);
4214 uint8 face = (uint8)(_pb >> 8);
4215 uint8 hairstyle = (uint8)(_pb >> 16);
4216 uint8 haircolor = (uint8)(_pb >> 24);
4217 uint8 facialhair = (uint8)(_pb2);
4219 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4220 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4222 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4223 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4225 uint32 flags = CORPSE_FLAG_UNK2;
4226 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4227 flags |= CORPSE_FLAG_HIDE_HELM;
4228 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4229 flags |= CORPSE_FLAG_HIDE_CLOAK;
4230 if(InBattleGround() && !InArena())
4231 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4232 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4234 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4236 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4238 uint32 iDisplayID;
4239 uint16 iIventoryType;
4240 uint32 _cfi;
4241 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4243 if(m_items[i])
4245 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4246 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4248 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4249 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4253 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4254 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4255 assert(entry);
4256 if(entry->map_type != MAP_BATTLEGROUND)
4257 corpse->SaveToDB();
4259 // register for player, but not show
4260 ObjectAccessor::Instance().AddCorpse(corpse);
4263 void Player::SpawnCorpseBones()
4265 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4266 SaveToDB(); // prevent loading as ghost without corpse
4269 Corpse* Player::GetCorpse() const
4271 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4274 void Player::DurabilityLossAll(double percent, bool inventory)
4276 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4277 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4278 DurabilityLoss(pItem,percent);
4280 if(inventory)
4282 // bags not have durability
4283 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4285 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4286 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4287 DurabilityLoss(pItem,percent);
4289 // keys not have durability
4290 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4292 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4293 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4294 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4295 if(Item* pItem = GetItemByPos( i, j ))
4296 DurabilityLoss(pItem,percent);
4300 void Player::DurabilityLoss(Item* item, double percent)
4302 if(!item )
4303 return;
4305 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4307 if(!pMaxDurability)
4308 return;
4310 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4312 if(pDurabilityLoss < 1 )
4313 pDurabilityLoss = 1;
4315 DurabilityPointsLoss(item,pDurabilityLoss);
4318 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4320 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4321 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4322 DurabilityPointsLoss(pItem,points);
4324 if(inventory)
4326 // bags not have durability
4327 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4329 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4330 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4331 DurabilityPointsLoss(pItem,points);
4333 // keys not have durability
4334 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4336 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4337 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4338 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4339 if(Item* pItem = GetItemByPos( i, j ))
4340 DurabilityPointsLoss(pItem,points);
4344 void Player::DurabilityPointsLoss(Item* item, int32 points)
4346 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4347 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4348 int32 pNewDurability = pOldDurability - points;
4350 if (pNewDurability < 0)
4351 pNewDurability = 0;
4352 else if (pNewDurability > pMaxDurability)
4353 pNewDurability = pMaxDurability;
4355 if (pOldDurability != pNewDurability)
4357 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4358 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4359 _ApplyItemMods(item,item->GetSlot(), false);
4361 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4363 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4364 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4365 _ApplyItemMods(item,item->GetSlot(), true);
4367 item->SetState(ITEM_CHANGED, this);
4371 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4373 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4374 DurabilityPointsLoss(pItem,1);
4377 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4379 uint32 TotalCost = 0;
4380 // equipped, backpack, bags itself
4381 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4382 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4384 // bank, buyback and keys not repaired
4386 // items in inventory bags
4387 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4388 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4389 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4390 return TotalCost;
4393 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4395 Item* item = GetItemByPos(pos);
4397 uint32 TotalCost = 0;
4398 if(!item)
4399 return TotalCost;
4401 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4402 if(!maxDurability)
4403 return TotalCost;
4405 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4407 if(cost)
4409 uint32 LostDurability = maxDurability - curDurability;
4410 if(LostDurability>0)
4412 ItemPrototype const *ditemProto = item->GetProto();
4414 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4415 if(!dcost)
4417 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4418 return TotalCost;
4421 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4422 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4423 if(!dQualitymodEntry)
4425 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4426 return TotalCost;
4429 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4430 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4432 costs = uint32(costs * discountMod);
4434 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4435 costs = 1;
4437 if (guildBank)
4439 if (GetGuildId()==0)
4441 DEBUG_LOG("You are not member of a guild");
4442 return TotalCost;
4445 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4446 if (!pGuild)
4447 return TotalCost;
4449 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4451 DEBUG_LOG("You do not have rights to withdraw for repairs");
4452 return TotalCost;
4455 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4457 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4458 return TotalCost;
4461 if (pGuild->GetGuildBankMoney() < costs)
4463 DEBUG_LOG("There is not enough money in bank");
4464 return TotalCost;
4467 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4468 TotalCost = costs;
4470 else if (GetMoney() < costs)
4472 DEBUG_LOG("You do not have enough money");
4473 return TotalCost;
4475 else
4476 ModifyMoney( -int32(costs) );
4480 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4481 item->SetState(ITEM_CHANGED, this);
4483 // reapply mods for total broken and repaired item if equipped
4484 if(IsEquipmentPos(pos) && !curDurability)
4485 _ApplyItemMods(item,pos & 255, true);
4486 return TotalCost;
4489 void Player::RepopAtGraveyard()
4491 // note: this can be called also when the player is alive
4492 // for example from WorldSession::HandleMovementOpcodes
4494 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4496 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4497 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4499 ResurrectPlayer(0.5f);
4500 SpawnCorpseBones();
4503 WorldSafeLocsEntry const *ClosestGrave = NULL;
4505 // Special handle for battleground maps
4506 if( BattleGround *bg = GetBattleGround() )
4507 ClosestGrave = bg->GetClosestGraveYard(this);
4508 else
4509 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4511 // stop countdown until repop
4512 m_deathTimer = 0;
4514 // if no grave found, stay at the current location
4515 // and don't show spirit healer location
4516 if(ClosestGrave)
4518 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4519 if(isDead()) // not send if alive, because it used in TeleportTo()
4521 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4522 data << ClosestGrave->map_id;
4523 data << ClosestGrave->x;
4524 data << ClosestGrave->y;
4525 data << ClosestGrave->z;
4526 GetSession()->SendPacket(&data);
4531 void Player::JoinedChannel(Channel *c)
4533 m_channels.push_back(c);
4536 void Player::LeftChannel(Channel *c)
4538 m_channels.remove(c);
4541 void Player::CleanupChannels()
4543 while(!m_channels.empty())
4545 Channel* ch = *m_channels.begin();
4546 m_channels.erase(m_channels.begin()); // remove from player's channel list
4547 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4548 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4549 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4552 sLog.outDebug("Player: channels cleaned up!");
4555 void Player::UpdateLocalChannels(uint32 newZone )
4557 if(m_channels.empty())
4558 return;
4560 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4561 if(!current_zone)
4562 return;
4564 ChannelMgr* cMgr = channelMgr(GetTeam());
4565 if(!cMgr)
4566 return;
4568 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4570 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4572 next = i; ++next;
4574 // skip non built-in channels
4575 if(!(*i)->IsConstant())
4576 continue;
4578 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4579 if(!ch)
4580 continue;
4582 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4583 continue;
4585 // new channel
4586 char new_channel_name_buf[100];
4587 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4588 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4590 if((*i)!=new_channel)
4592 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4594 // leave old channel
4595 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4596 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4597 LeftChannel(*i); // remove from player's channel list
4598 cMgr->LeftChannel(name); // delete if empty
4601 sLog.outDebug("Player: channels cleaned up!");
4604 void Player::LeaveLFGChannel()
4606 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4608 if((*i)->IsLFG())
4610 (*i)->Leave(GetGUID());
4611 break;
4616 void Player::UpdateDefense()
4618 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4620 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4622 // update dependent from defense skill part
4623 UpdateDefenseBonusesMod();
4627 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4629 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4631 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4632 return;
4635 float val = 1.0f;
4637 switch(modType)
4639 case FLAT_MOD:
4640 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4641 break;
4642 case PCT_MOD:
4643 if(amount <= -100.0f)
4644 amount = -200.0f;
4646 val = (100.0f + amount) / 100.0f;
4647 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4648 break;
4651 if(!CanModifyStats())
4652 return;
4654 switch(modGroup)
4656 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4657 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4658 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4659 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4660 default: break;
4664 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4666 if(modGroup >= BASEMOD_END || modType > MOD_END)
4668 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4669 return 0.0f;
4672 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4673 return 0.0f;
4675 return m_auraBaseMod[modGroup][modType];
4678 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4680 if(modGroup >= BASEMOD_END)
4682 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4683 return 0.0f;
4686 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4687 return 0.0f;
4689 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4692 uint32 Player::GetShieldBlockValue() const
4694 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4696 value = (value < 0) ? 0 : value;
4698 return uint32(value);
4701 float Player::GetMeleeCritFromAgility()
4703 uint32 level = getLevel();
4704 uint32 pclass = getClass();
4706 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4708 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4709 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4710 if (critBase==NULL || critRatio==NULL)
4711 return 0.0f;
4713 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4714 return crit*100.0f;
4717 float Player::GetDodgeFromAgility()
4719 // Table for base dodge values
4720 float dodge_base[MAX_CLASSES] = {
4721 0.0075f, // Warrior
4722 0.00652f, // Paladin
4723 -0.0545f, // Hunter
4724 -0.0059f, // Rogue
4725 0.03183f, // Priest
4726 0.0114f, // DK
4727 0.0167f, // Shaman
4728 0.034575f, // Mage
4729 0.02011f, // Warlock
4730 0.0f, // ??
4731 -0.0187f // Druid
4733 // Crit/agility to dodge/agility coefficient multipliers
4734 float crit_to_dodge[MAX_CLASSES] = {
4735 1.1f, // Warrior
4736 1.0f, // Paladin
4737 1.6f, // Hunter
4738 2.0f, // Rogue
4739 1.0f, // Priest
4740 1.0f, // DK?
4741 1.0f, // Shaman
4742 1.0f, // Mage
4743 1.0f, // Warlock
4744 0.0f, // ??
4745 1.7f // Druid
4748 uint32 level = getLevel();
4749 uint32 pclass = getClass();
4751 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4753 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4754 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4755 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4756 return 0.0f;
4758 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4759 return dodge*100.0f;
4762 float Player::GetSpellCritFromIntellect()
4764 uint32 level = getLevel();
4765 uint32 pclass = getClass();
4767 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4769 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4770 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4771 if (critBase==NULL || critRatio==NULL)
4772 return 0.0f;
4774 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4775 return crit*100.0f;
4778 float Player::GetRatingCoefficient(CombatRating cr) const
4780 uint32 level = getLevel();
4782 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4784 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4785 if (Rating == NULL)
4786 return 1.0f; // By default use minimum coefficient (not must be called)
4788 return Rating->ratio;
4791 float Player::GetRatingBonusValue(CombatRating cr) const
4793 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4796 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4798 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f;
4799 if (melee>33.0f) melee = 33.0f;
4800 return uint32 (melee * damage /100.0f);
4803 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4805 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f;
4806 if (ranged>33.0f) ranged=33.0f;
4807 return uint32 (ranged * damage /100.0f);
4810 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4812 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f;
4813 // In wow script resilience limited to 33%
4814 if (spell>33.0f)
4815 spell = 33.0f;
4816 return uint32 (spell * damage / 100.0f);
4819 uint32 Player::GetDotDamageReduction(uint32 damage) const
4821 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4822 // Dot resilience not limited (limit it by 100%)
4823 if (spellDot > 100.0f)
4824 spellDot = 100.0f;
4825 return uint32 (spellDot * damage / 100.0f);
4828 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4830 switch (attType)
4832 case BASE_ATTACK:
4833 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4834 case OFF_ATTACK:
4835 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4836 default:
4837 break;
4839 return 0.0f;
4842 float Player::OCTRegenHPPerSpirit()
4844 uint32 level = getLevel();
4845 uint32 pclass = getClass();
4847 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4849 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4850 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4851 if (baseRatio==NULL || moreRatio==NULL)
4852 return 0.0f;
4854 // Formula from PaperDollFrame script
4855 float spirit = GetStat(STAT_SPIRIT);
4856 float baseSpirit = spirit;
4857 if (baseSpirit>50) baseSpirit = 50;
4858 float moreSpirit = spirit - baseSpirit;
4859 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4860 return regen;
4863 float Player::OCTRegenMPPerSpirit()
4865 uint32 level = getLevel();
4866 uint32 pclass = getClass();
4868 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4870 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4871 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4872 if (moreRatio==NULL)
4873 return 0.0f;
4875 // Formula get from PaperDollFrame script
4876 float spirit = GetStat(STAT_SPIRIT);
4877 float regen = spirit * moreRatio->ratio;
4878 return regen;
4881 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4883 m_baseRatingValue[cr]+=(apply ? value : -value);
4885 int32 amount = uint32(m_baseRatingValue[cr]);
4886 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4887 // stat used stored in miscValueB for this aura
4888 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4889 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4890 if ((*i)->GetMiscValue() & (1<<cr))
4891 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4892 if (amount < 0)
4893 amount = 0;
4894 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4896 float RatingCoeffecient = GetRatingCoefficient(cr);
4897 float RatingChange = 0.0f;
4899 bool affectStats = CanModifyStats();
4901 switch (cr)
4903 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4904 case CR_DEFENSE_SKILL:
4905 UpdateDefenseBonusesMod();
4906 break;
4907 case CR_DODGE:
4908 UpdateDodgePercentage();
4909 break;
4910 case CR_PARRY:
4911 UpdateParryPercentage();
4912 break;
4913 case CR_BLOCK:
4914 UpdateBlockPercentage();
4915 break;
4916 case CR_HIT_MELEE:
4917 UpdateMeleeHitChances();
4918 break;
4919 case CR_HIT_RANGED:
4920 UpdateRangedHitChances();
4921 break;
4922 case CR_HIT_SPELL:
4923 UpdateSpellHitChances();
4924 break;
4925 case CR_CRIT_MELEE:
4926 if(affectStats)
4928 UpdateCritPercentage(BASE_ATTACK);
4929 UpdateCritPercentage(OFF_ATTACK);
4931 break;
4932 case CR_CRIT_RANGED:
4933 if(affectStats)
4934 UpdateCritPercentage(RANGED_ATTACK);
4935 break;
4936 case CR_CRIT_SPELL:
4937 if(affectStats)
4938 UpdateAllSpellCritChances();
4939 break;
4940 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4941 case CR_HIT_TAKEN_RANGED:
4942 break;
4943 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4944 break;
4945 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4946 case CR_CRIT_TAKEN_RANGED:
4947 break;
4948 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4949 break;
4950 case CR_HASTE_MELEE:
4951 RatingChange = value / RatingCoeffecient;
4952 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4953 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4954 break;
4955 case CR_HASTE_RANGED:
4956 RatingChange = value / RatingCoeffecient;
4957 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4958 break;
4959 case CR_HASTE_SPELL:
4960 RatingChange = value / RatingCoeffecient;
4961 ApplyCastTimePercentMod(RatingChange,apply);
4962 break;
4963 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4964 case CR_WEAPON_SKILL_OFFHAND:
4965 case CR_WEAPON_SKILL_RANGED:
4966 break;
4967 case CR_EXPERTISE:
4968 if(affectStats)
4970 UpdateExpertise(BASE_ATTACK);
4971 UpdateExpertise(OFF_ATTACK);
4973 break;
4974 case CR_ARMOR_PENETRATION:
4975 break;
4979 void Player::SetRegularAttackTime()
4981 for(int i = 0; i < MAX_ATTACK; ++i)
4983 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4984 if(tmpitem && !tmpitem->IsBroken())
4986 ItemPrototype const *proto = tmpitem->GetProto();
4987 if(proto->Delay)
4988 SetAttackTime(WeaponAttackType(i), proto->Delay);
4989 else
4990 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4995 //skill+step, checking for max value
4996 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4998 if(!skill_id)
4999 return false;
5001 uint16 i=0;
5002 for (; i < PLAYER_MAX_SKILLS; ++i)
5003 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
5004 break;
5006 if(i>=PLAYER_MAX_SKILLS)
5007 return false;
5009 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5010 uint32 value = SKILL_VALUE(data);
5011 uint32 max = SKILL_MAX(data);
5013 if ((!max) || (!value) || (value >= max))
5014 return false;
5016 if (value*512 < max*urand(0,512))
5018 uint32 new_value = value+step;
5019 if(new_value > max)
5020 new_value = max;
5022 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
5023 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
5024 return true;
5027 return false;
5030 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
5032 if ( SkillValue >= GrayLevel )
5033 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
5034 if ( SkillValue >= GreenLevel )
5035 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
5036 if ( SkillValue >= YellowLevel )
5037 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
5038 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
5041 bool Player::UpdateCraftSkill(uint32 spellid)
5043 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
5045 SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spellid);
5047 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
5049 if (_spell_idx->second->skillId)
5051 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
5053 // Alchemy Discoveries here
5054 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
5055 if (spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
5057 if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
5058 learnSpell(discoveredSpell,false);
5061 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
5063 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
5064 _spell_idx->second->max_value,
5065 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
5066 _spell_idx->second->min_value),
5067 craft_skill_gain);
5070 return false;
5073 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
5075 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
5077 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5079 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5080 switch (SkillId)
5082 case SKILL_HERBALISM:
5083 case SKILL_LOCKPICKING:
5084 case SKILL_JEWELCRAFTING:
5085 case SKILL_INSCRIPTION:
5086 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5087 case SKILL_SKINNING:
5088 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
5089 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5090 else
5091 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
5092 case SKILL_MINING:
5093 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
5094 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5095 else
5096 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
5098 return false;
5101 bool Player::UpdateFishingSkill()
5103 sLog.outDebug("UpdateFishingSkill");
5105 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5107 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5109 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5111 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5114 // levels sync. with spell requirement for skill levels to learn
5115 // bonus abilities in sSkillLineAbilityStore
5116 // Used only to avoid scan DBC at each skill grow
5117 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5119 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5121 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5122 if ( !SkillId )
5123 return false;
5125 if(Chance <= 0) // speedup in 0 chance case
5127 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5128 return false;
5131 uint16 i=0;
5132 for (; i < PLAYER_MAX_SKILLS; ++i)
5133 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
5134 if ( i >= PLAYER_MAX_SKILLS )
5135 return false;
5137 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5138 uint16 SkillValue = SKILL_VALUE(data);
5139 uint16 MaxValue = SKILL_MAX(data);
5141 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5142 return false;
5144 int32 Roll = irand(1,1000);
5146 if ( Roll <= Chance )
5148 uint32 new_value = SkillValue+step;
5149 if(new_value > MaxValue)
5150 new_value = MaxValue;
5152 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
5153 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5155 if((SkillValue < *bsl && new_value >= *bsl))
5157 learnSkillRewardedSpells( SkillId, new_value);
5158 break;
5161 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5162 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5163 return true;
5166 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5167 return false;
5170 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5172 // no skill gain in pvp
5173 Unit *pVictim = getVictim();
5174 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5175 return;
5177 if(IsInFeralForm())
5178 return; // always maximized SKILL_FERAL_COMBAT in fact
5180 if(m_form == FORM_TREE)
5181 return; // use weapon but not skill up
5183 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5185 switch(attType)
5187 case BASE_ATTACK:
5189 Item *tmpitem = GetWeaponForAttack(attType,true);
5191 if (!tmpitem)
5192 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5193 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5194 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5195 break;
5197 case OFF_ATTACK:
5198 case RANGED_ATTACK:
5200 Item *tmpitem = GetWeaponForAttack(attType,true);
5201 if (tmpitem)
5202 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5203 break;
5206 UpdateAllCritPercentages();
5209 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5211 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5212 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5213 uint32 moblevel = pVictim->getLevelForTarget(this);
5214 if(moblevel < greylevel)
5215 return;
5217 if (moblevel > plevel + 5)
5218 moblevel = plevel + 5;
5220 uint32 lvldif = moblevel - greylevel;
5221 if(lvldif < 3)
5222 lvldif = 3;
5224 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5225 if(skilldif <= 0)
5226 return;
5228 float chance = float(3 * lvldif * skilldif) / plevel;
5229 if(!defence)
5231 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5232 chance *= 0.1f * GetStat(STAT_INTELLECT);
5235 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5237 if(roll_chance_f(chance))
5239 if(defence)
5240 UpdateDefense();
5241 else
5242 UpdateWeaponSkill(attType);
5244 else
5245 return;
5248 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5250 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5251 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5253 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5254 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5255 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5257 if(talent) // permanent bonus stored in high part
5258 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5259 else // temporary/item bonus stored in low part
5260 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5261 return;
5265 void Player::UpdateSkillsForLevel()
5267 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5268 uint32 maxSkill = GetMaxSkillValueForLevel();
5270 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5272 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5273 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5275 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5277 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5278 if(!pSkill)
5279 continue;
5281 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5282 continue;
5284 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5285 uint32 max = SKILL_MAX(data);
5286 uint32 val = SKILL_VALUE(data);
5288 /// update only level dependent max skill values
5289 if(max!=1)
5291 /// miximize skill always
5292 if(alwaysMaxSkill)
5293 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5294 /// update max skill value if current max skill not maximized
5295 else if(max != maxconfskill)
5296 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5301 void Player::UpdateSkillsToMaxSkillsForLevel()
5303 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5304 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5306 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5307 if( IsProfessionOrRidingSkill(pskill))
5308 continue;
5309 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5311 uint32 max = SKILL_MAX(data);
5313 if(max > 1)
5314 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5316 if(pskill == SKILL_DEFENSE)
5317 UpdateDefenseBonusesMod();
5321 // This functions sets a skill line value (and adds if doesn't exist yet)
5322 // To "remove" a skill line, set it's values to zero
5323 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5325 if(!id)
5326 return;
5328 uint16 i=0;
5329 for (; i < PLAYER_MAX_SKILLS; ++i)
5330 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5332 if(i<PLAYER_MAX_SKILLS) //has skill
5334 if(currVal)
5336 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5337 learnSkillRewardedSpells(id, currVal);
5338 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5339 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5341 else //remove
5343 // clear skill fields
5344 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5345 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5346 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5348 // remove all spells that related to this skill
5349 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5350 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5351 if (pAbility->skillId==id)
5352 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5355 else if(currVal) //add
5357 for (i=0; i < PLAYER_MAX_SKILLS; ++i)
5358 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5360 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5361 if(!pSkill)
5363 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5364 return;
5366 // enable unlearn button for primary professions only
5367 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5368 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5369 else
5370 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5371 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5372 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5373 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5375 // apply skill bonuses
5376 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5378 // temporary bonuses
5379 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5380 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5381 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5382 (*j)->ApplyModifier(true);
5384 // permanent bonuses
5385 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5386 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5387 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5388 (*j)->ApplyModifier(true);
5390 // Learn all spells for skill
5391 learnSkillRewardedSpells(id, currVal);
5392 return;
5397 bool Player::HasSkill(uint32 skill) const
5399 if(!skill)return false;
5400 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5402 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5404 return true;
5407 return false;
5410 uint16 Player::GetSkillValue(uint32 skill) const
5412 if(!skill)
5413 return 0;
5415 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5417 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5419 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5421 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5422 result += SKILL_TEMP_BONUS(bonus);
5423 result += SKILL_PERM_BONUS(bonus);
5424 return result < 0 ? 0 : result;
5427 return 0;
5430 uint16 Player::GetMaxSkillValue(uint32 skill) const
5432 if(!skill)return 0;
5433 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5435 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5437 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5439 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5440 result += SKILL_TEMP_BONUS(bonus);
5441 result += SKILL_PERM_BONUS(bonus);
5442 return result < 0 ? 0 : result;
5445 return 0;
5448 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5450 if(!skill)return 0;
5451 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5453 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5455 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5458 return 0;
5461 uint16 Player::GetBaseSkillValue(uint32 skill) const
5463 if(!skill)return 0;
5464 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5466 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5468 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5469 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5470 return result < 0 ? 0 : result;
5473 return 0;
5476 uint16 Player::GetPureSkillValue(uint32 skill) const
5478 if(!skill)return 0;
5479 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5481 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5483 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5486 return 0;
5489 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5491 if(!skill)
5492 return 0;
5494 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5496 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5498 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5502 return 0;
5505 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5507 if(!skill)
5508 return 0;
5510 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5512 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5514 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5518 return 0;
5521 void Player::SendInitialActionButtons() const
5523 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5525 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5526 data << uint8(0); // can be 0, 1, 2 (talent spec)
5527 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5529 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5530 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5531 data << uint32(itr->second.packedData);
5532 else
5533 data << uint32(0);
5536 GetSession()->SendPacket( &data );
5537 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5540 ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type)
5542 if(button >= MAX_ACTION_BUTTONS)
5544 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5545 return NULL;
5548 if(action >= MAX_ACTION_BUTTON_ACTION_VALUE)
5550 sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, GetName(), MAX_ACTION_BUTTON_ACTION_VALUE );
5551 return NULL;
5554 switch(type)
5556 case ACTION_BUTTON_SPELL:
5557 if(!sSpellStore.LookupEntry(action))
5559 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5560 return NULL;
5563 if(!HasSpell(action))
5565 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5566 return NULL;
5568 break;
5569 case ACTION_BUTTON_ITEM:
5570 if(!objmgr.GetItemPrototype(action))
5572 sLog.outError( "Action %u not added into button %u for player %s: item not exist", action, button, GetName() );
5573 return NULL;
5575 break;
5576 default:
5577 break; // pther cases not checked at this moment
5581 // it create new button (NEW state) if need or return existed
5582 ActionButton& ab = m_actionButtons[button];
5584 // set data and update to CHANGED if not NEW
5585 ab.SetActionAndType(action,ActionButtonType(type));
5587 sLog.outDetail( "Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUIDLow(), action, uint32(type), button );
5588 return &ab;
5591 void Player::removeActionButton(uint8 button)
5593 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5594 if (buttonItr==m_actionButtons.end())
5595 return;
5597 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5598 m_actionButtons.erase(buttonItr); // new and not saved
5599 else
5600 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5602 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5605 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5607 // prevent crash when a bad coord is sent by the client
5608 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5610 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5611 return false;
5614 Map *m = GetMap();
5616 const float old_x = GetPositionX();
5617 const float old_y = GetPositionY();
5618 const float old_z = GetPositionZ();
5619 const float old_r = GetOrientation();
5621 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5623 if (teleport || old_x != x || old_y != y || old_z != z)
5624 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5625 else
5626 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5628 // move and update visible state if need
5629 m->PlayerRelocation(this, x, y, z, orientation);
5631 // reread after Map::Relocation
5632 m = GetMap();
5633 x = GetPositionX();
5634 y = GetPositionY();
5635 z = GetPositionZ();
5637 // group update
5638 if(GetGroup() && (old_x != x || old_y != y))
5639 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5642 // code block for underwater state update
5643 UpdateUnderwaterState(m, x, y, z);
5645 CheckExploreSystem();
5647 return true;
5650 void Player::SaveRecallPosition()
5652 m_recallMap = GetMapId();
5653 m_recallX = GetPositionX();
5654 m_recallY = GetPositionY();
5655 m_recallZ = GetPositionZ();
5656 m_recallO = GetOrientation();
5659 void Player::SendMessageToSet(WorldPacket *data, bool self)
5661 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5662 if(_map)
5664 _map->MessageBroadcast(this, data, self);
5665 return;
5668 //if player is not in world and map in not created/already destroyed
5669 //no need to create one, just send packet for itself!
5670 if(self)
5671 GetSession()->SendPacket(data);
5674 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5676 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5677 if(_map)
5679 _map->MessageDistBroadcast(this, data, dist, self);
5680 return;
5683 if(self)
5684 GetSession()->SendPacket(data);
5687 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5689 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5690 if(_map)
5692 _map->MessageDistBroadcast(this, data, dist, self, own_team_only);
5693 return;
5696 if(self)
5697 GetSession()->SendPacket(data);
5700 void Player::SendDirectMessage(WorldPacket *data)
5702 GetSession()->SendPacket(data);
5705 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5707 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5708 data << uint32(CinematicSequenceId);
5709 SendDirectMessage(&data);
5712 void Player::SendMovieStart(uint32 MovieId)
5714 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5715 data << uint32(MovieId);
5716 SendDirectMessage(&data);
5719 void Player::CheckExploreSystem()
5721 if (!isAlive())
5722 return;
5724 if (isInFlight())
5725 return;
5727 uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5728 if(areaFlag==0xffff)
5729 return;
5730 int offset = areaFlag / 32;
5732 if(offset >= 128)
5734 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);
5735 return;
5738 uint32 val = (uint32)(1 << (areaFlag % 32));
5739 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5741 if( !(currFields & val) )
5743 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5745 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5747 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5748 if(!p)
5750 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5752 else if(p->area_level > 0)
5754 uint32 area = p->ID;
5755 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5757 SendExplorationExperience(area,0);
5759 else
5761 int32 diff = int32(getLevel()) - p->area_level;
5762 uint32 XP = 0;
5763 if (diff < -5)
5765 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5767 else if (diff > 5)
5769 int32 exploration_percent = (100-((diff-5)*5));
5770 if (exploration_percent > 100)
5771 exploration_percent = 100;
5772 else if (exploration_percent < 0)
5773 exploration_percent = 0;
5775 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5777 else
5779 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5782 GiveXP( XP, NULL );
5783 SendExplorationExperience(area,XP);
5785 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5790 uint32 Player::TeamForRace(uint8 race)
5792 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5793 if(!rEntry)
5795 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5796 return ALLIANCE;
5799 switch(rEntry->TeamID)
5801 case 7: return ALLIANCE;
5802 case 1: return HORDE;
5805 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5806 return ALLIANCE;
5809 uint32 Player::getFactionForRace(uint8 race)
5811 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5812 if(!rEntry)
5814 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5815 return 0;
5818 return rEntry->FactionID;
5821 void Player::setFactionForRace(uint8 race)
5823 m_team = TeamForRace(race);
5824 setFaction( getFactionForRace(race) );
5827 ReputationRank Player::GetReputationRank(uint32 faction) const
5829 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5830 return GetReputationMgr().GetRank(factionEntry);
5833 //Calculate total reputation percent player gain with quest/creature level
5834 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5836 float percent = 100.0f;
5838 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5840 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5841 percent *= rate;
5843 float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5845 if (!for_quest)
5846 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
5848 percent += rep > 0 ? repMod : -repMod;
5850 if (percent <= 0.0f)
5851 return 0;
5853 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100.0f);
5856 //Calculates how many reputation points player gains in victim's enemy factions
5857 void Player::RewardReputation(Unit *pVictim, float rate)
5859 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5860 return;
5862 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5864 if(!Rep)
5865 return;
5867 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5869 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
5870 donerep1 = int32(donerep1*rate);
5871 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5872 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5873 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5874 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5876 // Wiki: Team factions value divided by 2
5877 if (factionEntry1 && Rep->is_teamaward1)
5879 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5880 if(team1_factionEntry)
5881 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5885 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5887 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
5888 donerep2 = int32(donerep2*rate);
5889 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5890 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5891 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5892 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5894 // Wiki: Team factions value divided by 2
5895 if (factionEntry2 && Rep->is_teamaward2)
5897 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5898 if(team2_factionEntry)
5899 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5904 //Calculate how many reputation points player gain with the quest
5905 void Player::RewardReputation(Quest const *pQuest)
5907 // quest reputation reward/loss
5908 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5910 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5912 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
5913 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5914 if(factionEntry)
5915 GetReputationMgr().ModifyReputation(factionEntry, rep);
5919 // TODO: implement reputation spillover
5922 void Player::UpdateArenaFields(void)
5924 /* arena calcs go here */
5927 void Player::UpdateHonorFields()
5929 /// called when rewarding honor and at each save
5930 uint64 now = time(NULL);
5931 uint64 today = uint64(time(NULL) / DAY) * DAY;
5933 if(m_lastHonorUpdateTime < today)
5935 uint64 yesterday = today - DAY;
5937 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5939 // update yesterday's contribution
5940 if(m_lastHonorUpdateTime >= yesterday )
5942 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5944 // this is the first update today, reset today's contribution
5945 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5946 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5948 else
5950 // no honor/kills yesterday or today, reset
5951 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5952 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5956 m_lastHonorUpdateTime = now;
5959 ///Calculate the amount of honor gained based on the victim
5960 ///and the size of the group for which the honor is divided
5961 ///An exact honor value can also be given (overriding the calcs)
5962 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5964 // do not reward honor in arenas, but enable onkill spellproc
5965 if(InArena())
5967 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5968 return false;
5970 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5971 return false;
5973 return true;
5976 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5977 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5978 return false;
5980 uint64 victim_guid = 0;
5981 uint32 victim_rank = 0;
5983 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5984 UpdateHonorFields();
5986 if(honor <= 0)
5988 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5989 return false;
5991 victim_guid = uVictim->GetGUID();
5993 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5995 Player *pVictim = (Player *)uVictim;
5997 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5998 return false;
6000 float f = 1; //need for total kills (?? need more info)
6001 uint32 k_grey = 0;
6002 uint32 k_level = getLevel();
6003 uint32 v_level = pVictim->getLevel();
6006 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6007 // [0] Just name
6008 // [1..14] Alliance honor titles and player name
6009 // [15..28] Horde honor titles and player name
6010 // [29..38] Other title and player name
6011 // [39+] Nothing
6012 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6013 // Get Killer titles, CharTitlesEntry::bit_index
6014 // Ranks:
6015 // title[1..14] -> rank[5..18]
6016 // title[15..28] -> rank[5..18]
6017 // title[other] -> 0
6018 if (victim_title == 0)
6019 victim_guid = 0; // Don't show HK: <rank> message, only log.
6020 else if (victim_title < 15)
6021 victim_rank = victim_title + 4;
6022 else if (victim_title < 29)
6023 victim_rank = victim_title - 14 + 4;
6024 else
6025 victim_guid = 0; // Don't show HK: <rank> message, only log.
6028 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6030 if(v_level<=k_grey)
6031 return false;
6033 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6035 int32 v_rank =1; //need more info
6037 honor = ((f * diff_level * (190 + v_rank*10))/6);
6038 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6040 // count the number of playerkills in one day
6041 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6042 // and those in a lifetime
6043 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6044 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
6045 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
6046 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
6048 else
6050 Creature *cVictim = (Creature *)uVictim;
6052 if (!cVictim->isRacialLeader())
6053 return false;
6055 honor = 100; // ??? need more info
6056 victim_rank = 19; // HK: Leader
6060 if (uVictim != NULL)
6062 honor *= sWorld.getRate(RATE_HONOR);
6064 if(groupsize > 1)
6065 honor /= groupsize;
6067 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6070 // honor - for show honor points in log
6071 // victim_guid - for show victim name in log
6072 // victim_rank [1..4] HK: <dishonored rank>
6073 // victim_rank [5..19] HK: <alliance\horde rank>
6074 // victim_rank [0,20+] HK: <>
6075 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6076 data << (uint32) honor;
6077 data << (uint64) victim_guid;
6078 data << (uint32) victim_rank;
6080 GetSession()->SendPacket(&data);
6082 // add honor points
6083 ModifyHonorPoints(int32(honor));
6085 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6086 return true;
6089 void Player::ModifyHonorPoints( int32 value )
6091 if(value < 0)
6093 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6094 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6095 else
6096 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6098 else
6099 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6102 void Player::ModifyArenaPoints( int32 value )
6104 if(value < 0)
6106 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6107 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6108 else
6109 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6111 else
6112 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6115 uint32 Player::GetGuildIdFromDB(uint64 guid)
6117 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6118 if(!result)
6119 return 0;
6121 uint32 id = result->Fetch()[0].GetUInt32();
6122 delete result;
6123 return id;
6126 uint32 Player::GetRankFromDB(uint64 guid)
6128 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6129 if( result )
6131 uint32 v = result->Fetch()[0].GetUInt32();
6132 delete result;
6133 return v;
6135 else
6136 return 0;
6139 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6141 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);
6142 if(!result)
6143 return 0;
6145 uint32 id = (*result)[0].GetUInt32();
6146 delete result;
6147 return id;
6150 uint32 Player::GetZoneIdFromDB(uint64 guid)
6152 uint32 guidLow = GUID_LOPART(guid);
6153 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6154 if (!result)
6155 return 0;
6156 Field* fields = result->Fetch();
6157 uint32 zone = fields[0].GetUInt32();
6158 delete result;
6160 if (!zone)
6162 // stored zone is zero, use generic and slow zone detection
6163 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6164 if( !result )
6165 return 0;
6166 fields = result->Fetch();
6167 uint32 map = fields[0].GetUInt32();
6168 float posx = fields[1].GetFloat();
6169 float posy = fields[2].GetFloat();
6170 float posz = fields[3].GetFloat();
6171 delete result;
6173 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6175 if (zone > 0)
6176 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6179 return zone;
6182 uint32 Player::GetLevelFromDB(uint64 guid)
6184 QueryResult *result = CharacterDatabase.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid) );
6185 if (!result)
6186 return 0;
6188 Field* fields = result->Fetch();
6189 uint32 level = fields[0].GetUInt32();
6190 delete result;
6192 return level;
6195 void Player::UpdateArea(uint32 newArea)
6197 // FFA_PVP flags are area and not zone id dependent
6198 // so apply them accordingly
6199 m_areaUpdateId = newArea;
6201 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6203 if(area && (area->flags & AREA_FLAG_ARENA))
6205 if(!isGameMaster())
6206 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6208 else
6210 // remove ffa flag only if not ffapvp realm
6211 // removal in sanctuaries and capitals is handled in zone update
6212 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6213 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6216 UpdateAreaDependentAuras(newArea);
6219 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6221 if(m_zoneUpdateId != newZone)
6222 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6224 m_zoneUpdateId = newZone;
6225 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6227 // zone changed, so area changed as well, update it
6228 UpdateArea(newArea);
6230 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6231 if(!zone)
6232 return;
6234 if (sWorld.getConfig(CONFIG_WEATHER))
6236 Weather *wth = sWorld.FindWeather(zone->ID);
6237 if(wth)
6239 wth->SendWeatherUpdateToPlayer(this);
6241 else
6243 if(!sWorld.AddWeather(zone->ID))
6245 // send fine weather packet to remove old zone's weather
6246 Weather::SendFineWeatherUpdateToPlayer(this);
6251 // in PvP, any not controlled zone (except zone->team == 6, default case)
6252 // in PvE, only opposition team capital
6253 switch(zone->team)
6255 case AREATEAM_ALLY:
6256 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6257 break;
6258 case AREATEAM_HORDE:
6259 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6260 break;
6261 case AREATEAM_NONE:
6262 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6263 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6264 break;
6265 default: // 6 in fact
6266 pvpInfo.inHostileArea = false;
6267 break;
6270 if(pvpInfo.inHostileArea) // in hostile area
6272 if(!IsPvP() || pvpInfo.endTimer != 0)
6273 UpdatePvP(true, true);
6275 else // in friendly area
6277 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6278 pvpInfo.endTimer = time(0); // start toggle-off
6281 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6283 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6284 if(sWorld.IsFFAPvPRealm())
6285 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6287 else
6289 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6292 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6294 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6295 SetRestType(REST_TYPE_IN_CITY);
6296 InnEnter(time(0),GetMapId(),0,0,0);
6298 if(sWorld.IsFFAPvPRealm())
6299 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6301 else // anywhere else
6303 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6305 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6307 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6309 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6310 SetRestType(REST_TYPE_NO);
6312 if(sWorld.IsFFAPvPRealm())
6313 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6316 else // not in tavern (leave city then)
6318 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6319 SetRestType(REST_TYPE_NO);
6321 // Set player to FFA PVP when not in rested environment.
6322 if(sWorld.IsFFAPvPRealm())
6323 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6328 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6329 // if player resurrected at teleport this will be applied in resurrect code
6330 if(isAlive())
6331 DestroyZoneLimitedItem( true, newZone );
6333 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6334 AutoUnequipOffhandIfNeed();
6336 // recent client version not send leave/join channel packets for built-in local channels
6337 UpdateLocalChannels( newZone );
6339 // group update
6340 if(GetGroup())
6341 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6343 UpdateZoneDependentAuras(newZone);
6346 //If players are too far way of duel flag... then player loose the duel
6347 void Player::CheckDuelDistance(time_t currTime)
6349 if(!duel)
6350 return;
6352 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6353 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6354 if(!obj)
6355 return;
6357 if(duel->outOfBound == 0)
6359 if(!IsWithinDistInMap(obj, 50))
6361 duel->outOfBound = currTime;
6363 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6364 GetSession()->SendPacket(&data);
6367 else
6369 if(IsWithinDistInMap(obj, 40))
6371 duel->outOfBound = 0;
6373 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6374 GetSession()->SendPacket(&data);
6376 else if(currTime >= (duel->outOfBound+10))
6378 DuelComplete(DUEL_FLED);
6383 void Player::DuelComplete(DuelCompleteType type)
6385 // duel not requested
6386 if(!duel)
6387 return;
6389 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6390 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6391 GetSession()->SendPacket(&data);
6392 duel->opponent->GetSession()->SendPacket(&data);
6394 if(type != DUEL_INTERUPTED)
6396 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6397 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6398 data << duel->opponent->GetName();
6399 data << GetName();
6400 SendMessageToSet(&data,true);
6403 if (type == DUEL_WON)
6405 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6406 if (duel->opponent)
6407 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6410 //Remove Duel Flag object
6411 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6412 if(obj)
6413 duel->initiator->RemoveGameObject(obj,true);
6415 /* remove auras */
6416 std::vector<uint32> auras2remove;
6417 AuraMap const& vAuras = duel->opponent->GetAuras();
6418 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6420 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6421 auras2remove.push_back(i->second->GetId());
6424 for(size_t i=0; i<auras2remove.size(); ++i)
6425 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6427 auras2remove.clear();
6428 AuraMap const& auras = GetAuras();
6429 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6431 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6432 auras2remove.push_back(i->second->GetId());
6434 for(size_t i=0; i<auras2remove.size(); ++i)
6435 RemoveAurasDueToSpell(auras2remove[i]);
6437 // cleanup combo points
6438 if(GetComboTarget()==duel->opponent->GetGUID())
6439 ClearComboPoints();
6440 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6441 ClearComboPoints();
6443 if(duel->opponent->GetComboTarget()==GetGUID())
6444 duel->opponent->ClearComboPoints();
6445 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6446 duel->opponent->ClearComboPoints();
6448 //cleanups
6449 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6450 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6451 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6452 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6454 delete duel->opponent->duel;
6455 duel->opponent->duel = NULL;
6456 delete duel;
6457 duel = NULL;
6460 //---------------------------------------------------------//
6462 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6464 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6465 return;
6467 // not apply/remove mods for broken item
6468 if(item->IsBroken())
6469 return;
6471 ItemPrototype const *proto = item->GetProto();
6473 if(!proto)
6474 return;
6476 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6478 uint32 attacktype = Player::GetAttackBySlot(slot);
6479 if(attacktype < MAX_ATTACK)
6480 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6482 _ApplyItemBonuses(proto,slot,apply);
6484 if( slot==EQUIPMENT_SLOT_RANGED )
6485 _ApplyAmmoBonuses();
6487 ApplyItemEquipSpell(item,apply);
6488 ApplyEnchantment(item, apply);
6490 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6491 CorrectMetaGemEnchants(slot, apply);
6493 sLog.outDebug("_ApplyItemMods complete.");
6496 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
6498 if (slot >= INVENTORY_SLOT_BAG_END || !proto)
6499 return;
6501 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
6502 if (only_level_scale && !ssd)
6503 return;
6505 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6506 uint32 ssd_level = getLevel();
6507 if (ssd && ssd_level > ssd->MaxLevel)
6508 ssd_level = ssd->MaxLevel;
6510 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
6511 if (only_level_scale && !ssv)
6512 return;
6514 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6516 uint32 statType = 0;
6517 int32 val = 0;
6518 // If set ScalingStatDistribution need get stats and values from it
6519 if (ssd && ssv)
6521 if (ssd->StatMod[i] < 0)
6522 continue;
6523 statType = ssd->StatMod[i];
6524 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6526 else
6528 if (i >= proto->StatsCount)
6529 continue;
6530 statType = proto->ItemStat[i].ItemStatType;
6531 val = proto->ItemStat[i].ItemStatValue;
6534 if(val == 0)
6535 continue;
6537 switch (statType)
6539 case ITEM_MOD_MANA:
6540 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6541 break;
6542 case ITEM_MOD_HEALTH: // modify HP
6543 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6544 break;
6545 case ITEM_MOD_AGILITY: // modify agility
6546 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6547 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6548 break;
6549 case ITEM_MOD_STRENGTH: //modify strength
6550 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6551 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6552 break;
6553 case ITEM_MOD_INTELLECT: //modify intellect
6554 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6555 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6556 break;
6557 case ITEM_MOD_SPIRIT: //modify spirit
6558 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6559 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6560 break;
6561 case ITEM_MOD_STAMINA: //modify stamina
6562 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6563 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6564 break;
6565 case ITEM_MOD_DEFENSE_SKILL_RATING:
6566 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6567 break;
6568 case ITEM_MOD_DODGE_RATING:
6569 ApplyRatingMod(CR_DODGE, int32(val), apply);
6570 break;
6571 case ITEM_MOD_PARRY_RATING:
6572 ApplyRatingMod(CR_PARRY, int32(val), apply);
6573 break;
6574 case ITEM_MOD_BLOCK_RATING:
6575 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6576 break;
6577 case ITEM_MOD_HIT_MELEE_RATING:
6578 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6579 break;
6580 case ITEM_MOD_HIT_RANGED_RATING:
6581 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6582 break;
6583 case ITEM_MOD_HIT_SPELL_RATING:
6584 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6585 break;
6586 case ITEM_MOD_CRIT_MELEE_RATING:
6587 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6588 break;
6589 case ITEM_MOD_CRIT_RANGED_RATING:
6590 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6591 break;
6592 case ITEM_MOD_CRIT_SPELL_RATING:
6593 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6594 break;
6595 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6596 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6597 break;
6598 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6599 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6600 break;
6601 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6602 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6603 break;
6604 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6605 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6606 break;
6607 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6608 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6609 break;
6610 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6611 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6612 break;
6613 case ITEM_MOD_HASTE_MELEE_RATING:
6614 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6615 break;
6616 case ITEM_MOD_HASTE_RANGED_RATING:
6617 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6618 break;
6619 case ITEM_MOD_HASTE_SPELL_RATING:
6620 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6621 break;
6622 case ITEM_MOD_HIT_RATING:
6623 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6624 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6625 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6626 break;
6627 case ITEM_MOD_CRIT_RATING:
6628 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6629 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6630 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6631 break;
6632 case ITEM_MOD_HIT_TAKEN_RATING:
6633 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6634 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6635 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6636 break;
6637 case ITEM_MOD_CRIT_TAKEN_RATING:
6638 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6639 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6640 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6641 break;
6642 case ITEM_MOD_RESILIENCE_RATING:
6643 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6644 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6645 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6646 break;
6647 case ITEM_MOD_HASTE_RATING:
6648 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6649 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6650 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6651 break;
6652 case ITEM_MOD_EXPERTISE_RATING:
6653 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6654 break;
6655 case ITEM_MOD_ATTACK_POWER:
6656 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6657 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6658 break;
6659 case ITEM_MOD_RANGED_ATTACK_POWER:
6660 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6661 break;
6662 case ITEM_MOD_FERAL_ATTACK_POWER:
6663 ApplyFeralAPBonus(int32(val), apply);
6664 break;
6665 case ITEM_MOD_MANA_REGENERATION:
6666 ApplyManaRegenBonus(int32(val), apply);
6667 break;
6668 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6669 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6670 break;
6671 case ITEM_MOD_SPELL_POWER:
6672 ApplySpellPowerBonus(int32(val), apply);
6673 break;
6674 // depricated item mods
6675 case ITEM_MOD_SPELL_HEALING_DONE:
6676 case ITEM_MOD_SPELL_DAMAGE_DONE:
6677 break;
6681 // If set ScalingStatValue armor get it or use item armor
6682 uint32 armor = proto->Armor;
6683 if (ssv)
6685 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6686 armor = ssvarmor;
6688 // Add armor bonus from ArmorDamageModifier if > 0
6689 if (proto->ArmorDamageModifier > 0)
6690 armor += uint32(proto->ArmorDamageModifier);
6692 if (armor)
6693 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6695 if (proto->Block)
6696 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6698 if (proto->HolyRes)
6699 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6701 if (proto->FireRes)
6702 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6704 if (proto->NatureRes)
6705 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6707 if (proto->FrostRes)
6708 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6710 if (proto->ShadowRes)
6711 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6713 if (proto->ArcaneRes)
6714 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6716 WeaponAttackType attType = BASE_ATTACK;
6717 float damage = 0.0f;
6719 if( slot == EQUIPMENT_SLOT_RANGED && (
6720 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6721 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6723 attType = RANGED_ATTACK;
6725 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6727 attType = OFF_ATTACK;
6730 float minDamage = proto->Damage[0].DamageMin;
6731 float maxDamage = proto->Damage[0].DamageMax;
6732 int32 extraDPS = 0;
6733 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6734 if (ssv)
6736 if (extraDPS = ssv->getDPSMod(proto->ScalingStatValue))
6738 float average = extraDPS * proto->Delay / 1000.0f;
6739 minDamage = 0.7f * average;
6740 maxDamage = 1.3f * average;
6743 if (minDamage > 0 )
6745 damage = apply ? minDamage : BASE_MINDAMAGE;
6746 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6747 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6750 if (maxDamage > 0 )
6752 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6753 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6756 // Apply feral bonus from ScalingStatValue if set
6757 if (ssv)
6759 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6760 ApplyFeralAPBonus(feral_bonus, apply);
6762 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6763 if(getClass() == CLASS_DRUID)
6765 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6766 if (feral_bonus > 0)
6767 ApplyFeralAPBonus(feral_bonus, apply);
6770 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6771 return;
6773 if (proto->Delay)
6775 if(slot == EQUIPMENT_SLOT_RANGED)
6776 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6777 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6778 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6779 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6780 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6783 if(CanModifyStats() && (damage || proto->Delay))
6784 UpdateDamagePhysical(attType);
6787 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6789 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6790 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6791 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6793 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6794 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6795 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6797 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6798 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6799 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6802 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6804 // generic not weapon specific case processes in aura code
6805 if(aura->GetSpellProto()->EquippedItemClass == -1)
6806 return;
6808 BaseModGroup mod = BASEMOD_END;
6809 switch(attackType)
6811 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6812 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6813 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6814 default: return;
6817 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6819 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6823 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6825 // ignore spell mods for not wands
6826 Modifier const* modifier = aura->GetModifier();
6827 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6828 return;
6830 // generic not weapon specific case processes in aura code
6831 if(aura->GetSpellProto()->EquippedItemClass == -1)
6832 return;
6834 UnitMods unitMod = UNIT_MOD_END;
6835 switch(attackType)
6837 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6838 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6839 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6840 default: return;
6843 UnitModifierType unitModType = TOTAL_VALUE;
6844 switch(modifier->m_auraname)
6846 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6847 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6848 default: return;
6851 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6853 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6857 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6859 if(!item)
6860 return;
6862 ItemPrototype const *proto = item->GetProto();
6863 if(!proto)
6864 return;
6866 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6868 _Spell const& spellData = proto->Spells[i];
6870 // no spell
6871 if(!spellData.SpellId )
6872 continue;
6874 // wrong triggering type
6875 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6876 continue;
6878 // check if it is valid spell
6879 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6880 if(!spellproto)
6881 continue;
6883 ApplyEquipSpell(spellproto,item,apply,form_change);
6887 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6889 if(apply)
6891 // Cannot be used in this stance/form
6892 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6893 return;
6895 if(form_change) // check aura active state from other form
6897 bool found = false;
6898 for (int k=0; k < 3; ++k)
6900 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6901 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6903 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6905 found = true;
6906 break;
6909 if(found)
6910 break;
6913 if(found) // and skip re-cast already active aura at form change
6914 return;
6917 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6919 CastSpell(this,spellInfo,true,item);
6921 else
6923 if(form_change) // check aura compatibility
6925 // Cannot be used in this stance/form
6926 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6927 return; // and remove only not compatible at form change
6930 if(item)
6931 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6932 else
6933 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6937 void Player::UpdateEquipSpellsAtFormChange()
6939 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6941 if(m_items[i] && !m_items[i]->IsBroken())
6943 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6944 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6948 // item set bonuses not dependent from item broken state
6949 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6951 ItemSetEffect* eff = ItemSetEff[setindex];
6952 if(!eff)
6953 continue;
6955 for(uint32 y=0;y<8; ++y)
6957 SpellEntry const* spellInfo = eff->spells[y];
6958 if(!spellInfo)
6959 continue;
6961 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6962 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6967 void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
6969 Item *item = GetWeaponForAttack(attType, true);
6970 if(!item || item->IsBroken())
6971 return;
6973 ItemPrototype const *proto = item->GetProto();
6974 if(!proto)
6975 return;
6977 if (!Target || Target == this )
6978 return;
6980 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6982 _Spell const& spellData = proto->Spells[i];
6984 // no spell
6985 if(!spellData.SpellId )
6986 continue;
6988 // wrong triggering type
6989 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6990 continue;
6992 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6993 if(!spellInfo)
6995 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6996 continue;
6999 // not allow proc extra attack spell at extra attack
7000 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7001 return;
7003 float chance = spellInfo->procChance;
7005 if(spellData.SpellPPMRate)
7007 uint32 WeaponSpeed = proto->Delay;
7008 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7010 else if(chance > 100.0f)
7012 chance = GetWeaponProcChance();
7015 if (roll_chance_f(chance))
7016 CastSpell(Target, spellInfo->Id, true, item);
7019 // item combat enchantments
7020 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7022 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7023 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7024 if(!pEnchant) continue;
7025 for (int s=0;s<3;s++)
7027 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7028 continue;
7030 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7031 if (!spellInfo)
7033 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7034 continue;
7037 // Use first rank to access spell item enchant procs
7038 float ppmRate = spellmgr.GetItemEnchantProcChance(spellInfo->Id);
7040 float chance = ppmRate
7041 ? GetPPMProcChance(proto->Delay, ppmRate)
7042 : pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7045 ApplySpellMod(spellInfo->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
7046 ApplySpellMod(spellInfo->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
7048 if (roll_chance_f(chance))
7050 if(IsPositiveSpell(pEnchant->spellid[s]))
7051 CastSpell(this, pEnchant->spellid[s], true, item);
7052 else
7053 CastSpell(Target, pEnchant->spellid[s], true, item);
7059 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7061 ItemPrototype const* proto = item->GetProto();
7062 // special learning case
7063 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7065 uint32 learn_spell_id = proto->Spells[0].SpellId;
7066 uint32 learning_spell_id = proto->Spells[1].SpellId;
7068 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7069 if(!spellInfo)
7071 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7072 SendEquipError(EQUIP_ERR_NONE,item,NULL);
7073 return;
7076 Spell *spell = new Spell(this, spellInfo, false);
7077 spell->m_CastItem = item;
7078 spell->m_cast_count = cast_count; //set count of casts
7079 spell->m_currentBasePoints[0] = learning_spell_id;
7080 spell->prepare(&targets);
7081 return;
7084 // use triggered flag only for items with many spell casts and for not first cast
7085 int count = 0;
7087 // item spells casted at use
7088 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7090 _Spell const& spellData = proto->Spells[i];
7092 // no spell
7093 if(!spellData.SpellId)
7094 continue;
7096 // wrong triggering type
7097 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7098 continue;
7100 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7101 if(!spellInfo)
7103 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7104 continue;
7107 Spell *spell = new Spell(this, spellInfo, (count > 0));
7108 spell->m_CastItem = item;
7109 spell->m_cast_count = cast_count; // set count of casts
7110 spell->m_glyphIndex = glyphIndex; // glyph index
7111 spell->prepare(&targets);
7113 ++count;
7116 // Item enchantments spells casted at use
7117 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7119 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7120 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7121 if(!pEnchant) continue;
7122 for (int s=0;s<3;s++)
7124 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7125 continue;
7127 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7128 if (!spellInfo)
7130 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7131 continue;
7134 Spell *spell = new Spell(this, spellInfo, (count > 0));
7135 spell->m_CastItem = item;
7136 spell->m_cast_count = cast_count; // set count of casts
7137 spell->m_glyphIndex = glyphIndex; // glyph index
7138 spell->prepare(&targets);
7140 ++count;
7145 void Player::_RemoveAllItemMods()
7147 sLog.outDebug("_RemoveAllItemMods start.");
7149 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7151 if(m_items[i])
7153 ItemPrototype const *proto = m_items[i]->GetProto();
7154 if(!proto)
7155 continue;
7157 // item set bonuses not dependent from item broken state
7158 if(proto->ItemSet)
7159 RemoveItemsSetItem(this,proto);
7161 if(m_items[i]->IsBroken())
7162 continue;
7164 ApplyItemEquipSpell(m_items[i],false);
7165 ApplyEnchantment(m_items[i], false);
7169 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7171 if(m_items[i])
7173 if(m_items[i]->IsBroken())
7174 continue;
7175 ItemPrototype const *proto = m_items[i]->GetProto();
7176 if(!proto)
7177 continue;
7179 uint32 attacktype = Player::GetAttackBySlot(i);
7180 if(attacktype < MAX_ATTACK)
7181 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7183 _ApplyItemBonuses(proto,i, false);
7185 if( i == EQUIPMENT_SLOT_RANGED )
7186 _ApplyAmmoBonuses();
7190 sLog.outDebug("_RemoveAllItemMods complete.");
7193 void Player::_ApplyAllItemMods()
7195 sLog.outDebug("_ApplyAllItemMods start.");
7197 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7199 if(m_items[i])
7201 if(m_items[i]->IsBroken())
7202 continue;
7204 ItemPrototype const *proto = m_items[i]->GetProto();
7205 if(!proto)
7206 continue;
7208 uint32 attacktype = Player::GetAttackBySlot(i);
7209 if(attacktype < MAX_ATTACK)
7210 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7212 _ApplyItemBonuses(proto,i, true);
7214 if( i == EQUIPMENT_SLOT_RANGED )
7215 _ApplyAmmoBonuses();
7219 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7221 if(m_items[i])
7223 ItemPrototype const *proto = m_items[i]->GetProto();
7224 if(!proto)
7225 continue;
7227 // item set bonuses not dependent from item broken state
7228 if(proto->ItemSet)
7229 AddItemsSetItem(this,m_items[i]);
7231 if(m_items[i]->IsBroken())
7232 continue;
7234 ApplyItemEquipSpell(m_items[i],true);
7235 ApplyEnchantment(m_items[i], true);
7239 sLog.outDebug("_ApplyAllItemMods complete.");
7242 void Player::_ApplyAllLevelScaleItemMods(bool apply)
7244 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7246 if(m_items[i])
7248 if(m_items[i]->IsBroken())
7249 continue;
7251 ItemPrototype const *proto = m_items[i]->GetProto();
7252 if(!proto)
7253 continue;
7255 _ApplyItemBonuses(proto,i, apply, true);
7260 void Player::_ApplyAmmoBonuses()
7262 // check ammo
7263 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7264 if(!ammo_id)
7265 return;
7267 float currentAmmoDPS;
7269 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7270 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7271 currentAmmoDPS = 0.0f;
7272 else
7273 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7275 if(currentAmmoDPS == GetAmmoDPS())
7276 return;
7278 m_ammoDPS = currentAmmoDPS;
7280 if(CanModifyStats())
7281 UpdateDamagePhysical(RANGED_ATTACK);
7284 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7286 if(!ammo_proto)
7287 return false;
7289 // check ranged weapon
7290 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7291 if(!weapon || weapon->IsBroken() )
7292 return false;
7294 ItemPrototype const* weapon_proto = weapon->GetProto();
7295 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7296 return false;
7298 // check ammo ws. weapon compatibility
7299 switch(weapon_proto->SubClass)
7301 case ITEM_SUBCLASS_WEAPON_BOW:
7302 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7303 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7304 return false;
7305 break;
7306 case ITEM_SUBCLASS_WEAPON_GUN:
7307 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7308 return false;
7309 break;
7310 default:
7311 return false;
7314 return true;
7317 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7318 Called by remove insignia spell effect */
7319 void Player::RemovedInsignia(Player* looterPlr)
7321 if (!GetBattleGroundId())
7322 return;
7324 // If not released spirit, do it !
7325 if(m_deathTimer > 0)
7327 m_deathTimer = 0;
7328 BuildPlayerRepop();
7329 RepopAtGraveyard();
7332 Corpse *corpse = GetCorpse();
7333 if (!corpse)
7334 return;
7336 // We have to convert player corpse to bones, not to be able to resurrect there
7337 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7338 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7339 if (!bones)
7340 return;
7342 // Now we must make bones lootable, and send player loot
7343 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7345 // We store the level of our player in the gold field
7346 // We retrieve this information at Player::SendLoot()
7347 bones->loot.gold = getLevel();
7348 bones->lootRecipient = looterPlr;
7349 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7352 void Player::SendLootRelease( uint64 guid )
7354 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7355 data << uint64(guid) << uint8(1);
7356 SendDirectMessage( &data );
7359 void Player::SendLoot(uint64 guid, LootType loot_type)
7361 if (uint64 lguid = GetLootGUID())
7362 m_session->DoLootRelease(lguid);
7364 Loot *loot = 0;
7365 PermissionTypes permission = ALL_PERMISSION;
7367 sLog.outDebug("Player::SendLoot");
7368 if (IS_GAMEOBJECT_GUID(guid))
7370 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7371 GameObject *go = GetMap()->GetGameObject(guid);
7373 // not check distance for GO in case owned GO (fishing bobber case, for example)
7374 // And permit out of range GO with no owner in case fishing hole
7375 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7377 SendLootRelease(guid);
7378 return;
7381 loot = &go->loot;
7383 if (go->getLootState() == GO_READY)
7385 uint32 lootid = go->GetGOInfo()->GetLootId();
7387 if (lootid)
7389 sLog.outDebug(" if(lootid)");
7390 loot->clear();
7391 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7394 if (loot_type == LOOT_FISHING)
7395 go->getFishLoot(loot,this);
7397 go->SetLootState(GO_ACTIVATED);
7400 else if (IS_ITEM_GUID(guid))
7402 Item *item = GetItemByGuid( guid );
7404 if (!item)
7406 SendLootRelease(guid);
7407 return;
7410 loot = &item->loot;
7412 if (!item->m_lootGenerated)
7414 item->m_lootGenerated = true;
7415 loot->clear();
7417 switch(loot_type)
7419 case LOOT_DISENCHANTING:
7420 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7421 break;
7422 case LOOT_PROSPECTING:
7423 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7424 break;
7425 case LOOT_MILLING:
7426 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7427 break;
7428 default:
7429 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7430 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7431 break;
7435 else if (IS_CORPSE_GUID(guid)) // remove insignia
7437 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7439 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7441 SendLootRelease(guid);
7442 return;
7445 loot = &bones->loot;
7447 if (!bones->lootForBody)
7449 bones->lootForBody = true;
7450 uint32 pLevel = bones->loot.gold;
7451 bones->loot.clear();
7452 // It may need a better formula
7453 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7454 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7457 if (bones->lootRecipient != this)
7458 permission = NONE_PERMISSION;
7460 else
7462 Creature *creature = GetMap()->GetCreature(guid);
7464 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7465 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7467 SendLootRelease(guid);
7468 return;
7471 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7473 SendLootRelease(guid);
7474 return;
7477 loot = &creature->loot;
7479 if (loot_type == LOOT_PICKPOCKETING)
7481 if (!creature->lootForPickPocketed)
7483 creature->lootForPickPocketed = true;
7484 loot->clear();
7486 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7487 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7489 // Generate extra money for pick pocket loot
7490 const uint32 a = urand(0, creature->getLevel()/2);
7491 const uint32 b = urand(0, getLevel()/2);
7492 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7495 else
7497 // the player whose group may loot the corpse
7498 Player *recipient = creature->GetLootRecipient();
7499 if (!recipient)
7501 creature->SetLootRecipient(this);
7502 recipient = this;
7505 if (creature->lootForPickPocketed)
7507 creature->lootForPickPocketed = false;
7508 loot->clear();
7511 if (!creature->lootForBody)
7513 creature->lootForBody = true;
7514 loot->clear();
7516 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7517 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7519 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7521 if (Group* group = recipient->GetGroup())
7523 group->UpdateLooterGuid(creature,true);
7525 switch (group->GetLootMethod())
7527 case GROUP_LOOT:
7528 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7529 group->GroupLoot(recipient->GetGUID(), loot, creature);
7530 break;
7531 case NEED_BEFORE_GREED:
7532 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7533 break;
7534 case MASTER_LOOT:
7535 group->MasterLoot(recipient->GetGUID(), loot, creature);
7536 break;
7537 default:
7538 break;
7543 // possible only if creature->lootForBody && loot->empty() at spell cast check
7544 if (loot_type == LOOT_SKINNING)
7546 loot->clear();
7547 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7549 // set group rights only for loot_type != LOOT_SKINNING
7550 else
7552 if(Group* group = GetGroup())
7554 if (group == recipient->GetGroup())
7556 if (group->GetLootMethod() == FREE_FOR_ALL)
7557 permission = ALL_PERMISSION;
7558 else if (group->GetLooterGuid() == GetGUID())
7560 if (group->GetLootMethod() == MASTER_LOOT)
7561 permission = MASTER_PERMISSION;
7562 else
7563 permission = ALL_PERMISSION;
7565 else
7566 permission = GROUP_PERMISSION;
7568 else
7569 permission = NONE_PERMISSION;
7571 else if (recipient == this)
7572 permission = ALL_PERMISSION;
7573 else
7574 permission = NONE_PERMISSION;
7579 SetLootGUID(guid);
7581 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7582 switch(loot_type)
7584 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7585 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7586 default: break;
7589 // need know merged fishing/corpse loot type for achievements
7590 loot->loot_type = loot_type;
7592 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7594 data << uint64(guid);
7595 data << uint8(loot_type);
7596 data << LootView(*loot, this, permission);
7598 SendDirectMessage(&data);
7600 // add 'this' player as one of the players that are looting 'loot'
7601 if (permission != NONE_PERMISSION)
7602 loot->AddLooter(GetGUID());
7604 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7605 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7608 void Player::SendNotifyLootMoneyRemoved()
7610 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7611 GetSession()->SendPacket( &data );
7614 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7616 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7617 data << uint8(lootSlot);
7618 GetSession()->SendPacket( &data );
7621 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7623 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7624 data << Field;
7625 data << Value;
7626 GetSession()->SendPacket(&data);
7629 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7631 // data depends on zoneid/mapid...
7632 BattleGround* bg = GetBattleGround();
7633 uint16 NumberOfFields = 0;
7634 uint32 mapid = GetMapId();
7636 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7638 // may be exist better way to do this...
7639 switch(zoneid)
7641 case 0:
7642 case 1:
7643 case 4:
7644 case 8:
7645 case 10:
7646 case 11:
7647 case 12:
7648 case 36:
7649 case 38:
7650 case 40:
7651 case 41:
7652 case 51:
7653 case 267:
7654 case 1519:
7655 case 1537:
7656 case 2257:
7657 case 2918:
7658 NumberOfFields = 8;
7659 break;
7660 case 139:
7661 NumberOfFields = 41;
7662 break;
7663 case 1377:
7664 NumberOfFields = 15;
7665 break;
7666 case 2597:
7667 NumberOfFields = 83;
7668 break;
7669 case 3277:
7670 NumberOfFields = 16;
7671 break;
7672 case 3358:
7673 case 3820:
7674 NumberOfFields = 40;
7675 break;
7676 case 3483:
7677 NumberOfFields = 27;
7678 break;
7679 case 3518:
7680 NumberOfFields = 39;
7681 break;
7682 case 3519:
7683 NumberOfFields = 38;
7684 break;
7685 case 3521:
7686 NumberOfFields = 37;
7687 break;
7688 case 3698:
7689 case 3702:
7690 case 3968:
7691 NumberOfFields = 11;
7692 break;
7693 case 3703:
7694 NumberOfFields = 11;
7695 break;
7696 default:
7697 NumberOfFields = 12;
7698 break;
7701 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7702 data << uint32(mapid); // mapid
7703 data << uint32(zoneid); // zone id
7704 data << uint32(areaid); // area id, new 2.1.0
7705 data << uint16(NumberOfFields); // count of uint64 blocks
7706 data << uint32(0x8d8) << uint32(0x0); // 1
7707 data << uint32(0x8d7) << uint32(0x0); // 2
7708 data << uint32(0x8d6) << uint32(0x0); // 3
7709 data << uint32(0x8d5) << uint32(0x0); // 4
7710 data << uint32(0x8d4) << uint32(0x0); // 5
7711 data << uint32(0x8d3) << uint32(0x0); // 6
7712 // 7 1 - Arena season in progress, 0 - end of season
7713 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7714 // 8 Arena season id
7715 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7716 if(mapid == 530) // Outland
7718 data << uint32(0x9bf) << uint32(0x0); // 7
7719 data << uint32(0x9bd) << uint32(0xF); // 8
7720 data << uint32(0x9bb) << uint32(0xF); // 9
7722 switch(zoneid)
7724 case 1:
7725 case 11:
7726 case 12:
7727 case 38:
7728 case 40:
7729 case 51:
7730 case 1519:
7731 case 1537:
7732 case 2257:
7733 break;
7734 case 2597: // AV
7735 data << uint32(0x7ae) << uint32(0x1); // 7
7736 data << uint32(0x532) << uint32(0x1); // 8
7737 data << uint32(0x531) << uint32(0x0); // 9
7738 data << uint32(0x52e) << uint32(0x0); // 10
7739 data << uint32(0x571) << uint32(0x0); // 11
7740 data << uint32(0x570) << uint32(0x0); // 12
7741 data << uint32(0x567) << uint32(0x1); // 13
7742 data << uint32(0x566) << uint32(0x1); // 14
7743 data << uint32(0x550) << uint32(0x1); // 15
7744 data << uint32(0x544) << uint32(0x0); // 16
7745 data << uint32(0x536) << uint32(0x0); // 17
7746 data << uint32(0x535) << uint32(0x1); // 18
7747 data << uint32(0x518) << uint32(0x0); // 19
7748 data << uint32(0x517) << uint32(0x0); // 20
7749 data << uint32(0x574) << uint32(0x0); // 21
7750 data << uint32(0x573) << uint32(0x0); // 22
7751 data << uint32(0x572) << uint32(0x0); // 23
7752 data << uint32(0x56f) << uint32(0x0); // 24
7753 data << uint32(0x56e) << uint32(0x0); // 25
7754 data << uint32(0x56d) << uint32(0x0); // 26
7755 data << uint32(0x56c) << uint32(0x0); // 27
7756 data << uint32(0x56b) << uint32(0x0); // 28
7757 data << uint32(0x56a) << uint32(0x1); // 29
7758 data << uint32(0x569) << uint32(0x1); // 30
7759 data << uint32(0x568) << uint32(0x1); // 13
7760 data << uint32(0x565) << uint32(0x0); // 32
7761 data << uint32(0x564) << uint32(0x0); // 33
7762 data << uint32(0x563) << uint32(0x0); // 34
7763 data << uint32(0x562) << uint32(0x0); // 35
7764 data << uint32(0x561) << uint32(0x0); // 36
7765 data << uint32(0x560) << uint32(0x0); // 37
7766 data << uint32(0x55f) << uint32(0x0); // 38
7767 data << uint32(0x55e) << uint32(0x0); // 39
7768 data << uint32(0x55d) << uint32(0x0); // 40
7769 data << uint32(0x3c6) << uint32(0x4); // 41
7770 data << uint32(0x3c4) << uint32(0x6); // 42
7771 data << uint32(0x3c2) << uint32(0x4); // 43
7772 data << uint32(0x516) << uint32(0x1); // 44
7773 data << uint32(0x515) << uint32(0x0); // 45
7774 data << uint32(0x3b6) << uint32(0x6); // 46
7775 data << uint32(0x55c) << uint32(0x0); // 47
7776 data << uint32(0x55b) << uint32(0x0); // 48
7777 data << uint32(0x55a) << uint32(0x0); // 49
7778 data << uint32(0x559) << uint32(0x0); // 50
7779 data << uint32(0x558) << uint32(0x0); // 51
7780 data << uint32(0x557) << uint32(0x0); // 52
7781 data << uint32(0x556) << uint32(0x0); // 53
7782 data << uint32(0x555) << uint32(0x0); // 54
7783 data << uint32(0x554) << uint32(0x1); // 55
7784 data << uint32(0x553) << uint32(0x1); // 56
7785 data << uint32(0x552) << uint32(0x1); // 57
7786 data << uint32(0x551) << uint32(0x1); // 58
7787 data << uint32(0x54f) << uint32(0x0); // 59
7788 data << uint32(0x54e) << uint32(0x0); // 60
7789 data << uint32(0x54d) << uint32(0x1); // 61
7790 data << uint32(0x54c) << uint32(0x0); // 62
7791 data << uint32(0x54b) << uint32(0x0); // 63
7792 data << uint32(0x545) << uint32(0x0); // 64
7793 data << uint32(0x543) << uint32(0x1); // 65
7794 data << uint32(0x542) << uint32(0x0); // 66
7795 data << uint32(0x540) << uint32(0x0); // 67
7796 data << uint32(0x53f) << uint32(0x0); // 68
7797 data << uint32(0x53e) << uint32(0x0); // 69
7798 data << uint32(0x53d) << uint32(0x0); // 70
7799 data << uint32(0x53c) << uint32(0x0); // 71
7800 data << uint32(0x53b) << uint32(0x0); // 72
7801 data << uint32(0x53a) << uint32(0x1); // 73
7802 data << uint32(0x539) << uint32(0x0); // 74
7803 data << uint32(0x538) << uint32(0x0); // 75
7804 data << uint32(0x537) << uint32(0x0); // 76
7805 data << uint32(0x534) << uint32(0x0); // 77
7806 data << uint32(0x533) << uint32(0x0); // 78
7807 data << uint32(0x530) << uint32(0x0); // 79
7808 data << uint32(0x52f) << uint32(0x0); // 80
7809 data << uint32(0x52d) << uint32(0x1); // 81
7810 break;
7811 case 3277: // WS
7812 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7813 bg->FillInitialWorldStates(data);
7814 else
7816 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7817 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7818 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7819 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7820 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7821 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7822 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7823 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7825 break;
7826 case 3358: // AB
7827 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7828 bg->FillInitialWorldStates(data);
7829 else
7831 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7832 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7833 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7834 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7835 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7836 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7837 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7838 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7839 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7840 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7841 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7842 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7843 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7844 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7845 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7846 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7847 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7848 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7849 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7850 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7851 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7852 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7853 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7854 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7855 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7856 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7857 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7858 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7859 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7860 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7861 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7862 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7864 break;
7865 case 3820: // EY
7866 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7867 bg->FillInitialWorldStates(data);
7868 else
7870 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7871 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7872 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7873 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7874 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7875 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7876 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7877 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7878 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7879 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7880 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7881 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7882 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7883 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7884 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7885 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7886 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7887 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7888 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7889 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7890 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7891 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7892 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7893 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7894 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7895 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7896 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7897 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7898 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7899 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7900 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7901 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7902 // and some more ... unknown
7904 break;
7905 case 3483: // Hellfire Peninsula
7906 data << uint32(0x9ba) << uint32(0x1); // 10
7907 data << uint32(0x9b9) << uint32(0x1); // 11
7908 data << uint32(0x9b5) << uint32(0x0); // 12
7909 data << uint32(0x9b4) << uint32(0x1); // 13
7910 data << uint32(0x9b3) << uint32(0x0); // 14
7911 data << uint32(0x9b2) << uint32(0x0); // 15
7912 data << uint32(0x9b1) << uint32(0x1); // 16
7913 data << uint32(0x9b0) << uint32(0x0); // 17
7914 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7915 data << uint32(0x9ac) << uint32(0x0); // 19
7916 data << uint32(0x9a8) << uint32(0x0); // 20
7917 data << uint32(0x9a7) << uint32(0x0); // 21
7918 data << uint32(0x9a6) << uint32(0x1); // 22
7919 break;
7920 case 3519: // Terokkar Forest
7921 data << uint32(0xa41) << uint32(0x0); // 10
7922 data << uint32(0xa40) << uint32(0x14); // 11
7923 data << uint32(0xa3f) << uint32(0x0); // 12
7924 data << uint32(0xa3e) << uint32(0x0); // 13
7925 data << uint32(0xa3d) << uint32(0x5); // 14
7926 data << uint32(0xa3c) << uint32(0x0); // 15
7927 data << uint32(0xa87) << uint32(0x0); // 16
7928 data << uint32(0xa86) << uint32(0x0); // 17
7929 data << uint32(0xa85) << uint32(0x0); // 18
7930 data << uint32(0xa84) << uint32(0x0); // 19
7931 data << uint32(0xa83) << uint32(0x0); // 20
7932 data << uint32(0xa82) << uint32(0x0); // 21
7933 data << uint32(0xa81) << uint32(0x0); // 22
7934 data << uint32(0xa80) << uint32(0x0); // 23
7935 data << uint32(0xa7e) << uint32(0x0); // 24
7936 data << uint32(0xa7d) << uint32(0x0); // 25
7937 data << uint32(0xa7c) << uint32(0x0); // 26
7938 data << uint32(0xa7b) << uint32(0x0); // 27
7939 data << uint32(0xa7a) << uint32(0x0); // 28
7940 data << uint32(0xa79) << uint32(0x0); // 29
7941 data << uint32(0x9d0) << uint32(0x5); // 30
7942 data << uint32(0x9ce) << uint32(0x0); // 31
7943 data << uint32(0x9cd) << uint32(0x0); // 32
7944 data << uint32(0x9cc) << uint32(0x0); // 33
7945 data << uint32(0xa88) << uint32(0x0); // 34
7946 data << uint32(0xad0) << uint32(0x0); // 35
7947 data << uint32(0xacf) << uint32(0x1); // 36
7948 break;
7949 case 3521: // Zangarmarsh
7950 data << uint32(0x9e1) << uint32(0x0); // 10
7951 data << uint32(0x9e0) << uint32(0x0); // 11
7952 data << uint32(0x9df) << uint32(0x0); // 12
7953 data << uint32(0xa5d) << uint32(0x1); // 13
7954 data << uint32(0xa5c) << uint32(0x0); // 14
7955 data << uint32(0xa5b) << uint32(0x1); // 15
7956 data << uint32(0xa5a) << uint32(0x0); // 16
7957 data << uint32(0xa59) << uint32(0x1); // 17
7958 data << uint32(0xa58) << uint32(0x0); // 18
7959 data << uint32(0xa57) << uint32(0x0); // 19
7960 data << uint32(0xa56) << uint32(0x0); // 20
7961 data << uint32(0xa55) << uint32(0x1); // 21
7962 data << uint32(0xa54) << uint32(0x0); // 22
7963 data << uint32(0x9e7) << uint32(0x0); // 23
7964 data << uint32(0x9e6) << uint32(0x0); // 24
7965 data << uint32(0x9e5) << uint32(0x0); // 25
7966 data << uint32(0xa00) << uint32(0x0); // 26
7967 data << uint32(0x9ff) << uint32(0x1); // 27
7968 data << uint32(0x9fe) << uint32(0x0); // 28
7969 data << uint32(0x9fd) << uint32(0x0); // 29
7970 data << uint32(0x9fc) << uint32(0x1); // 30
7971 data << uint32(0x9fb) << uint32(0x0); // 31
7972 data << uint32(0xa62) << uint32(0x0); // 32
7973 data << uint32(0xa61) << uint32(0x1); // 33
7974 data << uint32(0xa60) << uint32(0x1); // 34
7975 data << uint32(0xa5f) << uint32(0x0); // 35
7976 break;
7977 case 3698: // Nagrand Arena
7978 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7979 bg->FillInitialWorldStates(data);
7980 else
7982 data << uint32(0xa0f) << uint32(0x0); // 7
7983 data << uint32(0xa10) << uint32(0x0); // 8
7984 data << uint32(0xa11) << uint32(0x0); // 9 show
7986 break;
7987 case 3702: // Blade's Edge Arena
7988 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7989 bg->FillInitialWorldStates(data);
7990 else
7992 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7993 data << uint32(0x9f1) << uint32(0x0); // 8 green
7994 data << uint32(0x9f3) << uint32(0x0); // 9 show
7996 break;
7997 case 3968: // Ruins of Lordaeron
7998 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7999 bg->FillInitialWorldStates(data);
8000 else
8002 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8003 data << uint32(0xbb9) << uint32(0x0); // 8 green
8004 data << uint32(0xbba) << uint32(0x0); // 9 show
8006 break;
8007 case 3703: // Shattrath City
8008 break;
8009 default:
8010 data << uint32(0x914) << uint32(0x0); // 7
8011 data << uint32(0x913) << uint32(0x0); // 8
8012 data << uint32(0x912) << uint32(0x0); // 9
8013 data << uint32(0x915) << uint32(0x0); // 10
8014 break;
8016 GetSession()->SendPacket(&data);
8019 uint32 Player::GetXPRestBonus(uint32 xp)
8021 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8023 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8024 rested_bonus = xp;
8026 SetRestBonus( GetRestBonus() - rested_bonus);
8028 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8029 return rested_bonus;
8032 void Player::SetBindPoint(uint64 guid)
8034 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8035 data << uint64(guid);
8036 GetSession()->SendPacket( &data );
8039 void Player::SendTalentWipeConfirm(uint64 guid)
8041 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8042 data << uint64(guid);
8043 data << uint32(resetTalentsCost());
8044 GetSession()->SendPacket( &data );
8047 void Player::SendPetSkillWipeConfirm()
8049 Pet* pet = GetPet();
8050 if(!pet)
8051 return;
8052 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8053 data << pet->GetGUID();
8054 data << uint32(pet->resetTalentsCost());
8055 GetSession()->SendPacket( &data );
8058 /*********************************************************/
8059 /*** STORAGE SYSTEM ***/
8060 /*********************************************************/
8062 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8064 assert(i < 3);
8065 if(i < 2 && item)
8067 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8068 return;
8069 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8070 if(charges == 0)
8071 return;
8072 if(charges > 1)
8073 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8074 else if(charges <= 1)
8076 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8077 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8082 void Player::SetSheath( SheathState sheathed )
8084 switch (sheathed)
8086 case SHEATH_STATE_UNARMED: // no prepared weapon
8087 SetVirtualItemSlot(0,NULL);
8088 SetVirtualItemSlot(1,NULL);
8089 SetVirtualItemSlot(2,NULL);
8090 break;
8091 case SHEATH_STATE_MELEE: // prepared melee weapon
8093 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
8094 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
8095 SetVirtualItemSlot(2,NULL);
8096 }; break;
8097 case SHEATH_STATE_RANGED: // prepared ranged weapon
8098 SetVirtualItemSlot(0,NULL);
8099 SetVirtualItemSlot(1,NULL);
8100 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
8101 break;
8102 default:
8103 SetVirtualItemSlot(0,NULL);
8104 SetVirtualItemSlot(1,NULL);
8105 SetVirtualItemSlot(2,NULL);
8106 break;
8108 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
8111 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8113 uint8 pClass = getClass();
8115 uint8 slots[4];
8116 slots[0] = NULL_SLOT;
8117 slots[1] = NULL_SLOT;
8118 slots[2] = NULL_SLOT;
8119 slots[3] = NULL_SLOT;
8120 switch( proto->InventoryType )
8122 case INVTYPE_HEAD:
8123 slots[0] = EQUIPMENT_SLOT_HEAD;
8124 break;
8125 case INVTYPE_NECK:
8126 slots[0] = EQUIPMENT_SLOT_NECK;
8127 break;
8128 case INVTYPE_SHOULDERS:
8129 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8130 break;
8131 case INVTYPE_BODY:
8132 slots[0] = EQUIPMENT_SLOT_BODY;
8133 break;
8134 case INVTYPE_CHEST:
8135 slots[0] = EQUIPMENT_SLOT_CHEST;
8136 break;
8137 case INVTYPE_ROBE:
8138 slots[0] = EQUIPMENT_SLOT_CHEST;
8139 break;
8140 case INVTYPE_WAIST:
8141 slots[0] = EQUIPMENT_SLOT_WAIST;
8142 break;
8143 case INVTYPE_LEGS:
8144 slots[0] = EQUIPMENT_SLOT_LEGS;
8145 break;
8146 case INVTYPE_FEET:
8147 slots[0] = EQUIPMENT_SLOT_FEET;
8148 break;
8149 case INVTYPE_WRISTS:
8150 slots[0] = EQUIPMENT_SLOT_WRISTS;
8151 break;
8152 case INVTYPE_HANDS:
8153 slots[0] = EQUIPMENT_SLOT_HANDS;
8154 break;
8155 case INVTYPE_FINGER:
8156 slots[0] = EQUIPMENT_SLOT_FINGER1;
8157 slots[1] = EQUIPMENT_SLOT_FINGER2;
8158 break;
8159 case INVTYPE_TRINKET:
8160 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8161 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8162 break;
8163 case INVTYPE_CLOAK:
8164 slots[0] = EQUIPMENT_SLOT_BACK;
8165 break;
8166 case INVTYPE_WEAPON:
8168 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8170 // suggest offhand slot only if know dual wielding
8171 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8172 if(CanDualWield())
8173 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8174 break;
8176 case INVTYPE_SHIELD:
8177 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8178 break;
8179 case INVTYPE_RANGED:
8180 slots[0] = EQUIPMENT_SLOT_RANGED;
8181 break;
8182 case INVTYPE_2HWEAPON:
8183 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8184 if (CanDualWield() && CanTitanGrip())
8185 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8186 break;
8187 case INVTYPE_TABARD:
8188 slots[0] = EQUIPMENT_SLOT_TABARD;
8189 break;
8190 case INVTYPE_WEAPONMAINHAND:
8191 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8192 break;
8193 case INVTYPE_WEAPONOFFHAND:
8194 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8195 break;
8196 case INVTYPE_HOLDABLE:
8197 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8198 break;
8199 case INVTYPE_THROWN:
8200 slots[0] = EQUIPMENT_SLOT_RANGED;
8201 break;
8202 case INVTYPE_RANGEDRIGHT:
8203 slots[0] = EQUIPMENT_SLOT_RANGED;
8204 break;
8205 case INVTYPE_BAG:
8206 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8207 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8208 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8209 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8210 break;
8211 case INVTYPE_RELIC:
8213 switch(proto->SubClass)
8215 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8216 if (pClass == CLASS_PALADIN)
8217 slots[0] = EQUIPMENT_SLOT_RANGED;
8218 break;
8219 case ITEM_SUBCLASS_ARMOR_IDOL:
8220 if (pClass == CLASS_DRUID)
8221 slots[0] = EQUIPMENT_SLOT_RANGED;
8222 break;
8223 case ITEM_SUBCLASS_ARMOR_TOTEM:
8224 if (pClass == CLASS_SHAMAN)
8225 slots[0] = EQUIPMENT_SLOT_RANGED;
8226 break;
8227 case ITEM_SUBCLASS_ARMOR_MISC:
8228 if (pClass == CLASS_WARLOCK)
8229 slots[0] = EQUIPMENT_SLOT_RANGED;
8230 break;
8231 case ITEM_SUBCLASS_ARMOR_SIGIL:
8232 if (pClass == CLASS_DEATH_KNIGHT)
8233 slots[0] = EQUIPMENT_SLOT_RANGED;
8234 break;
8236 break;
8238 default :
8239 return NULL_SLOT;
8242 if( slot != NULL_SLOT )
8244 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8246 for (int i = 0; i < 4; ++i)
8248 if ( slots[i] == slot )
8249 return slot;
8253 else
8255 // search free slot at first
8256 for (int i = 0; i < 4; ++i)
8258 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8260 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8261 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8262 return slots[i];
8266 // if not found free and can swap return first appropriate from used
8267 for (int i = 0; i < 4; ++i)
8269 if ( slots[i] != NULL_SLOT && swap )
8270 return slots[i];
8274 // no free position
8275 return NULL_SLOT;
8278 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8280 Item *pItem;
8281 uint32 tempcount = 0;
8283 uint8 res = EQUIP_ERR_OK;
8285 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8287 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8288 if( pItem && pItem->GetEntry() == item )
8290 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8291 if(ires==EQUIP_ERR_OK)
8293 tempcount += pItem->GetCount();
8294 if( tempcount >= count )
8295 return EQUIP_ERR_OK;
8297 else
8298 res = ires;
8301 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8303 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8304 if( pItem && pItem->GetEntry() == item )
8306 tempcount += pItem->GetCount();
8307 if( tempcount >= count )
8308 return EQUIP_ERR_OK;
8311 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8313 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8314 if( pItem && pItem->GetEntry() == item )
8316 tempcount += pItem->GetCount();
8317 if( tempcount >= count )
8318 return EQUIP_ERR_OK;
8321 Bag *pBag;
8322 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8324 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8325 if( pBag )
8327 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8329 pItem = GetItemByPos( i, j );
8330 if( pItem && pItem->GetEntry() == item )
8332 tempcount += pItem->GetCount();
8333 if( tempcount >= count )
8334 return EQUIP_ERR_OK;
8340 // not found req. item count and have unequippable items
8341 return res;
8344 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8346 uint32 count = 0;
8347 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8349 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8350 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8351 count += pItem->GetCount();
8353 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8355 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8356 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8357 count += pItem->GetCount();
8359 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8361 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8362 if( pBag )
8363 count += pBag->GetItemCount(item,skipItem);
8366 if(skipItem && skipItem->GetProto()->GemProperties)
8368 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8370 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8371 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8372 count += pItem->GetGemCountWithID(item);
8376 if(inBankAlso)
8378 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8380 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8381 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8382 count += pItem->GetCount();
8384 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8386 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8387 if( pBag )
8388 count += pBag->GetItemCount(item,skipItem);
8391 if(skipItem && skipItem->GetProto()->GemProperties)
8393 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8395 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8396 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8397 count += pItem->GetGemCountWithID(item);
8402 return count;
8405 Item* Player::GetItemByGuid( uint64 guid ) const
8407 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8409 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8410 if( pItem && pItem->GetGUID() == guid )
8411 return pItem;
8413 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8415 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8416 if( pItem && pItem->GetGUID() == guid )
8417 return pItem;
8420 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8422 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8423 if( pBag )
8425 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8427 Item* pItem = pBag->GetItemByPos( j );
8428 if( pItem && pItem->GetGUID() == guid )
8429 return pItem;
8433 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8435 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8436 if( pBag )
8438 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8440 Item* pItem = pBag->GetItemByPos( j );
8441 if( pItem && pItem->GetGUID() == guid )
8442 return pItem;
8447 return NULL;
8450 Item* Player::GetItemByPos( uint16 pos ) const
8452 uint8 bag = pos >> 8;
8453 uint8 slot = pos & 255;
8454 return GetItemByPos( bag, slot );
8457 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8459 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8460 return m_items[slot];
8461 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8462 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8464 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8465 if ( pBag )
8466 return pBag->GetItemByPos(slot);
8468 return NULL;
8471 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8473 uint16 slot;
8474 switch (attackType)
8476 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8477 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8478 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8479 default: return NULL;
8482 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8483 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8484 return NULL;
8486 if(!useable)
8487 return item;
8489 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8490 return NULL;
8492 return item;
8495 Item* Player::GetShield(bool useable) const
8497 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8498 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8499 return NULL;
8501 if(!useable)
8502 return item;
8504 if( item->IsBroken())
8505 return NULL;
8507 return item;
8510 uint32 Player::GetAttackBySlot( uint8 slot )
8512 switch(slot)
8514 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8515 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8516 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8517 default: return MAX_ATTACK;
8521 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8523 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8524 return true;
8525 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8526 return true;
8527 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8528 return true;
8529 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8530 return true;
8531 return false;
8534 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8536 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8537 return true;
8538 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8539 return true;
8540 return false;
8543 bool Player::IsBankPos( uint8 bag, uint8 slot )
8545 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8546 return true;
8547 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8548 return true;
8549 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8550 return true;
8551 return false;
8554 bool Player::IsBagPos( uint16 pos )
8556 uint8 bag = pos >> 8;
8557 uint8 slot = pos & 255;
8558 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8559 return true;
8560 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8561 return true;
8562 return false;
8565 bool Player::IsValidPos( uint8 bag, uint8 slot )
8567 // post selected
8568 if(bag == NULL_BAG)
8569 return true;
8571 if (bag == INVENTORY_SLOT_BAG_0)
8573 // any post selected
8574 if (slot == NULL_SLOT)
8575 return true;
8577 // equipment
8578 if (slot < EQUIPMENT_SLOT_END)
8579 return true;
8581 // bag equip slots
8582 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8583 return true;
8585 // backpack slots
8586 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8587 return true;
8589 // keyring slots
8590 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8591 return true;
8593 // bank main slots
8594 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8595 return true;
8597 // bank bag slots
8598 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8599 return true;
8601 return false;
8604 // bag content slots
8605 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8607 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8608 if(!pBag)
8609 return false;
8611 // any post selected
8612 if (slot == NULL_SLOT)
8613 return true;
8615 return slot < pBag->GetBagSize();
8618 // bank bag content slots
8619 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8621 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8622 if(!pBag)
8623 return false;
8625 // any post selected
8626 if (slot == NULL_SLOT)
8627 return true;
8629 return slot < pBag->GetBagSize();
8632 // where this?
8633 return false;
8637 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8639 uint32 tempcount = 0;
8640 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8642 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8643 if( pItem && pItem->GetEntry() == item )
8645 tempcount += pItem->GetCount();
8646 if( tempcount >= count )
8647 return true;
8650 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8652 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8653 if( pItem && pItem->GetEntry() == item )
8655 tempcount += pItem->GetCount();
8656 if( tempcount >= count )
8657 return true;
8660 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8662 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8664 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8666 Item* pItem = GetItemByPos( i, j );
8667 if( pItem && pItem->GetEntry() == item )
8669 tempcount += pItem->GetCount();
8670 if( tempcount >= count )
8671 return true;
8677 if(inBankAlso)
8679 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8681 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8682 if( pItem && pItem->GetEntry() == item )
8684 tempcount += pItem->GetCount();
8685 if( tempcount >= count )
8686 return true;
8689 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8691 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8693 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8695 Item* pItem = GetItemByPos( i, j );
8696 if( pItem && pItem->GetEntry() == item )
8698 tempcount += pItem->GetCount();
8699 if( tempcount >= count )
8700 return true;
8707 return false;
8710 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8712 uint32 tempcount = 0;
8713 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8715 if(i==int(except_slot))
8716 continue;
8718 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8719 if( pItem && pItem->GetEntry() == item)
8721 tempcount += pItem->GetCount();
8722 if( tempcount >= count )
8723 return true;
8727 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8728 if (pProto && pProto->GemProperties)
8730 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8732 if(i==int(except_slot))
8733 continue;
8735 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8736 if( pItem && pItem->GetProto()->Socket[0].Color)
8738 tempcount += pItem->GetGemCountWithID(item);
8739 if( tempcount >= count )
8740 return true;
8745 return false;
8748 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8750 uint32 tempcount = 0;
8751 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8753 if(i==int(except_slot))
8754 continue;
8756 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8757 if (!pItem)
8758 continue;
8760 ItemPrototype const *pProto = pItem->GetProto();
8761 if (!pProto)
8762 continue;
8764 if (pProto->ItemLimitCategory == limitCategory)
8766 tempcount += pItem->GetCount();
8767 if( tempcount >= count )
8768 return true;
8771 if( pProto->Socket[0].Color)
8773 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8774 if( tempcount >= count )
8775 return true;
8779 return false;
8782 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8784 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8785 if( !pProto )
8787 if(no_space_count)
8788 *no_space_count = count;
8789 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8792 // no maximum
8793 if(pProto->MaxCount <= 0)
8794 return EQUIP_ERR_OK;
8796 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8798 if (curcount + count > uint32(pProto->MaxCount))
8800 if(no_space_count)
8801 *no_space_count = count +curcount - pProto->MaxCount;
8802 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8805 return EQUIP_ERR_OK;
8808 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8810 Item *pItem;
8811 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8813 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8814 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8815 return true;
8817 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8819 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8820 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8821 return true;
8823 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8825 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8827 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8829 pItem = GetItemByPos( i, j );
8830 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8831 return true;
8835 return false;
8838 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8840 Item* pItem2 = GetItemByPos( bag, slot );
8842 // ignore move item (this slot will be empty at move)
8843 if (pItem2==pSrcItem)
8844 pItem2 = NULL;
8846 uint32 need_space;
8848 // empty specific slot - check item fit to slot
8849 if (!pItem2 || swap)
8851 if (bag == INVENTORY_SLOT_BAG_0)
8853 // keyring case
8854 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8855 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8857 // currencytoken case
8858 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8859 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8861 // prevent cheating
8862 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8863 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8865 else
8867 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8868 if (!pBag)
8869 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8871 ItemPrototype const* pBagProto = pBag->GetProto();
8872 if (!pBagProto)
8873 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8875 if (slot >= pBagProto->ContainerSlots)
8876 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8878 if (!ItemCanGoIntoBag(pProto,pBagProto))
8879 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8882 // non empty stack with space
8883 need_space = pProto->GetMaxStackSize();
8885 // non empty slot, check item type
8886 else
8888 // check item type
8889 if (pItem2->GetEntry() != pProto->ItemId)
8890 return EQUIP_ERR_ITEM_CANT_STACK;
8892 // check free space
8893 if (pItem2->GetCount() >= pProto->GetMaxStackSize())
8894 return EQUIP_ERR_ITEM_CANT_STACK;
8896 // free stack space or infinity
8897 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8900 if (need_space > count)
8901 need_space = count;
8903 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8904 if (!newPosition.isContainedIn(dest))
8906 dest.push_back(newPosition);
8907 count -= need_space;
8909 return EQUIP_ERR_OK;
8912 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
8914 // skip specific bag already processed in first called _CanStoreItem_InBag
8915 if (bag==skip_bag)
8916 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8918 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8919 if (!pBag)
8920 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8922 ItemPrototype const* pBagProto = pBag->GetProto();
8923 if (!pBagProto)
8924 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8926 // specialized bag mode or non-specilized
8927 if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
8928 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8930 if (!ItemCanGoIntoBag(pProto,pBagProto))
8931 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8933 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8935 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8936 if (j==skip_slot)
8937 continue;
8939 Item* pItem2 = GetItemByPos( bag, j );
8941 // ignore move item (this slot will be empty at move)
8942 if (pItem2==pSrcItem)
8943 pItem2 = NULL;
8945 // if merge skip empty, if !merge skip non-empty
8946 if ((pItem2!=NULL)!=merge)
8947 continue;
8949 if (pItem2)
8951 if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8953 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8954 if(need_space > count)
8955 need_space = count;
8957 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8958 if (!newPosition.isContainedIn(dest))
8960 dest.push_back(newPosition);
8961 count -= need_space;
8963 if (count==0)
8964 return EQUIP_ERR_OK;
8968 else
8970 uint32 need_space = pProto->GetMaxStackSize();
8971 if (need_space > count)
8972 need_space = count;
8974 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8975 if (!newPosition.isContainedIn(dest))
8977 dest.push_back(newPosition);
8978 count -= need_space;
8980 if (count==0)
8981 return EQUIP_ERR_OK;
8985 return EQUIP_ERR_OK;
8988 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
8990 for(uint32 j = slot_begin; j < slot_end; ++j)
8992 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8993 if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8994 continue;
8996 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8998 // ignore move item (this slot will be empty at move)
8999 if (pItem2==pSrcItem)
9000 pItem2 = NULL;
9002 // if merge skip empty, if !merge skip non-empty
9003 if ((pItem2!=NULL)!=merge)
9004 continue;
9006 if (pItem2)
9008 if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9010 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9011 if (need_space > count)
9012 need_space = count;
9013 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9014 if (!newPosition.isContainedIn(dest))
9016 dest.push_back(newPosition);
9017 count -= need_space;
9019 if (count==0)
9020 return EQUIP_ERR_OK;
9024 else
9026 uint32 need_space = pProto->GetMaxStackSize();
9027 if (need_space > count)
9028 need_space = count;
9030 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9031 if (!newPosition.isContainedIn(dest))
9033 dest.push_back(newPosition);
9034 count -= need_space;
9036 if (count==0)
9037 return EQUIP_ERR_OK;
9041 return EQUIP_ERR_OK;
9044 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9046 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9048 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
9049 if (!pProto)
9051 if (no_space_count)
9052 *no_space_count = count;
9053 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9056 if (pItem && pItem->IsBindedNotWith(this))
9058 if (no_space_count)
9059 *no_space_count = count;
9060 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9063 // check count of items (skip for auto move for same player from bank)
9064 uint32 no_similar_count = 0; // can't store this amount similar items
9065 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9066 if (res!=EQUIP_ERR_OK)
9068 if (count==no_similar_count)
9070 if (no_space_count)
9071 *no_space_count = no_similar_count;
9072 return res;
9074 count -= no_similar_count;
9077 // in specific slot
9078 if (bag != NULL_BAG && slot != NULL_SLOT)
9080 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9081 if (res!=EQUIP_ERR_OK)
9083 if (no_space_count)
9084 *no_space_count = count + no_similar_count;
9085 return res;
9088 if (count==0)
9090 if (no_similar_count==0)
9091 return EQUIP_ERR_OK;
9093 if (no_space_count)
9094 *no_space_count = count + no_similar_count;
9095 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9099 // not specific slot or have space for partly store only in specific slot
9101 // in specific bag
9102 if (bag != NULL_BAG)
9104 // search stack in bag for merge to
9105 if (pProto->Stackable != 1)
9107 if (bag == INVENTORY_SLOT_BAG_0) // inventory
9109 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9110 if (res!=EQUIP_ERR_OK)
9112 if (no_space_count)
9113 *no_space_count = count + no_similar_count;
9114 return res;
9117 if (count==0)
9119 if (no_similar_count==0)
9120 return EQUIP_ERR_OK;
9122 if (no_space_count)
9123 *no_space_count = count + no_similar_count;
9124 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9127 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9128 if (res!=EQUIP_ERR_OK)
9130 if (no_space_count)
9131 *no_space_count = count + no_similar_count;
9132 return res;
9135 if (count==0)
9137 if (no_similar_count==0)
9138 return EQUIP_ERR_OK;
9140 if (no_space_count)
9141 *no_space_count = count + no_similar_count;
9142 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9145 else // equipped bag
9147 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9148 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9149 if (res!=EQUIP_ERR_OK)
9150 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9152 if (res!=EQUIP_ERR_OK)
9154 if (no_space_count)
9155 *no_space_count = count + no_similar_count;
9156 return res;
9159 if (count==0)
9161 if (no_similar_count==0)
9162 return EQUIP_ERR_OK;
9164 if (no_space_count)
9165 *no_space_count = count + no_similar_count;
9166 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9171 // search free slot in bag for place to
9172 if(bag == INVENTORY_SLOT_BAG_0) // inventory
9174 // search free slot - keyring case
9175 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9177 uint32 keyringSize = GetMaxKeyringSize();
9178 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9179 if (res!=EQUIP_ERR_OK)
9181 if (no_space_count)
9182 *no_space_count = count + no_similar_count;
9183 return res;
9186 if (count==0)
9188 if (no_similar_count==0)
9189 return EQUIP_ERR_OK;
9191 if (no_space_count)
9192 *no_space_count = count + no_similar_count;
9193 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9196 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9197 if (res!=EQUIP_ERR_OK)
9199 if (no_space_count)
9200 *no_space_count = count + no_similar_count;
9201 return res;
9204 if (count==0)
9206 if (no_similar_count==0)
9207 return EQUIP_ERR_OK;
9209 if (no_space_count)
9210 *no_space_count = count + no_similar_count;
9211 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9214 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9216 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9217 if (res!=EQUIP_ERR_OK)
9219 if (no_space_count)
9220 *no_space_count = count + no_similar_count;
9221 return res;
9224 if (count==0)
9226 if (no_similar_count==0)
9227 return EQUIP_ERR_OK;
9229 if (no_space_count)
9230 *no_space_count = count + no_similar_count;
9231 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9235 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9236 if (res!=EQUIP_ERR_OK)
9238 if (no_space_count)
9239 *no_space_count = count + no_similar_count;
9240 return res;
9243 if (count==0)
9245 if (no_similar_count==0)
9246 return EQUIP_ERR_OK;
9248 if (no_space_count)
9249 *no_space_count = count + no_similar_count;
9250 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9253 else // equipped bag
9255 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9256 if (res!=EQUIP_ERR_OK)
9257 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9259 if (res!=EQUIP_ERR_OK)
9261 if (no_space_count)
9262 *no_space_count = count + no_similar_count;
9263 return res;
9266 if (count==0)
9268 if (no_similar_count==0)
9269 return EQUIP_ERR_OK;
9271 if (no_space_count)
9272 *no_space_count = count + no_similar_count;
9273 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9278 // not specific bag or have space for partly store only in specific bag
9280 // search stack for merge to
9281 if (pProto->Stackable != 1)
9283 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,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 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9302 if (res!=EQUIP_ERR_OK)
9304 if (no_space_count)
9305 *no_space_count = count + no_similar_count;
9306 return res;
9309 if (count==0)
9311 if (no_similar_count==0)
9312 return EQUIP_ERR_OK;
9314 if (no_space_count)
9315 *no_space_count = count + no_similar_count;
9316 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9319 if (pProto->BagFamily)
9321 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9323 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9324 if (res!=EQUIP_ERR_OK)
9325 continue;
9327 if (count==0)
9329 if (no_similar_count==0)
9330 return EQUIP_ERR_OK;
9332 if (no_space_count)
9333 *no_space_count = count + no_similar_count;
9334 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9339 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9341 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9342 if (res!=EQUIP_ERR_OK)
9343 continue;
9345 if (count==0)
9347 if (no_similar_count==0)
9348 return EQUIP_ERR_OK;
9350 if (no_space_count)
9351 *no_space_count = count + no_similar_count;
9352 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9357 // search free slot - special bag case
9358 if (pProto->BagFamily)
9360 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9362 uint32 keyringSize = GetMaxKeyringSize();
9363 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9364 if (res!=EQUIP_ERR_OK)
9366 if (no_space_count)
9367 *no_space_count = count + no_similar_count;
9368 return res;
9371 if (count==0)
9373 if (no_similar_count==0)
9374 return EQUIP_ERR_OK;
9376 if (no_space_count)
9377 *no_space_count = count + no_similar_count;
9378 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9381 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9383 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9384 if (res!=EQUIP_ERR_OK)
9386 if (no_space_count)
9387 *no_space_count = count + no_similar_count;
9388 return res;
9391 if (count==0)
9393 if (no_similar_count==0)
9394 return EQUIP_ERR_OK;
9396 if (no_space_count)
9397 *no_space_count = count + no_similar_count;
9398 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9402 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9404 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9405 if (res!=EQUIP_ERR_OK)
9406 continue;
9408 if (count==0)
9410 if (no_similar_count==0)
9411 return EQUIP_ERR_OK;
9413 if (no_space_count)
9414 *no_space_count = count + no_similar_count;
9415 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9420 // search free slot
9421 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9422 if (res!=EQUIP_ERR_OK)
9424 if (no_space_count)
9425 *no_space_count = count + no_similar_count;
9426 return res;
9429 if (count==0)
9431 if (no_similar_count==0)
9432 return EQUIP_ERR_OK;
9434 if (no_space_count)
9435 *no_space_count = count + no_similar_count;
9436 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9439 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9441 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9442 if (res!=EQUIP_ERR_OK)
9443 continue;
9445 if (count==0)
9447 if (no_similar_count==0)
9448 return EQUIP_ERR_OK;
9450 if (no_space_count)
9451 *no_space_count = count + no_similar_count;
9452 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9456 if (no_space_count)
9457 *no_space_count = count + no_similar_count;
9459 return EQUIP_ERR_INVENTORY_FULL;
9462 //////////////////////////////////////////////////////////////////////////
9463 uint8 Player::CanStoreItems( Item **pItems,int count) const
9465 Item *pItem2;
9467 // fill space table
9468 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9469 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9470 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9471 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9473 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9474 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9475 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9476 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9478 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9480 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9482 if (pItem2 && !pItem2->IsInTrade())
9484 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9488 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9490 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9492 if (pItem2 && !pItem2->IsInTrade())
9494 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9498 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9500 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9502 if (pItem2 && !pItem2->IsInTrade())
9504 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9508 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9510 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9512 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9514 pItem2 = GetItemByPos( i, j );
9515 if (pItem2 && !pItem2->IsInTrade())
9517 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9523 // check free space for all items
9524 for (int k = 0; k < count; ++k)
9526 Item *pItem = pItems[k];
9528 // no item
9529 if (!pItem) continue;
9531 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9532 ItemPrototype const *pProto = pItem->GetProto();
9534 // strange item
9535 if( !pProto )
9536 return EQUIP_ERR_ITEM_NOT_FOUND;
9538 // item it 'bind'
9539 if(pItem->IsBindedNotWith(this))
9540 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9542 Bag *pBag;
9543 ItemPrototype const *pBagProto;
9545 // item is 'one item only'
9546 uint8 res = CanTakeMoreSimilarItems(pItem);
9547 if(res != EQUIP_ERR_OK)
9548 return res;
9550 // search stack for merge to
9551 if( pProto->Stackable != 1 )
9553 bool b_found = false;
9555 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9557 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9558 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9560 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9561 b_found = true;
9562 break;
9565 if (b_found) continue;
9567 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9569 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9570 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9572 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9573 b_found = true;
9574 break;
9577 if (b_found) continue;
9579 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9581 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9582 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9584 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9585 b_found = true;
9586 break;
9589 if (b_found) continue;
9591 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9593 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9594 if( pBag )
9596 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9598 pItem2 = GetItemByPos( t, j );
9599 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9601 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9602 b_found = true;
9603 break;
9608 if (b_found) continue;
9611 // special bag case
9612 if( pProto->BagFamily )
9614 bool b_found = false;
9615 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9617 uint32 keyringSize = GetMaxKeyringSize();
9618 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9620 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9622 inv_keys[t-KEYRING_SLOT_START] = 1;
9623 b_found = true;
9624 break;
9629 if (b_found) continue;
9631 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9633 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9635 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9637 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9638 b_found = true;
9639 break;
9644 if (b_found) continue;
9646 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9648 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9649 if( pBag )
9651 pBagProto = pBag->GetProto();
9653 // not plain container check
9654 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9655 ItemCanGoIntoBag(pProto,pBagProto) )
9657 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9659 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9661 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9662 b_found = true;
9663 break;
9669 if (b_found) continue;
9672 // search free slot
9673 bool b_found = false;
9674 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9676 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9678 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9679 b_found = true;
9680 break;
9683 if (b_found) continue;
9685 // search free slot in bags
9686 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9688 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9689 if( pBag )
9691 pBagProto = pBag->GetProto();
9693 // special bag already checked
9694 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9695 continue;
9697 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9699 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9701 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9702 b_found = true;
9703 break;
9709 // no free slot found?
9710 if (!b_found)
9711 return EQUIP_ERR_INVENTORY_FULL;
9714 return EQUIP_ERR_OK;
9717 //////////////////////////////////////////////////////////////////////////
9718 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9720 dest = 0;
9721 Item *pItem = Item::CreateItem( item, 1, this );
9722 if( pItem )
9724 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9725 delete pItem;
9726 return result;
9729 return EQUIP_ERR_ITEM_NOT_FOUND;
9732 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9734 dest = 0;
9735 if( pItem )
9737 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9738 ItemPrototype const *pProto = pItem->GetProto();
9739 if( pProto )
9741 if(pItem->IsBindedNotWith(this))
9742 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9744 // check count of items (skip for auto move for same player from bank)
9745 uint8 res = CanTakeMoreSimilarItems(pItem);
9746 if(res != EQUIP_ERR_OK)
9747 return res;
9749 // check this only in game
9750 if(not_loading)
9752 // May be here should be more stronger checks; STUNNED checked
9753 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9754 if (hasUnitState(UNIT_STAT_STUNNED))
9755 return EQUIP_ERR_YOU_ARE_STUNNED;
9757 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9758 // - combat
9759 // - in-progress arenas
9760 if( !pProto->CanChangeEquipStateInCombat() )
9762 if( isInCombat() )
9763 return EQUIP_ERR_NOT_IN_COMBAT;
9765 if(BattleGround* bg = GetBattleGround())
9766 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9767 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9770 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9771 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9773 if(IsNonMeleeSpellCasted(false))
9774 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9777 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
9778 // check allowed level (extend range to upper values if MaxLevel more or equal max player level, this let GM set high level with 1...max range items)
9779 if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
9780 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9782 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9783 if (eslot == NULL_SLOT)
9784 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9786 uint8 msg = CanUseItem(pItem , not_loading);
9787 if (msg != EQUIP_ERR_OK)
9788 return msg;
9789 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
9790 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9792 // if swap ignore item (equipped also)
9793 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9794 return res2;
9796 // check unique-equipped special item classes
9797 if (pProto->Class == ITEM_CLASS_QUIVER)
9799 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9801 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
9803 if (pBag != pItem)
9805 if (ItemPrototype const* pBagProto = pBag->GetProto())
9807 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
9808 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9809 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
9810 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9817 uint32 type = pProto->InventoryType;
9819 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9821 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9823 if (!CanDualWield())
9824 return EQUIP_ERR_CANT_DUAL_WIELD;
9826 else if (type == INVTYPE_2HWEAPON)
9828 if (!CanDualWield() || !CanTitanGrip())
9829 return EQUIP_ERR_CANT_DUAL_WIELD;
9832 if (IsTwoHandUsed())
9833 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9836 // equip two-hand weapon case (with possible unequip 2 items)
9837 if (type == INVTYPE_2HWEAPON)
9839 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9841 if (!CanTitanGrip())
9842 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9844 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9845 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9847 if (!CanTitanGrip())
9849 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9850 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9851 ItemPosCountVec off_dest;
9852 if (offItem && (!not_loading ||
9853 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9854 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
9855 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9858 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9859 return EQUIP_ERR_OK;
9863 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9866 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9868 // Applied only to equipped items and bank bags
9869 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9870 return EQUIP_ERR_OK;
9872 Item* pItem = GetItemByPos(pos);
9874 // Applied only to existed equipped item
9875 if( !pItem )
9876 return EQUIP_ERR_OK;
9878 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9880 ItemPrototype const *pProto = pItem->GetProto();
9881 if( !pProto )
9882 return EQUIP_ERR_ITEM_NOT_FOUND;
9884 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9885 // - combat
9886 // - in-progress arenas
9887 if( !pProto->CanChangeEquipStateInCombat() )
9889 if( isInCombat() )
9890 return EQUIP_ERR_NOT_IN_COMBAT;
9892 if(BattleGround* bg = GetBattleGround())
9893 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9894 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9897 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9898 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9900 return EQUIP_ERR_OK;
9903 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9905 if (!pItem)
9906 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9908 uint32 count = pItem->GetCount();
9910 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9911 ItemPrototype const *pProto = pItem->GetProto();
9912 if (!pProto)
9913 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9915 if (pItem->IsBindedNotWith(this))
9916 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9918 // check count of items (skip for auto move for same player from bank)
9919 uint8 res = CanTakeMoreSimilarItems(pItem);
9920 if (res != EQUIP_ERR_OK)
9921 return res;
9923 // in specific slot
9924 if (bag != NULL_BAG && slot != NULL_SLOT)
9926 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
9928 if (!pItem->IsBag())
9929 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9931 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
9932 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9934 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
9935 return cantuse;
9938 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9939 if (res!=EQUIP_ERR_OK)
9940 return res;
9942 if (count==0)
9943 return EQUIP_ERR_OK;
9946 // not specific slot or have space for partly store only in specific slot
9948 // in specific bag
9949 if( bag != NULL_BAG )
9951 if( pProto->InventoryType == INVTYPE_BAG )
9953 Bag *pBag = (Bag*)pItem;
9954 if( pBag && !pBag->IsEmpty() )
9955 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9958 // search stack in bag for merge to
9959 if( pProto->Stackable != 1 )
9961 if( bag == INVENTORY_SLOT_BAG_0 )
9963 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9964 if(res!=EQUIP_ERR_OK)
9965 return res;
9967 if(count==0)
9968 return EQUIP_ERR_OK;
9970 else
9972 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9973 if(res!=EQUIP_ERR_OK)
9974 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9976 if(res!=EQUIP_ERR_OK)
9977 return res;
9979 if(count==0)
9980 return EQUIP_ERR_OK;
9984 // search free slot in bag
9985 if( bag == INVENTORY_SLOT_BAG_0 )
9987 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9988 if(res!=EQUIP_ERR_OK)
9989 return res;
9991 if(count==0)
9992 return EQUIP_ERR_OK;
9994 else
9996 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
9997 if(res != EQUIP_ERR_OK)
9998 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
10000 if(res != EQUIP_ERR_OK)
10001 return res;
10003 if(count == 0)
10004 return EQUIP_ERR_OK;
10008 // not specific bag or have space for partly store only in specific bag
10010 // search stack for merge to
10011 if( pProto->Stackable != 1 )
10013 // in slots
10014 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10015 if(res != EQUIP_ERR_OK)
10016 return res;
10018 if(count == 0)
10019 return EQUIP_ERR_OK;
10021 // in special bags
10022 if( pProto->BagFamily )
10024 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10026 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10027 if(res!=EQUIP_ERR_OK)
10028 continue;
10030 if(count==0)
10031 return EQUIP_ERR_OK;
10035 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10037 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10038 if(res!=EQUIP_ERR_OK)
10039 continue;
10041 if(count==0)
10042 return EQUIP_ERR_OK;
10046 // search free place in special bag
10047 if( pProto->BagFamily )
10049 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10051 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10052 if(res!=EQUIP_ERR_OK)
10053 continue;
10055 if(count==0)
10056 return EQUIP_ERR_OK;
10060 // search free space
10061 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10062 if(res!=EQUIP_ERR_OK)
10063 return res;
10065 if(count==0)
10066 return EQUIP_ERR_OK;
10068 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10070 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10071 if(res!=EQUIP_ERR_OK)
10072 continue;
10074 if(count==0)
10075 return EQUIP_ERR_OK;
10077 return EQUIP_ERR_BANK_FULL;
10080 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10082 if (pItem)
10084 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10086 if (!isAlive() && not_loading)
10087 return EQUIP_ERR_YOU_ARE_DEAD;
10089 //if (isStunned())
10090 // return EQUIP_ERR_YOU_ARE_STUNNED;
10092 ItemPrototype const *pProto = pItem->GetProto();
10093 if (pProto)
10095 if (pItem->IsBindedNotWith(this))
10096 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10098 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
10099 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10101 if (pItem->GetSkill() != 0)
10103 if (GetSkillValue( pItem->GetSkill() ) == 0)
10104 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10107 if (pProto->RequiredSkill != 0)
10109 if (GetSkillValue( pProto->RequiredSkill ) == 0)
10110 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10112 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
10113 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10116 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
10117 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10119 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
10120 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10122 if (getLevel() < pProto->RequiredLevel)
10123 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10125 return EQUIP_ERR_OK;
10128 return EQUIP_ERR_ITEM_NOT_FOUND;
10131 bool Player::CanUseItem( ItemPrototype const *pProto )
10133 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10135 if( pProto )
10137 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10138 return false;
10139 if( pProto->RequiredSkill != 0 )
10141 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10142 return false;
10143 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10144 return false;
10146 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10147 return false;
10148 if( getLevel() < pProto->RequiredLevel )
10149 return false;
10150 return true;
10152 return false;
10155 uint8 Player::CanUseAmmo( uint32 item ) const
10157 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10158 if( !isAlive() )
10159 return EQUIP_ERR_YOU_ARE_DEAD;
10160 //if( isStunned() )
10161 // return EQUIP_ERR_YOU_ARE_STUNNED;
10162 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10163 if( pProto )
10165 if( pProto->InventoryType!= INVTYPE_AMMO )
10166 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10167 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10168 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10169 if( pProto->RequiredSkill != 0 )
10171 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10172 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10173 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10174 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10176 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10177 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10178 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10179 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10181 if( getLevel() < pProto->RequiredLevel )
10182 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10184 // Requires No Ammo
10185 if(GetDummyAura(46699))
10186 return EQUIP_ERR_BAG_FULL6;
10188 return EQUIP_ERR_OK;
10190 return EQUIP_ERR_ITEM_NOT_FOUND;
10193 void Player::SetAmmo( uint32 item )
10195 if(!item)
10196 return;
10198 // already set
10199 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10200 return;
10202 // check ammo
10203 if(item)
10205 uint8 msg = CanUseAmmo( item );
10206 if( msg != EQUIP_ERR_OK )
10208 SendEquipError( msg, NULL, NULL );
10209 return;
10213 SetUInt32Value(PLAYER_AMMO_ID, item);
10215 _ApplyAmmoBonuses();
10218 void Player::RemoveAmmo()
10220 SetUInt32Value(PLAYER_AMMO_ID, 0);
10222 m_ammoDPS = 0.0f;
10224 if(CanModifyStats())
10225 UpdateDamagePhysical(RANGED_ATTACK);
10228 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10229 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10231 uint32 count = 0;
10232 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10233 count += itr->count;
10235 Item *pItem = Item::CreateItem( item, count, this );
10236 if( pItem )
10238 ItemAddedQuestCheck( item, count );
10239 if(randomPropertyId)
10240 pItem->SetItemRandomProperties(randomPropertyId);
10241 pItem = StoreItem( dest, pItem, update );
10243 return pItem;
10246 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10248 if( !pItem )
10249 return NULL;
10251 Item* lastItem = pItem;
10252 uint32 entry = pItem->GetEntry();
10253 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10255 uint16 pos = itr->pos;
10256 uint32 count = itr->count;
10258 ++itr;
10260 if(itr == dest.end())
10262 lastItem = _StoreItem(pos,pItem,count,false,update);
10263 break;
10266 lastItem = _StoreItem(pos,pItem,count,true,update);
10268 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10269 return lastItem;
10272 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10273 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10275 if( !pItem )
10276 return NULL;
10278 uint8 bag = pos >> 8;
10279 uint8 slot = pos & 255;
10281 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10283 Item *pItem2 = GetItemByPos( bag, slot );
10285 if (!pItem2)
10287 if (clone)
10288 pItem = pItem->CloneItem(count, this);
10289 else
10290 pItem->SetCount(count);
10292 if (!pItem)
10293 return NULL;
10295 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10296 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10297 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10298 pItem->SetBinding( true );
10300 if (bag == INVENTORY_SLOT_BAG_0)
10302 m_items[slot] = pItem;
10303 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10304 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10305 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10307 pItem->SetSlot( slot );
10308 pItem->SetContainer( NULL );
10310 // need update known currency
10311 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10312 UpdateKnownCurrencies(pItem->GetEntry(), true);
10314 if (IsInWorld() && update)
10316 pItem->AddToWorld();
10317 pItem->SendUpdateToPlayer( this );
10320 pItem->SetState(ITEM_CHANGED, this);
10322 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10324 pBag->StoreItem( slot, pItem, update );
10325 if( IsInWorld() && update )
10327 pItem->AddToWorld();
10328 pItem->SendUpdateToPlayer( this );
10330 pItem->SetState(ITEM_CHANGED, this);
10331 pBag->SetState(ITEM_CHANGED, this);
10334 AddEnchantmentDurations(pItem);
10335 AddItemDurations(pItem);
10337 return pItem;
10339 else
10341 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10342 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10343 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10344 pItem2->SetBinding( true );
10346 pItem2->SetCount( pItem2->GetCount() + count );
10347 if (IsInWorld() && update)
10348 pItem2->SendUpdateToPlayer( this );
10350 if (!clone)
10352 // delete item (it not in any slot currently)
10353 if (IsInWorld() && update)
10355 pItem->RemoveFromWorld();
10356 pItem->DestroyForPlayer( this );
10359 RemoveEnchantmentDurations(pItem);
10360 RemoveItemDurations(pItem);
10362 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10363 pItem->SetState(ITEM_REMOVED, this);
10366 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10367 AddEnchantmentDurations(pItem2);
10369 pItem2->SetState(ITEM_CHANGED, this);
10371 return pItem2;
10375 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10377 if (Item *pItem = Item::CreateItem( item, 1, this ))
10379 ItemAddedQuestCheck( item, 1 );
10380 return EquipItem( pos, pItem, update );
10383 return NULL;
10386 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10388 AddEnchantmentDurations(pItem);
10389 AddItemDurations(pItem);
10391 uint8 bag = pos >> 8;
10392 uint8 slot = pos & 255;
10394 Item *pItem2 = GetItemByPos( bag, slot );
10396 if( !pItem2 )
10398 VisualizeItem( slot, pItem);
10400 if(isAlive())
10402 ItemPrototype const *pProto = pItem->GetProto();
10404 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10405 if(pProto && pProto->ItemSet)
10406 AddItemsSetItem(this, pItem);
10408 _ApplyItemMods(pItem, slot, true);
10410 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10412 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10414 if (getClass() == CLASS_ROGUE)
10415 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10417 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10419 if (!spellProto)
10420 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10421 else
10423 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10425 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10426 data << uint64(GetGUID());
10427 data << uint8(1);
10428 data << uint32(cooldownSpell);
10429 data << uint32(0);
10430 GetSession()->SendPacket(&data);
10435 if( IsInWorld() && update )
10437 pItem->AddToWorld();
10438 pItem->SendUpdateToPlayer( this );
10441 ApplyEquipCooldown(pItem);
10443 if( slot == EQUIPMENT_SLOT_MAINHAND )
10444 UpdateExpertise(BASE_ATTACK);
10445 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10446 UpdateExpertise(OFF_ATTACK);
10448 else
10450 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10451 if( IsInWorld() && update )
10452 pItem2->SendUpdateToPlayer( this );
10454 // delete item (it not in any slot currently)
10455 //pItem->DeleteFromDB();
10456 if( IsInWorld() && update )
10458 pItem->RemoveFromWorld();
10459 pItem->DestroyForPlayer( this );
10462 RemoveEnchantmentDurations(pItem);
10463 RemoveItemDurations(pItem);
10465 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10466 pItem->SetState(ITEM_REMOVED, this);
10467 pItem2->SetState(ITEM_CHANGED, this);
10469 ApplyEquipCooldown(pItem2);
10471 return pItem2;
10474 // only for full equip instead adding to stack
10475 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10477 return pItem;
10480 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10482 if( pItem )
10484 AddEnchantmentDurations(pItem);
10485 AddItemDurations(pItem);
10487 uint8 slot = pos & 255;
10488 VisualizeItem( slot, pItem);
10490 if( IsInWorld() )
10492 pItem->AddToWorld();
10493 pItem->SendUpdateToPlayer( this );
10496 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10500 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10502 if(pItem)
10504 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10505 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10506 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10508 else
10510 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10511 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10515 void Player::VisualizeItem( uint8 slot, Item *pItem)
10517 if(!pItem)
10518 return;
10520 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10521 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10522 pItem->SetBinding( true );
10524 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10526 m_items[slot] = pItem;
10527 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10528 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10529 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10530 pItem->SetSlot( slot );
10531 pItem->SetContainer( NULL );
10533 if( slot < EQUIPMENT_SLOT_END )
10534 SetVisibleItemSlot(slot, pItem);
10536 pItem->SetState(ITEM_CHANGED, this);
10539 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10541 // note: removeitem does not actually change the item
10542 // it only takes the item out of storage temporarily
10543 // note2: if removeitem is to be used for delinking
10544 // the item must be removed from the player's updatequeue
10546 Item *pItem = GetItemByPos( bag, slot );
10547 if( pItem )
10549 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10551 RemoveEnchantmentDurations(pItem);
10552 RemoveItemDurations(pItem);
10554 if( bag == INVENTORY_SLOT_BAG_0 )
10556 if ( slot < INVENTORY_SLOT_BAG_END )
10558 ItemPrototype const *pProto = pItem->GetProto();
10559 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10561 if(pProto && pProto->ItemSet)
10562 RemoveItemsSetItem(this, pProto);
10564 _ApplyItemMods(pItem, slot, false);
10566 // remove item dependent auras and casts (only weapon and armor slots)
10567 if(slot < EQUIPMENT_SLOT_END)
10569 RemoveItemDependentAurasAndCasts(pItem);
10571 // remove held enchantments, update expertise
10572 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10574 if (pItem->GetItemSuffixFactor())
10576 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10577 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10579 else
10581 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10582 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10585 UpdateExpertise(BASE_ATTACK);
10587 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10588 UpdateExpertise(OFF_ATTACK);
10591 // need update known currency
10592 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10593 UpdateKnownCurrencies(pItem->GetEntry(), false);
10595 m_items[slot] = NULL;
10596 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10598 if ( slot < EQUIPMENT_SLOT_END )
10599 SetVisibleItemSlot(slot, NULL);
10601 else
10603 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10604 if( pBag )
10605 pBag->RemoveItem(slot, update);
10607 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10608 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10609 pItem->SetSlot( NULL_SLOT );
10610 if( IsInWorld() && update )
10611 pItem->SendUpdateToPlayer( this );
10615 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10616 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10618 if(Item* it = GetItemByPos(bag,slot))
10620 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10621 RemoveItem(bag, slot, update);
10622 it->RemoveFromUpdateQueueOf(this);
10623 if(it->IsInWorld())
10625 it->RemoveFromWorld();
10626 it->DestroyForPlayer( this );
10631 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10632 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10634 // update quest counters
10635 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10637 // store item
10638 Item* pLastItem = StoreItem(dest, pItem, update);
10640 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10641 if(pLastItem == pItem)
10643 // update owner for last item (this can be original item with wrong owner
10644 if(pLastItem->GetOwnerGUID() != GetGUID())
10645 pLastItem->SetOwnerGUID(GetGUID());
10647 // if this original item then it need create record in inventory
10648 // in case trade we already have item in other player inventory
10649 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10653 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10655 Item *pItem = GetItemByPos( bag, slot );
10656 if( pItem )
10658 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10660 // start from destroy contained items (only equipped bag can have its)
10661 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10663 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10664 DestroyItem(slot, i, update);
10667 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10668 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10670 RemoveEnchantmentDurations(pItem);
10671 RemoveItemDurations(pItem);
10673 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10675 if( bag == INVENTORY_SLOT_BAG_0 )
10677 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10679 // equipment and equipped bags can have applied bonuses
10680 if ( slot < INVENTORY_SLOT_BAG_END )
10682 ItemPrototype const *pProto = pItem->GetProto();
10684 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10685 if(pProto && pProto->ItemSet)
10686 RemoveItemsSetItem(this, pProto);
10688 _ApplyItemMods(pItem, slot, false);
10691 if ( slot < EQUIPMENT_SLOT_END )
10693 // remove item dependent auras and casts (only weapon and armor slots)
10694 RemoveItemDependentAurasAndCasts(pItem);
10696 // update expertise
10697 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10698 UpdateExpertise(BASE_ATTACK);
10699 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10700 UpdateExpertise(OFF_ATTACK);
10702 // equipment visual show
10703 SetVisibleItemSlot(slot, NULL);
10705 // need update known currency
10706 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10707 UpdateKnownCurrencies(pItem->GetEntry(), false);
10709 m_items[slot] = NULL;
10711 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10712 pBag->RemoveItem(slot, update);
10714 if( IsInWorld() && update )
10716 pItem->RemoveFromWorld();
10717 pItem->DestroyForPlayer(this);
10720 //pItem->SetOwnerGUID(0);
10721 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10722 pItem->SetSlot( NULL_SLOT );
10723 pItem->SetState(ITEM_REMOVED, this);
10727 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10729 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10730 uint32 remcount = 0;
10732 // in inventory
10733 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10735 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10737 if (pItem->GetEntry() == item)
10739 if (pItem->GetCount() + remcount <= count)
10741 // all items in inventory can unequipped
10742 remcount += pItem->GetCount();
10743 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10745 if (remcount >= count)
10746 return;
10748 else
10750 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10751 pItem->SetCount( pItem->GetCount() - count + remcount );
10752 if (IsInWorld() & update)
10753 pItem->SendUpdateToPlayer( this );
10754 pItem->SetState(ITEM_CHANGED, this);
10755 return;
10761 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10763 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10765 if (pItem->GetEntry() == item)
10767 if (pItem->GetCount() + remcount <= count)
10769 // all keys can be unequipped
10770 remcount += pItem->GetCount();
10771 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10773 if (remcount >= count)
10774 return;
10776 else
10778 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10779 pItem->SetCount( pItem->GetCount() - count + remcount );
10780 if (IsInWorld() & update)
10781 pItem->SendUpdateToPlayer( this );
10782 pItem->SetState(ITEM_CHANGED, this);
10783 return;
10789 // in inventory bags
10790 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10792 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10794 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10796 if(Item* pItem = pBag->GetItemByPos(j))
10798 if (pItem->GetEntry() == item)
10800 // all items in bags can be unequipped
10801 if (pItem->GetCount() + remcount <= count)
10803 remcount += pItem->GetCount();
10804 DestroyItem( i, j, update );
10806 if (remcount >= count)
10807 return;
10809 else
10811 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10812 pItem->SetCount( pItem->GetCount() - count + remcount );
10813 if (IsInWorld() && update)
10814 pItem->SendUpdateToPlayer( this );
10815 pItem->SetState(ITEM_CHANGED, this);
10816 return;
10824 // in equipment and bag list
10825 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10827 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10829 if (pItem && pItem->GetEntry() == item)
10831 if (pItem->GetCount() + remcount <= count)
10833 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
10835 remcount += pItem->GetCount();
10836 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10838 if (remcount >= count)
10839 return;
10842 else
10844 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10845 pItem->SetCount( pItem->GetCount() - count + remcount );
10846 if (IsInWorld() & update)
10847 pItem->SendUpdateToPlayer( this );
10848 pItem->SetState(ITEM_CHANGED, this);
10849 return;
10856 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10858 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10860 // in inventory
10861 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10862 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10863 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10864 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10866 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10867 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10868 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10869 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10871 // in inventory bags
10872 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10873 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10874 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10875 if (Item* pItem = pBag->GetItemByPos(j))
10876 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10877 DestroyItem(i, j, update);
10879 // in equipment and bag list
10880 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10881 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10882 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10883 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10886 void Player::DestroyConjuredItems( bool update )
10888 // used when entering arena
10889 // destroys all conjured items
10890 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10892 // in inventory
10893 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10894 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10895 if (pItem->IsConjuredConsumable())
10896 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10898 // in inventory bags
10899 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10900 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10901 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10902 if (Item* pItem = pBag->GetItemByPos(j))
10903 if (pItem->IsConjuredConsumable())
10904 DestroyItem( i, j, update);
10906 // in equipment and bag list
10907 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10908 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10909 if (pItem->IsConjuredConsumable())
10910 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10913 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10915 if(!pItem)
10916 return;
10918 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10920 if( pItem->GetCount() <= count )
10922 count -= pItem->GetCount();
10924 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10926 else
10928 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10929 pItem->SetCount( pItem->GetCount() - count );
10930 count = 0;
10931 if( IsInWorld() & update )
10932 pItem->SendUpdateToPlayer( this );
10933 pItem->SetState(ITEM_CHANGED, this);
10937 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10939 uint8 srcbag = src >> 8;
10940 uint8 srcslot = src & 255;
10942 uint8 dstbag = dst >> 8;
10943 uint8 dstslot = dst & 255;
10945 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10946 if( !pSrcItem )
10948 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10949 return;
10952 // not let split all items (can be only at cheating)
10953 if(pSrcItem->GetCount() == count)
10955 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10956 return;
10959 // not let split more existed items (can be only at cheating)
10960 if(pSrcItem->GetCount() < count)
10962 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10963 return;
10966 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10968 //best error message found for attempting to split while looting
10969 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10970 return;
10973 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10974 Item *pNewItem = pSrcItem->CloneItem( count, this );
10975 if( !pNewItem )
10977 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10978 return;
10981 if( IsInventoryPos( dst ) )
10983 // change item amount before check (for unique max count check)
10984 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10986 ItemPosCountVec dest;
10987 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10988 if( msg != EQUIP_ERR_OK )
10990 delete pNewItem;
10991 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10992 SendEquipError( msg, pSrcItem, NULL );
10993 return;
10996 if( IsInWorld() )
10997 pSrcItem->SendUpdateToPlayer( this );
10998 pSrcItem->SetState(ITEM_CHANGED, this);
10999 StoreItem( dest, pNewItem, true);
11001 else if( IsBankPos ( dst ) )
11003 // change item amount before check (for unique max count check)
11004 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11006 ItemPosCountVec dest;
11007 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11008 if( msg != EQUIP_ERR_OK )
11010 delete pNewItem;
11011 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11012 SendEquipError( msg, pSrcItem, NULL );
11013 return;
11016 if( IsInWorld() )
11017 pSrcItem->SendUpdateToPlayer( this );
11018 pSrcItem->SetState(ITEM_CHANGED, this);
11019 BankItem( dest, pNewItem, true);
11021 else if( IsEquipmentPos ( dst ) )
11023 // change item amount before check (for unique max count check), provide space for splitted items
11024 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11026 uint16 dest;
11027 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11028 if( msg != EQUIP_ERR_OK )
11030 delete pNewItem;
11031 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11032 SendEquipError( msg, pSrcItem, NULL );
11033 return;
11036 if( IsInWorld() )
11037 pSrcItem->SendUpdateToPlayer( this );
11038 pSrcItem->SetState(ITEM_CHANGED, this);
11039 EquipItem( dest, pNewItem, true);
11040 AutoUnequipOffhandIfNeed();
11044 void Player::SwapItem( uint16 src, uint16 dst )
11046 uint8 srcbag = src >> 8;
11047 uint8 srcslot = src & 255;
11049 uint8 dstbag = dst >> 8;
11050 uint8 dstslot = dst & 255;
11052 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11053 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11055 if( !pSrcItem )
11056 return;
11058 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11060 if(!isAlive() )
11062 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11063 return;
11066 // SRC checks
11068 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11070 //best error message found for attempting to swap while looting
11071 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11072 return;
11075 // check unequip potability for equipped items and bank bags
11076 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11078 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11079 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
11080 if(msg != EQUIP_ERR_OK)
11082 SendEquipError( msg, pSrcItem, pDstItem );
11083 return;
11087 // prevent put equipped/bank bag in self
11088 if( IsBagPos ( src ) && srcslot == dstbag)
11090 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11091 return;
11094 // DST checks
11096 if (pDstItem)
11098 if(pDstItem->m_lootGenerated) // prevent swap looting item
11100 //best error message found for attempting to swap while looting
11101 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11102 return;
11105 // check unequip potability for equipped items and bank bags
11106 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11108 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11109 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
11110 if(msg != EQUIP_ERR_OK)
11112 SendEquipError( msg, pSrcItem, pDstItem );
11113 return;
11118 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11119 // or swap empty bag with another empty or not empty bag (with items exchange)
11121 // Move case
11122 if( !pDstItem )
11124 if( IsInventoryPos( dst ) )
11126 ItemPosCountVec dest;
11127 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11128 if( msg != EQUIP_ERR_OK )
11130 SendEquipError( msg, pSrcItem, NULL );
11131 return;
11134 RemoveItem(srcbag, srcslot, true);
11135 StoreItem( dest, pSrcItem, true);
11137 else if( IsBankPos ( dst ) )
11139 ItemPosCountVec dest;
11140 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11141 if( msg != EQUIP_ERR_OK )
11143 SendEquipError( msg, pSrcItem, NULL );
11144 return;
11147 RemoveItem(srcbag, srcslot, true);
11148 BankItem( dest, pSrcItem, true);
11150 else if( IsEquipmentPos ( dst ) )
11152 uint16 dest;
11153 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11154 if( msg != EQUIP_ERR_OK )
11156 SendEquipError( msg, pSrcItem, NULL );
11157 return;
11160 RemoveItem(srcbag, srcslot, true);
11161 EquipItem(dest, pSrcItem, true);
11162 AutoUnequipOffhandIfNeed();
11165 return;
11168 // attempt merge to / fill target item
11169 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11171 uint8 msg;
11172 ItemPosCountVec sDest;
11173 uint16 eDest;
11174 if( IsInventoryPos( dst ) )
11175 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11176 else if( IsBankPos ( dst ) )
11177 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11178 else if( IsEquipmentPos ( dst ) )
11179 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11180 else
11181 return;
11183 // can be merge/fill
11184 if(msg == EQUIP_ERR_OK)
11186 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11188 RemoveItem(srcbag, srcslot, true);
11190 if( IsInventoryPos( dst ) )
11191 StoreItem( sDest, pSrcItem, true);
11192 else if( IsBankPos ( dst ) )
11193 BankItem( sDest, pSrcItem, true);
11194 else if( IsEquipmentPos ( dst ) )
11196 EquipItem( eDest, pSrcItem, true);
11197 AutoUnequipOffhandIfNeed();
11200 else
11202 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11203 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11204 pSrcItem->SetState(ITEM_CHANGED, this);
11205 pDstItem->SetState(ITEM_CHANGED, this);
11206 if( IsInWorld() )
11208 pSrcItem->SendUpdateToPlayer( this );
11209 pDstItem->SendUpdateToPlayer( this );
11212 return;
11216 // impossible merge/fill, do real swap
11217 uint8 msg;
11219 // check src->dest move possibility
11220 ItemPosCountVec sDest;
11221 uint16 eDest = 0;
11222 if( IsInventoryPos( dst ) )
11223 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11224 else if( IsBankPos( dst ) )
11225 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11226 else if( IsEquipmentPos( dst ) )
11228 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11229 if( msg == EQUIP_ERR_OK )
11230 msg = CanUnequipItem( eDest, true );
11233 if( msg != EQUIP_ERR_OK )
11235 SendEquipError( msg, pSrcItem, pDstItem );
11236 return;
11239 // check dest->src move possibility
11240 ItemPosCountVec sDest2;
11241 uint16 eDest2 = 0;
11242 if( IsInventoryPos( src ) )
11243 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11244 else if( IsBankPos( src ) )
11245 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11246 else if( IsEquipmentPos( src ) )
11248 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11249 if( msg == EQUIP_ERR_OK )
11250 msg = CanUnequipItem( eDest2, true);
11253 if( msg != EQUIP_ERR_OK )
11255 SendEquipError( msg, pDstItem, pSrcItem );
11256 return;
11259 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11260 if(pSrcItem->IsBag() && pDstItem->IsBag())
11262 Bag* emptyBag = NULL;
11263 Bag* fullBag = NULL;
11264 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11266 emptyBag = (Bag*)pSrcItem;
11267 fullBag = (Bag*)pDstItem;
11269 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11271 emptyBag = (Bag*)pDstItem;
11272 fullBag = (Bag*)pSrcItem;
11275 // bag swap (with items exchange) case
11276 if(emptyBag && fullBag)
11278 ItemPrototype const* emotyProto = emptyBag->GetProto();
11280 uint32 count = 0;
11282 for(int i=0; i < fullBag->GetBagSize(); ++i)
11284 Item *bagItem = fullBag->GetItemByPos(i);
11285 if (!bagItem)
11286 continue;
11288 ItemPrototype const* bagItemProto = bagItem->GetProto();
11289 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11291 // one from items not go to empty target bag
11292 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11293 return;
11296 ++count;
11300 if (count > emptyBag->GetBagSize())
11302 // too small targeted bag
11303 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11304 return;
11307 // Items swap
11308 count = 0; // will pos in new bag
11309 for(int i = 0; i< fullBag->GetBagSize(); ++i)
11311 Item *bagItem = fullBag->GetItemByPos(i);
11312 if (!bagItem)
11313 continue;
11315 fullBag->RemoveItem(i, true);
11316 emptyBag->StoreItem(count, bagItem, true);
11317 bagItem->SetState(ITEM_CHANGED, this);
11319 ++count;
11324 // now do moves, remove...
11325 RemoveItem(dstbag, dstslot, false);
11326 RemoveItem(srcbag, srcslot, false);
11328 // add to dest
11329 if( IsInventoryPos( dst ) )
11330 StoreItem(sDest, pSrcItem, true);
11331 else if( IsBankPos( dst ) )
11332 BankItem(sDest, pSrcItem, true);
11333 else if( IsEquipmentPos( dst ) )
11334 EquipItem(eDest, pSrcItem, true);
11336 // add to src
11337 if( IsInventoryPos( src ) )
11338 StoreItem(sDest2, pDstItem, true);
11339 else if( IsBankPos( src ) )
11340 BankItem(sDest2, pDstItem, true);
11341 else if( IsEquipmentPos( src ) )
11342 EquipItem(eDest2, pDstItem, true);
11344 AutoUnequipOffhandIfNeed();
11347 void Player::AddItemToBuyBackSlot( Item *pItem )
11349 if( pItem )
11351 uint32 slot = m_currentBuybackSlot;
11352 // if current back slot non-empty search oldest or free
11353 if(m_items[slot])
11355 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11356 uint32 oldest_slot = BUYBACK_SLOT_START;
11358 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11360 // found empty
11361 if(!m_items[i])
11363 slot = i;
11364 break;
11367 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11369 if(oldest_time > i_time)
11371 oldest_time = i_time;
11372 oldest_slot = i;
11376 // find oldest
11377 slot = oldest_slot;
11380 RemoveItemFromBuyBackSlot( slot, true );
11381 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11383 m_items[slot] = pItem;
11384 time_t base = time(NULL);
11385 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11386 uint32 eslot = slot - BUYBACK_SLOT_START;
11388 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11389 ItemPrototype const *pProto = pItem->GetProto();
11390 if( pProto )
11391 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11392 else
11393 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11394 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11396 // move to next (for non filled list is move most optimized choice)
11397 if(m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11398 ++m_currentBuybackSlot;
11402 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11404 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11405 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11406 return m_items[slot];
11407 return NULL;
11410 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11412 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11413 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11415 Item *pItem = m_items[slot];
11416 if( pItem )
11418 pItem->RemoveFromWorld();
11419 if(del) pItem->SetState(ITEM_REMOVED, this);
11422 m_items[slot] = NULL;
11424 uint32 eslot = slot - BUYBACK_SLOT_START;
11425 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11426 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11427 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11429 // if current backslot is filled set to now free slot
11430 if(m_items[m_currentBuybackSlot])
11431 m_currentBuybackSlot = slot;
11435 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11437 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11438 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11439 data << uint8(msg);
11441 if(msg)
11443 data << uint64(pItem ? pItem->GetGUID() : 0);
11444 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11445 data << uint8(0); // not 0 there...
11447 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11449 uint32 level = 0;
11451 if(pItem)
11452 if(ItemPrototype const* proto = pItem->GetProto())
11453 level = proto->RequiredLevel;
11455 data << uint32(level); // new 2.4.0
11458 GetSession()->SendPacket(&data);
11461 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11463 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11464 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11465 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11466 data << uint32(item);
11467 if( param > 0 )
11468 data << uint32(param);
11469 data << uint8(msg);
11470 GetSession()->SendPacket(&data);
11473 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11475 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11476 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11477 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11478 data << uint64(guid);
11479 if( param > 0 )
11480 data << uint32(param);
11481 data << uint8(msg);
11482 GetSession()->SendPacket(&data);
11485 void Player::ClearTrade()
11487 tradeGold = 0;
11488 acceptTrade = false;
11489 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11490 tradeItems[i] = NULL_SLOT;
11493 void Player::TradeCancel(bool sendback)
11495 if(pTrader)
11497 // send yellow "Trade canceled" message to both traders
11498 WorldSession* ws;
11499 ws = GetSession();
11500 if(sendback)
11501 ws->SendCancelTrade();
11502 ws = pTrader->GetSession();
11503 if(!ws->PlayerLogout())
11504 ws->SendCancelTrade();
11506 // cleanup
11507 ClearTrade();
11508 pTrader->ClearTrade();
11509 // prevent loss of reference
11510 pTrader->pTrader = NULL;
11511 pTrader = NULL;
11515 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11517 if(m_itemDuration.empty())
11518 return;
11520 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11522 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11524 Item* item = *itr;
11525 ++itr; // current element can be erased in UpdateDuration
11527 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11528 item->UpdateDuration(this,time);
11532 void Player::UpdateEnchantTime(uint32 time)
11534 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11536 assert(itr->item);
11537 next = itr;
11538 if(!itr->item->GetEnchantmentId(itr->slot))
11540 next = m_enchantDuration.erase(itr);
11542 else if(itr->leftduration <= time)
11544 ApplyEnchantment(itr->item, itr->slot, false, false);
11545 itr->item->ClearEnchantment(itr->slot);
11546 next = m_enchantDuration.erase(itr);
11548 else if(itr->leftduration > time)
11550 itr->leftduration -= time;
11551 ++next;
11556 void Player::AddEnchantmentDurations(Item *item)
11558 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11560 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11561 continue;
11563 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11564 if( duration > 0 )
11565 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11569 void Player::RemoveEnchantmentDurations(Item *item)
11571 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11573 if(itr->item == item)
11575 // save duration in item
11576 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11577 itr = m_enchantDuration.erase(itr);
11579 else
11580 ++itr;
11584 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11586 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11587 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11589 next = itr;
11590 if(itr->slot == slot)
11592 if(itr->item && itr->item->GetEnchantmentId(slot))
11594 // remove from stats
11595 ApplyEnchantment(itr->item, slot, false, false);
11596 // remove visual
11597 itr->item->ClearEnchantment(slot);
11599 // remove from update list
11600 next = m_enchantDuration.erase(itr);
11602 else
11603 ++next;
11606 // remove enchants from inventory items
11607 // NOTE: no need to remove these from stats, since these aren't equipped
11608 // in inventory
11609 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11611 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11612 if( pItem && pItem->GetEnchantmentId(slot) )
11613 pItem->ClearEnchantment(slot);
11616 // in inventory bags
11617 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11619 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11620 if( pBag )
11622 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11624 Item* pItem = pBag->GetItemByPos(j);
11625 if( pItem && pItem->GetEnchantmentId(slot) )
11626 pItem->ClearEnchantment(slot);
11632 // duration == 0 will remove item enchant
11633 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11635 if(!item)
11636 return;
11638 if(slot >= MAX_ENCHANTMENT_SLOT)
11639 return;
11641 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11643 if(itr->item == item && itr->slot == slot)
11645 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11646 m_enchantDuration.erase(itr);
11647 break;
11650 if(item && duration > 0 )
11652 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11653 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11657 void Player::ApplyEnchantment(Item *item,bool apply)
11659 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11660 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11663 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11665 if(!item)
11666 return;
11668 if(!item->IsEquipped())
11669 return;
11671 if(slot >= MAX_ENCHANTMENT_SLOT)
11672 return;
11674 uint32 enchant_id = item->GetEnchantmentId(slot);
11675 if(!enchant_id)
11676 return;
11678 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11679 if(!pEnchant)
11680 return;
11682 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11683 return;
11685 if (!item->IsBroken())
11687 for (int s = 0; s < 3; ++s)
11689 uint32 enchant_display_type = pEnchant->type[s];
11690 uint32 enchant_amount = pEnchant->amount[s];
11691 uint32 enchant_spell_id = pEnchant->spellid[s];
11693 switch(enchant_display_type)
11695 case ITEM_ENCHANTMENT_TYPE_NONE:
11696 break;
11697 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11698 // processed in Player::CastItemCombatSpell
11699 break;
11700 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11701 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11702 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11703 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11704 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11705 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11706 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11707 break;
11708 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11709 if(enchant_spell_id)
11711 if(apply)
11713 int32 basepoints = 0;
11714 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11715 if (item->GetItemRandomPropertyId())
11717 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11718 if (item_rand)
11720 // Search enchant_amount
11721 for (int k = 0; k < 3; ++k)
11723 if(item_rand->enchant_id[k] == enchant_id)
11725 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11726 break;
11731 // Cast custom spell vs all equal basepoints getted from enchant_amount
11732 if (basepoints)
11733 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11734 else
11735 CastSpell(this, enchant_spell_id, true, item);
11737 else
11738 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11740 break;
11741 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11742 if (!enchant_amount)
11744 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11745 if(item_rand)
11747 for (int k = 0; k < 3; ++k)
11749 if(item_rand->enchant_id[k] == enchant_id)
11751 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11752 break;
11758 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11759 break;
11760 case ITEM_ENCHANTMENT_TYPE_STAT:
11762 if (!enchant_amount)
11764 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11765 if(item_rand_suffix)
11767 for (int k = 0; k < 3; ++k)
11769 if(item_rand_suffix->enchant_id[k] == enchant_id)
11771 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11772 break;
11778 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11779 switch (enchant_spell_id)
11781 case ITEM_MOD_MANA:
11782 sLog.outDebug("+ %u MANA",enchant_amount);
11783 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
11784 break;
11785 case ITEM_MOD_HEALTH:
11786 sLog.outDebug("+ %u HEALTH",enchant_amount);
11787 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
11788 break;
11789 case ITEM_MOD_AGILITY:
11790 sLog.outDebug("+ %u AGILITY",enchant_amount);
11791 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11792 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11793 break;
11794 case ITEM_MOD_STRENGTH:
11795 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11796 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11797 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11798 break;
11799 case ITEM_MOD_INTELLECT:
11800 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11801 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11802 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11803 break;
11804 case ITEM_MOD_SPIRIT:
11805 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11806 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11807 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11808 break;
11809 case ITEM_MOD_STAMINA:
11810 sLog.outDebug("+ %u STAMINA",enchant_amount);
11811 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11812 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11813 break;
11814 case ITEM_MOD_DEFENSE_SKILL_RATING:
11815 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11816 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11817 break;
11818 case ITEM_MOD_DODGE_RATING:
11819 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11820 sLog.outDebug("+ %u DODGE", enchant_amount);
11821 break;
11822 case ITEM_MOD_PARRY_RATING:
11823 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11824 sLog.outDebug("+ %u PARRY", enchant_amount);
11825 break;
11826 case ITEM_MOD_BLOCK_RATING:
11827 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11828 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11829 break;
11830 case ITEM_MOD_HIT_MELEE_RATING:
11831 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11832 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11833 break;
11834 case ITEM_MOD_HIT_RANGED_RATING:
11835 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11836 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11837 break;
11838 case ITEM_MOD_HIT_SPELL_RATING:
11839 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11840 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11841 break;
11842 case ITEM_MOD_CRIT_MELEE_RATING:
11843 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11844 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11845 break;
11846 case ITEM_MOD_CRIT_RANGED_RATING:
11847 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11848 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11849 break;
11850 case ITEM_MOD_CRIT_SPELL_RATING:
11851 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11852 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11853 break;
11854 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11855 // in Enchantments
11856 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11857 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11858 // break;
11859 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11860 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11861 // break;
11862 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11863 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11864 // break;
11865 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11866 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11867 // break;
11868 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11869 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11870 // break;
11871 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11872 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11873 // break;
11874 // case ITEM_MOD_HASTE_MELEE_RATING:
11875 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11876 // break;
11877 // case ITEM_MOD_HASTE_RANGED_RATING:
11878 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11879 // break;
11880 case ITEM_MOD_HASTE_SPELL_RATING:
11881 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11882 break;
11883 case ITEM_MOD_HIT_RATING:
11884 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11885 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11886 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11887 sLog.outDebug("+ %u HIT", enchant_amount);
11888 break;
11889 case ITEM_MOD_CRIT_RATING:
11890 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11891 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11892 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11893 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11894 break;
11895 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11896 // case ITEM_MOD_HIT_TAKEN_RATING:
11897 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11898 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11899 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11900 // break;
11901 // case ITEM_MOD_CRIT_TAKEN_RATING:
11902 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11903 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11904 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11905 // break;
11906 case ITEM_MOD_RESILIENCE_RATING:
11907 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11908 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11909 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11910 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11911 break;
11912 case ITEM_MOD_HASTE_RATING:
11913 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11914 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11915 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11916 sLog.outDebug("+ %u HASTE", enchant_amount);
11917 break;
11918 case ITEM_MOD_EXPERTISE_RATING:
11919 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11920 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11921 break;
11922 case ITEM_MOD_ATTACK_POWER:
11923 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11924 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11925 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11926 break;
11927 case ITEM_MOD_RANGED_ATTACK_POWER:
11928 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11929 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11930 break;
11931 case ITEM_MOD_FERAL_ATTACK_POWER:
11932 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11933 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11934 break;
11935 case ITEM_MOD_MANA_REGENERATION:
11936 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
11937 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
11938 break;
11939 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11940 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11941 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11942 break;
11943 case ITEM_MOD_SPELL_POWER:
11944 ((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
11945 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
11946 break;
11947 case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
11948 case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
11949 default:
11950 break;
11952 break;
11954 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11956 if(getClass() == CLASS_SHAMAN)
11958 float addValue = 0.0f;
11959 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11961 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11962 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11964 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11966 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11967 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11970 break;
11972 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
11973 // processed in Player::CastItemUseSpell
11974 break;
11975 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
11976 // nothing do..
11977 break;
11978 default:
11979 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
11980 break;
11981 } /*switch(enchant_display_type)*/
11982 } /*for*/
11985 // visualize enchantment at player and equipped items
11986 if(slot == PERM_ENCHANTMENT_SLOT)
11987 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
11989 if(slot == TEMP_ENCHANTMENT_SLOT)
11990 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
11993 if(apply_dur)
11995 if(apply)
11997 // set duration
11998 uint32 duration = item->GetEnchantmentDuration(slot);
11999 if(duration > 0)
12000 AddEnchantmentDuration(item, slot, duration);
12002 else
12004 // duration == 0 will remove EnchantDuration
12005 AddEnchantmentDuration(item, slot, 0);
12010 void Player::SendEnchantmentDurations()
12012 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
12014 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
12018 void Player::SendItemDurations()
12020 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
12022 (*itr)->SendTimeUpdate(this);
12026 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12028 if(!item) // prevent crash
12029 return;
12031 // last check 2.0.10
12032 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12033 data << uint64(GetGUID()); // player GUID
12034 data << uint32(received); // 0=looted, 1=from npc
12035 data << uint32(created); // 0=received, 1=created
12036 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12037 data << uint8(item->GetBagSlot()); // bagslot
12038 // item slot, but when added to stack: 0xFFFFFFFF
12039 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
12040 data << uint32(item->GetEntry()); // item id
12041 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12042 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12043 data << uint32(count); // count of items
12044 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
12046 if (broadcast && GetGroup())
12047 GetGroup()->BroadcastPacket(&data, true);
12048 else
12049 GetSession()->SendPacket(&data);
12052 /*********************************************************/
12053 /*** QUEST SYSTEM ***/
12054 /*********************************************************/
12056 void Player::PrepareQuestMenu( uint64 guid )
12058 Object *pObject;
12059 QuestRelations* pObjectQR;
12060 QuestRelations* pObjectQIR;
12062 // pets also can have quests
12063 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
12064 if( pCreature )
12066 pObject = (Object*)pCreature;
12067 pObjectQR = &objmgr.mCreatureQuestRelations;
12068 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12070 else
12072 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12073 //only for quests which cast teleport spells on player
12074 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
12075 ASSERT(_map);
12076 GameObject *pGameObject = _map->GetGameObject(guid);
12077 if( pGameObject )
12079 pObject = (Object*)pGameObject;
12080 pObjectQR = &objmgr.mGOQuestRelations;
12081 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12083 else
12084 return;
12087 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12088 qm.ClearMenu();
12090 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12092 uint32 quest_id = i->second;
12093 QuestStatus status = GetQuestStatus( quest_id );
12094 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12095 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12096 else if ( status == QUEST_STATUS_INCOMPLETE )
12097 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12098 else if (status == QUEST_STATUS_AVAILABLE )
12099 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12102 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12104 uint32 quest_id = i->second;
12105 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12106 if(!pQuest) continue;
12108 QuestStatus status = GetQuestStatus( quest_id );
12110 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12111 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12112 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12113 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12117 void Player::SendPreparedQuest( uint64 guid )
12119 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12120 if( questMenu.Empty() )
12121 return;
12123 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
12125 uint32 status = qmi0.m_qIcon;
12127 // single element case
12128 if ( questMenu.MenuItemCount() == 1 )
12130 // Auto open -- maybe also should verify there is no greeting
12131 uint32 quest_id = qmi0.m_qId;
12132 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12134 if ( pQuest )
12136 if( status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus( quest_id ) )
12137 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
12138 else if( status == DIALOG_STATUS_UNK2 )
12139 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
12140 // Send completable on repeatable quest if player don't have quest
12141 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
12142 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
12143 else
12144 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
12147 // multiply entries
12148 else
12150 QEmote qe;
12151 qe._Delay = 0;
12152 qe._Emote = 0;
12153 std::string title = "";
12155 // need pet case for some quests
12156 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
12157 if( pCreature )
12159 uint32 textid = pCreature->GetNpcTextId();
12160 GossipText const* gossiptext = objmgr.GetGossipText(textid);
12161 if( !gossiptext )
12163 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12164 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12165 title = "";
12167 else
12169 qe = gossiptext->Options[0].Emotes[0];
12171 if(!gossiptext->Options[0].Text_0.empty())
12173 title = gossiptext->Options[0].Text_0;
12175 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12176 if (loc_idx >= 0)
12178 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12179 if (nl)
12181 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12182 title = nl->Text_0[0][loc_idx];
12186 else
12188 title = gossiptext->Options[0].Text_1;
12190 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12191 if (loc_idx >= 0)
12193 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12194 if (nl)
12196 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12197 title = nl->Text_1[0][loc_idx];
12203 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12207 bool Player::IsActiveQuest( uint32 quest_id ) const
12209 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12211 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12214 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12216 Object *pObject;
12217 QuestRelations* pObjectQR;
12218 QuestRelations* pObjectQIR;
12220 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
12221 if( pCreature )
12223 pObject = (Object*)pCreature;
12224 pObjectQR = &objmgr.mCreatureQuestRelations;
12225 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12227 else
12229 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12230 //only for quests which cast teleport spells on player
12231 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
12232 ASSERT(_map);
12233 GameObject *pGameObject = _map->GetGameObject(guid);
12234 if( pGameObject )
12236 pObject = (Object*)pGameObject;
12237 pObjectQR = &objmgr.mGOQuestRelations;
12238 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12240 else
12241 return NULL;
12244 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12245 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12247 if (itr->second == nextQuestID)
12248 return objmgr.GetQuestTemplate(nextQuestID);
12251 return NULL;
12254 bool Player::CanSeeStartQuest( Quest const *pQuest )
12256 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12257 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12258 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12259 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12261 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12264 return false;
12267 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12269 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12270 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12271 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12272 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12273 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12274 && SatisfyQuestDay( pQuest, msg );
12277 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12279 if( !SatisfyQuestLog( msg ) )
12280 return false;
12282 uint32 srcitem = pQuest->GetSrcItemId();
12283 if( srcitem > 0 )
12285 uint32 count = pQuest->GetSrcItemCount();
12286 ItemPosCountVec dest;
12287 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12289 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12290 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12291 return true;
12292 else if( msg2 != EQUIP_ERR_OK )
12294 SendEquipError( msg2, NULL, NULL );
12295 return false;
12298 return true;
12301 bool Player::CanCompleteQuest( uint32 quest_id )
12303 if( quest_id )
12305 QuestStatusData& q_status = mQuestStatus[quest_id];
12306 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12307 return false; // not allow re-complete quest
12309 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12311 if(!qInfo)
12312 return false;
12314 // auto complete quest
12315 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12316 return true;
12318 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12321 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12323 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12325 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12326 return false;
12330 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12332 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12334 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12335 continue;
12337 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12338 return false;
12342 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12343 return false;
12345 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12346 return false;
12348 if ( qInfo->GetRewOrReqMoney() < 0 )
12350 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12351 return false;
12354 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12355 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12356 return false;
12358 return true;
12361 return false;
12364 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12366 // Solve problem that player don't have the quest and try complete it.
12367 // if repeatable she must be able to complete event if player don't have it.
12368 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12369 if( !CanTakeQuest(pQuest, false) )
12370 return false;
12372 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12373 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12374 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12375 return false;
12377 if( !CanRewardQuest(pQuest, false) )
12378 return false;
12380 return true;
12383 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12385 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12386 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12387 return false;
12389 // daily quest can't be rewarded (25 daily quest already completed)
12390 if(!SatisfyQuestDay(pQuest,true))
12391 return false;
12393 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12394 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12395 return false;
12397 // prevent receive reward with quest items in bank
12398 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12400 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12402 if( pQuest->ReqItemCount[i]!= 0 &&
12403 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12405 if(msg)
12406 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12407 return false;
12412 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12413 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12414 return false;
12416 return true;
12419 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12421 // prevent receive reward with quest items in bank or for not completed quest
12422 if(!CanRewardQuest(pQuest,msg))
12423 return false;
12425 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12427 if( pQuest->RewChoiceItemId[reward] )
12429 ItemPosCountVec dest;
12430 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12431 if( res != EQUIP_ERR_OK )
12433 SendEquipError( res, NULL, NULL );
12434 return false;
12439 if ( pQuest->GetRewItemsCount() > 0 )
12441 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12443 if( pQuest->RewItemId[i] )
12445 ItemPosCountVec dest;
12446 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12447 if( res != EQUIP_ERR_OK )
12449 SendEquipError( res, NULL, NULL );
12450 return false;
12456 return true;
12459 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12461 uint16 log_slot = FindQuestSlot( 0 );
12462 assert(log_slot < MAX_QUEST_LOG_SIZE);
12464 uint32 quest_id = pQuest->GetQuestId();
12466 // if not exist then created with set uState==NEW and rewarded=false
12467 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12469 // check for repeatable quests status reset
12470 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12471 questStatusData.m_explored = false;
12473 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12475 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12476 questStatusData.m_itemcount[i] = 0;
12479 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12481 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12482 questStatusData.m_creatureOrGOcount[i] = 0;
12485 GiveQuestSourceItem( pQuest );
12486 AdjustQuestReqItemCount( pQuest, questStatusData );
12488 if( pQuest->GetRepObjectiveFaction() )
12489 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12490 GetReputationMgr().SetVisible(factionEntry);
12492 uint32 qtime = 0;
12493 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12495 uint32 limittime = pQuest->GetLimitTime();
12497 // shared timed quest
12498 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12499 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12501 AddTimedQuest( quest_id );
12502 questStatusData.m_timer = limittime * IN_MILISECONDS;
12503 qtime = static_cast<uint32>(time(NULL)) + limittime;
12505 else
12506 questStatusData.m_timer = 0;
12508 SetQuestSlot(log_slot, quest_id, qtime);
12510 if (questStatusData.uState != QUEST_NEW)
12511 questStatusData.uState = QUEST_CHANGED;
12513 //starting initial quest script
12514 if(questGiver && pQuest->GetQuestStartScript()!=0)
12515 GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12517 // Some spells applied at quest activation
12518 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12519 if(saBounds.first != saBounds.second)
12521 uint32 zone, area;
12522 GetZoneAndAreaId(zone,area);
12524 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12525 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12526 if( !HasAura(itr->second->spellId,0) )
12527 CastSpell(this,itr->second->spellId,true);
12530 UpdateForQuestWorldObjects();
12533 void Player::CompleteQuest( uint32 quest_id )
12535 if( quest_id )
12537 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12539 uint16 log_slot = FindQuestSlot( quest_id );
12540 if( log_slot < MAX_QUEST_LOG_SIZE)
12541 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12543 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12545 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12546 RewardQuest(qInfo,0,this,false);
12547 else
12548 SendQuestComplete( quest_id );
12553 void Player::IncompleteQuest( uint32 quest_id )
12555 if( quest_id )
12557 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12559 uint16 log_slot = FindQuestSlot( quest_id );
12560 if( log_slot < MAX_QUEST_LOG_SIZE)
12561 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12565 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12567 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
12568 //should work fine, cause far teleport will be executed in Player::Update()
12569 SetCanDelayTeleport(true);
12571 uint32 quest_id = pQuest->GetQuestId();
12573 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i )
12575 if (pQuest->ReqItemId[i])
12576 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12579 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12580 // SetTimedQuest( 0 );
12581 m_timedquests.erase(pQuest->GetQuestId());
12583 if (pQuest->GetRewChoiceItemsCount() > 0)
12585 if (uint32 itemId = pQuest->RewChoiceItemId[reward])
12587 ItemPosCountVec dest;
12588 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK)
12590 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
12591 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12596 if (pQuest->GetRewItemsCount() > 0)
12598 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12600 if (uint32 itemId = pQuest->RewItemId[i])
12602 ItemPosCountVec dest;
12603 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i] ) == EQUIP_ERR_OK)
12605 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
12606 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12612 RewardReputation( pQuest );
12614 uint16 log_slot = FindQuestSlot( quest_id );
12615 if (log_slot < MAX_QUEST_LOG_SIZE)
12616 SetQuestSlot(log_slot,0);
12618 QuestStatusData& q_status = mQuestStatus[quest_id];
12620 // Not give XP in case already completed once repeatable quest
12621 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12623 if (getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
12624 GiveXP( XP , NULL );
12625 else
12627 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12628 ModifyMoney( money );
12629 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12632 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12633 if (pQuest->GetRewOrReqMoney())
12635 ModifyMoney( pQuest->GetRewOrReqMoney() );
12637 if (pQuest->GetRewOrReqMoney() > 0)
12638 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12641 // honor reward
12642 if (pQuest->GetRewHonorableKills())
12643 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12645 // title reward
12646 if (pQuest->GetCharTitleId())
12648 if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12649 SetTitle(titleEntry);
12652 if (pQuest->GetBonusTalents())
12654 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12655 InitTalentForLevel();
12658 // Send reward mail
12659 if (pQuest->GetRewMailTemplateId())
12661 MailMessageType mailType;
12662 uint32 senderGuidOrEntry;
12663 switch(questGiver->GetTypeId())
12665 case TYPEID_UNIT:
12666 mailType = MAIL_CREATURE;
12667 senderGuidOrEntry = questGiver->GetEntry();
12668 break;
12669 case TYPEID_GAMEOBJECT:
12670 mailType = MAIL_GAMEOBJECT;
12671 senderGuidOrEntry = questGiver->GetEntry();
12672 break;
12673 case TYPEID_ITEM:
12674 mailType = MAIL_ITEM;
12675 senderGuidOrEntry = questGiver->GetEntry();
12676 break;
12677 case TYPEID_PLAYER:
12678 mailType = MAIL_NORMAL;
12679 senderGuidOrEntry = questGiver->GetGUIDLow();
12680 break;
12681 default:
12682 mailType = MAIL_NORMAL;
12683 senderGuidOrEntry = GetGUIDLow();
12684 break;
12687 Loot questMailLoot;
12689 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12691 // fill mail
12692 MailItemsInfo mi; // item list preparing
12694 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12695 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12697 if (LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12699 if (Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12701 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12702 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12707 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12710 if (pQuest->IsDaily())
12712 SetDailyQuestStatus(quest_id);
12713 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12716 if (!pQuest->IsRepeatable())
12717 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12718 else
12719 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12721 q_status.m_rewarded = true;
12722 if (q_status.uState != QUEST_NEW)
12723 q_status.uState = QUEST_CHANGED;
12725 if (announce)
12726 SendQuestReward( pQuest, XP, questGiver );
12728 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
12729 if (pQuest->GetRewSpellCast() > 0)
12730 CastSpell( this, pQuest->GetRewSpellCast(), true);
12731 else if ( pQuest->GetRewSpell() > 0)
12732 CastSpell( this, pQuest->GetRewSpell(), true);
12734 if (pQuest->GetZoneOrSort() > 0)
12735 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12736 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12737 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
12739 uint32 zone = 0;
12740 uint32 area = 0;
12742 // remove auras from spells with quest reward state limitations
12743 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12744 if(saEndBounds.first != saEndBounds.second)
12746 GetZoneAndAreaId(zone,area);
12748 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12749 if(!itr->second->IsFitToRequirements(this,zone,area))
12750 RemoveAurasDueToSpell(itr->second->spellId);
12753 // Some spells applied at quest reward
12754 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12755 if(saBounds.first != saBounds.second)
12757 if(!zone || !area)
12758 GetZoneAndAreaId(zone,area);
12760 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12761 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12762 if( !HasAura(itr->second->spellId,0) )
12763 CastSpell(this,itr->second->spellId,true);
12766 //lets remove flag for delayed teleports
12767 SetCanDelayTeleport(false);
12770 void Player::FailQuest(uint32 questId)
12772 if (Quest const* pQuest = objmgr.GetQuestTemplate(questId))
12774 SetQuestStatus(questId, QUEST_STATUS_FAILED);
12776 uint16 log_slot = FindQuestSlot(questId);
12778 if (log_slot < MAX_QUEST_LOG_SIZE)
12780 SetQuestSlotTimer(log_slot, 1);
12781 SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
12784 if (pQuest->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
12786 QuestStatusData& q_status = mQuestStatus[questId];
12788 q_status.m_timer = 0;
12790 SendQuestTimerFailed(questId);
12792 else
12793 SendQuestFailed(questId);
12797 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12799 int32 zoneOrSort = qInfo->GetZoneOrSort();
12800 int32 skillOrClass = qInfo->GetSkillOrClass();
12802 // skip zone zoneOrSort and 0 case skillOrClass
12803 if( zoneOrSort >= 0 && skillOrClass == 0 )
12804 return true;
12806 int32 questSort = -zoneOrSort;
12807 uint8 reqSortClass = ClassByQuestSort(questSort);
12809 // check class sort cases in zoneOrSort
12810 if( reqSortClass != 0 && getClass() != reqSortClass)
12812 if( msg )
12813 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12814 return false;
12817 // check class
12818 if( skillOrClass < 0 )
12820 uint8 reqClass = -int32(skillOrClass);
12821 if(getClass() != reqClass)
12823 if( msg )
12824 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12825 return false;
12828 // check skill
12829 else if( skillOrClass > 0 )
12831 uint32 reqSkill = skillOrClass;
12832 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12834 if( msg )
12835 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12836 return false;
12840 return true;
12843 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12845 if( getLevel() < qInfo->GetMinLevel() )
12847 if( msg )
12848 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12849 return false;
12851 return true;
12854 bool Player::SatisfyQuestLog( bool msg )
12856 // exist free slot
12857 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12858 return true;
12860 if( msg )
12862 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12863 GetSession()->SendPacket( &data );
12864 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12866 return false;
12869 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12871 // No previous quest (might be first quest in a series)
12872 if( qInfo->prevQuests.empty())
12873 return true;
12875 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12877 uint32 prevId = abs(*iter);
12879 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12880 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12882 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12884 // If any of the positive previous quests completed, return true
12885 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12887 // skip one-from-all exclusive group
12888 if(qPrevInfo->GetExclusiveGroup() >= 0)
12889 return true;
12891 // each-from-all exclusive group ( < 0)
12892 // can be start if only all quests in prev quest exclusive group completed and rewarded
12893 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12894 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12896 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12898 for(; iter2 != end; ++iter2)
12900 uint32 exclude_Id = iter2->second;
12902 // skip checked quest id, only state of other quests in group is interesting
12903 if(exclude_Id == prevId)
12904 continue;
12906 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12908 // alternative quest from group also must be completed and rewarded(reported)
12909 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12911 if( msg )
12912 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12913 return false;
12916 return true;
12918 // If any of the negative previous quests active, return true
12919 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12920 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12922 // skip one-from-all exclusive group
12923 if(qPrevInfo->GetExclusiveGroup() >= 0)
12924 return true;
12926 // each-from-all exclusive group ( < 0)
12927 // can be start if only all quests in prev quest exclusive group active
12928 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12929 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12931 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12933 for(; iter2 != end; ++iter2)
12935 uint32 exclude_Id = iter2->second;
12937 // skip checked quest id, only state of other quests in group is interesting
12938 if(exclude_Id == prevId)
12939 continue;
12941 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12943 // alternative quest from group also must be active
12944 if( i_exstatus == mQuestStatus.end() ||
12945 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12946 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12948 if( msg )
12949 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12950 return false;
12953 return true;
12958 // Has only positive prev. quests in non-rewarded state
12959 // and negative prev. quests in non-active state
12960 if( msg )
12961 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12963 return false;
12966 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12968 uint32 reqraces = qInfo->GetRequiredRaces();
12969 if ( reqraces == 0 )
12970 return true;
12971 if( (reqraces & getRaceMask()) == 0 )
12973 if( msg )
12974 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12975 return false;
12977 return true;
12980 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12982 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12983 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12985 if( msg )
12986 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12987 return false;
12990 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12991 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12993 if( msg )
12994 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12995 return false;
12998 return true;
13001 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13003 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13004 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13006 if( msg )
13007 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13008 return false;
13010 return true;
13013 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
13015 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
13017 if( msg )
13018 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
13019 return false;
13021 return true;
13024 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13026 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13027 if(qInfo->GetExclusiveGroup() <= 0)
13028 return true;
13030 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13031 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13033 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13035 for(; iter != end; ++iter)
13037 uint32 exclude_Id = iter->second;
13039 // skip checked quest id, only state of other quests in group is interesting
13040 if(exclude_Id == qInfo->GetQuestId())
13041 continue;
13043 // not allow have daily quest if daily quest from exclusive group already recently completed
13044 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
13045 if( !SatisfyQuestDay(Nquest, false) )
13047 if( msg )
13048 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13049 return false;
13052 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13054 // alternative quest already started or completed
13055 if( i_exstatus != mQuestStatus.end()
13056 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13058 if( msg )
13059 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13060 return false;
13063 return true;
13066 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13068 if(!qInfo->GetNextQuestInChain())
13069 return true;
13071 // next quest in chain already started or completed
13072 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13073 if( itr != mQuestStatus.end()
13074 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13076 if( msg )
13077 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13078 return false;
13081 // check for all quests further up the chain
13082 // only necessary if there are quest chains with more than one quest that can be skipped
13083 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13084 return true;
13087 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13089 // No previous quest in chain
13090 if( qInfo->prevChainQuests.empty())
13091 return true;
13093 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13095 uint32 prevId = *iter;
13097 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13099 if( i_prevstatus != mQuestStatus.end() )
13101 // If any of the previous quests in chain active, return false
13102 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13103 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13105 if( msg )
13106 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13107 return false;
13111 // check for all quests further down the chain
13112 // only necessary if there are quest chains with more than one quest that can be skipped
13113 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13114 // return false;
13117 // No previous quest in chain active
13118 return true;
13121 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13123 if(!qInfo->IsDaily())
13124 return true;
13126 bool have_slot = false;
13127 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13129 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13130 if(qInfo->GetQuestId()==id)
13131 return false;
13133 if(!id)
13134 have_slot = true;
13137 if(!have_slot)
13139 if( msg )
13140 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13141 return false;
13144 return true;
13147 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13149 uint32 srcitem = pQuest->GetSrcItemId();
13150 if( srcitem > 0 )
13152 uint32 count = pQuest->GetSrcItemCount();
13153 if( count <= 0 )
13154 count = 1;
13156 ItemPosCountVec dest;
13157 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13158 if( msg == EQUIP_ERR_OK )
13160 Item * item = StoreNewItem(dest, srcitem, true);
13161 SendNewItem(item, count, true, false);
13162 return true;
13164 // player already have max amount required item, just report success
13165 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13166 return true;
13167 else
13168 SendEquipError( msg, NULL, NULL );
13169 return false;
13172 return true;
13175 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13177 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13178 if( qInfo )
13180 uint32 srcitem = qInfo->GetSrcItemId();
13181 if( srcitem > 0 )
13183 uint32 count = qInfo->GetSrcItemCount();
13184 if( count <= 0 )
13185 count = 1;
13187 // exist one case when destroy source quest item not possible:
13188 // non un-equippable item (equipped non-empty bag, for example)
13189 uint8 res = CanUnequipItems(srcitem,count);
13190 if(res != EQUIP_ERR_OK)
13192 if(msg)
13193 SendEquipError( res, NULL, NULL );
13194 return false;
13197 DestroyItemCount(srcitem, count, true, true);
13200 return true;
13203 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13205 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13206 if( qInfo )
13208 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13209 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13210 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13211 && !qInfo->IsRepeatable() )
13212 return itr->second.m_rewarded;
13214 return false;
13216 return false;
13219 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13221 if( quest_id )
13223 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13224 if( itr != mQuestStatus.end() )
13225 return itr->second.m_status;
13227 return QUEST_STATUS_NONE;
13230 bool Player::CanShareQuest(uint32 quest_id) const
13232 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13233 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13235 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13236 if( itr != mQuestStatus.end() )
13237 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13239 return false;
13242 void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
13244 if (Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
13246 if (status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE || status == QUEST_STATUS_FAILED)
13248 if (qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13249 m_timedquests.erase(qInfo->GetQuestId());
13252 QuestStatusData& q_status = mQuestStatus[quest_id];
13254 q_status.m_status = status;
13256 if (q_status.uState != QUEST_NEW)
13257 q_status.uState = QUEST_CHANGED;
13260 UpdateForQuestWorldObjects();
13263 // not used in MaNGOS, but used in scripting code
13264 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13266 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13267 if( !qInfo )
13268 return 0;
13270 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13271 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13272 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13274 return 0;
13277 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13279 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13281 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13283 uint32 reqitemcount = pQuest->ReqItemCount[i];
13284 if( reqitemcount != 0 )
13286 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13288 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13289 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13295 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13297 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13298 if ( GetQuestSlotQuestId(i) == quest_id )
13299 return i;
13301 return MAX_QUEST_LOG_SIZE;
13304 void Player::AreaExploredOrEventHappens( uint32 questId )
13306 if( questId )
13308 uint16 log_slot = FindQuestSlot( questId );
13309 if( log_slot < MAX_QUEST_LOG_SIZE)
13311 QuestStatusData& q_status = mQuestStatus[questId];
13313 if(!q_status.m_explored)
13315 q_status.m_explored = true;
13316 if (q_status.uState != QUEST_NEW)
13317 q_status.uState = QUEST_CHANGED;
13320 if( CanCompleteQuest( questId ) )
13321 CompleteQuest( questId );
13325 //not used in mangosd, function for external script library
13326 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13328 if( Group *pGroup = GetGroup() )
13330 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13332 Player *pGroupGuy = itr->getSource();
13334 // for any leave or dead (with not released body) group member at appropriate distance
13335 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13336 pGroupGuy->AreaExploredOrEventHappens(questId);
13339 else
13340 AreaExploredOrEventHappens(questId);
13343 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13345 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13347 uint32 questid = GetQuestSlotQuestId(i);
13348 if ( questid == 0 )
13349 continue;
13351 QuestStatusData& q_status = mQuestStatus[questid];
13353 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13354 continue;
13356 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13357 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13358 continue;
13360 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13362 uint32 reqitem = qInfo->ReqItemId[j];
13363 if ( reqitem == entry )
13365 uint32 reqitemcount = qInfo->ReqItemCount[j];
13366 uint32 curitemcount = q_status.m_itemcount[j];
13367 if ( curitemcount < reqitemcount )
13369 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13370 q_status.m_itemcount[j] += additemcount;
13371 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13373 SendQuestUpdateAddItem( qInfo, j, additemcount );
13375 if ( CanCompleteQuest( questid ) )
13376 CompleteQuest( questid );
13377 return;
13381 UpdateForQuestWorldObjects();
13384 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13386 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13388 uint32 questid = GetQuestSlotQuestId(i);
13389 if(!questid)
13390 continue;
13391 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13392 if ( !qInfo )
13393 continue;
13394 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13395 continue;
13397 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13399 uint32 reqitem = qInfo->ReqItemId[j];
13400 if ( reqitem == entry )
13402 QuestStatusData& q_status = mQuestStatus[questid];
13404 uint32 reqitemcount = qInfo->ReqItemCount[j];
13405 uint32 curitemcount;
13406 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13407 curitemcount = q_status.m_itemcount[j];
13408 else
13409 curitemcount = GetItemCount(entry,true);
13410 if ( curitemcount < reqitemcount + count )
13412 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13413 q_status.m_itemcount[j] = curitemcount - remitemcount;
13414 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13416 IncompleteQuest( questid );
13418 return;
13422 UpdateForQuestWorldObjects();
13425 void Player::KilledMonster( CreatureInfo const* cInfo, uint64 guid )
13427 if(cInfo->Entry)
13428 KilledMonsterCredit(cInfo->Entry,guid);
13430 for(int i = 0; i < MAX_KILL_CREDIT; ++i)
13431 if(cInfo->KillCredit[i])
13432 KilledMonsterCredit(cInfo->KillCredit[i],guid);
13435 void Player::KilledMonsterCredit( uint32 entry, uint64 guid )
13437 uint32 addkillcount = 1;
13438 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13439 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13441 uint32 questid = GetQuestSlotQuestId(i);
13442 if(!questid)
13443 continue;
13445 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13446 if( !qInfo )
13447 continue;
13448 // just if !ingroup || !noraidgroup || raidgroup
13449 QuestStatusData& q_status = mQuestStatus[questid];
13450 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13452 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13454 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13456 // skip GO activate objective or none
13457 if(qInfo->ReqCreatureOrGOId[j] <=0)
13458 continue;
13460 // skip Cast at creature objective
13461 if(qInfo->ReqSpell[j] !=0 )
13462 continue;
13464 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13466 if ( reqkill == entry )
13468 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13469 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13470 if ( curkillcount < reqkillcount )
13472 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13473 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13475 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13477 if ( CanCompleteQuest( questid ) )
13478 CompleteQuest( questid );
13480 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13481 continue;
13489 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13491 bool isCreature = IS_CREATURE_GUID(guid);
13493 uint32 addCastCount = 1;
13494 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13496 uint32 questid = GetQuestSlotQuestId(i);
13497 if(!questid)
13498 continue;
13500 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13501 if ( !qInfo )
13502 continue;
13504 QuestStatusData& q_status = mQuestStatus[questid];
13506 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13508 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13510 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13512 // skip kill creature objective (0) or wrong spell casts
13513 if(qInfo->ReqSpell[j] != spell_id )
13514 continue;
13516 uint32 reqTarget = 0;
13518 if(isCreature)
13520 // creature activate objectives
13521 if(qInfo->ReqCreatureOrGOId[j] > 0)
13522 // checked at quest_template loading
13523 reqTarget = qInfo->ReqCreatureOrGOId[j];
13525 else
13527 // GO activate objective
13528 if(qInfo->ReqCreatureOrGOId[j] < 0)
13529 // checked at quest_template loading
13530 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13533 // other not this creature/GO related objectives
13534 if( reqTarget != entry )
13535 continue;
13537 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13538 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13539 if ( curCastCount < reqCastCount )
13541 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13542 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13544 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13547 if ( CanCompleteQuest( questid ) )
13548 CompleteQuest( questid );
13550 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13551 break;
13558 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13560 uint32 addTalkCount = 1;
13561 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13563 uint32 questid = GetQuestSlotQuestId(i);
13564 if(!questid)
13565 continue;
13567 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13568 if ( !qInfo )
13569 continue;
13571 QuestStatusData& q_status = mQuestStatus[questid];
13573 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13575 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13577 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13579 // skip spell casts and Gameobject objectives
13580 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13581 continue;
13583 uint32 reqTarget = 0;
13585 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13586 // checked at quest_template loading
13587 reqTarget = qInfo->ReqCreatureOrGOId[j];
13588 else
13589 continue;
13591 if ( reqTarget == entry )
13593 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13594 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13595 if ( curTalkCount < reqTalkCount )
13597 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13598 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13600 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13602 if ( CanCompleteQuest( questid ) )
13603 CompleteQuest( questid );
13605 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13606 continue;
13614 void Player::MoneyChanged( uint32 count )
13616 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13618 uint32 questid = GetQuestSlotQuestId(i);
13619 if (!questid)
13620 continue;
13622 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13623 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13625 QuestStatusData& q_status = mQuestStatus[questid];
13627 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13629 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13631 if ( CanCompleteQuest( questid ) )
13632 CompleteQuest( questid );
13635 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13637 if(int32(count) < -qInfo->GetRewOrReqMoney())
13638 IncompleteQuest( questid );
13644 void Player::ReputationChanged(FactionEntry const* factionEntry )
13646 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13648 if(uint32 questid = GetQuestSlotQuestId(i))
13650 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13652 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13654 QuestStatusData& q_status = mQuestStatus[questid];
13655 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13657 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13658 if ( CanCompleteQuest( questid ) )
13659 CompleteQuest( questid );
13661 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13663 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13664 IncompleteQuest( questid );
13672 bool Player::HasQuestForItem( uint32 itemid ) const
13674 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13676 uint32 questid = GetQuestSlotQuestId(i);
13677 if ( questid == 0 )
13678 continue;
13680 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13681 if(qs_itr == mQuestStatus.end())
13682 continue;
13684 QuestStatusData const& q_status = qs_itr->second;
13686 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13688 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13689 if(!qinfo)
13690 continue;
13692 // hide quest if player is in raid-group and quest is no raid quest
13693 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13694 continue;
13696 // There should be no mixed ReqItem/ReqSource drop
13697 // This part for ReqItem drop
13698 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13700 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13701 return true;
13703 // This part - for ReqSource
13704 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
13706 // examined item is a source item
13707 if (qinfo->ReqSourceId[j] == itemid)
13709 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13711 // 'unique' item
13712 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13713 return true;
13715 // allows custom amount drop when not 0
13716 if (qinfo->ReqSourceCount[j])
13718 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13719 return true;
13720 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13721 return true;
13726 return false;
13729 void Player::SendQuestComplete( uint32 quest_id )
13731 if( quest_id )
13733 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13734 data << uint32(quest_id);
13735 GetSession()->SendPacket( &data );
13736 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13740 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13742 uint32 questid = pQuest->GetQuestId();
13743 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13744 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13745 data << uint32(questid);
13747 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13749 data << uint32(XP);
13750 data << uint32(pQuest->GetRewOrReqMoney());
13752 else
13754 data << uint32(0);
13755 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13758 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13759 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13760 GetSession()->SendPacket( &data );
13762 if (pQuest->GetQuestCompleteScript() != 0)
13763 GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13766 void Player::SendQuestFailed( uint32 quest_id )
13768 if( quest_id )
13770 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13771 data << quest_id;
13772 data << uint32(0); // failed reason (4 for inventory is full)
13773 GetSession()->SendPacket( &data );
13774 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13778 void Player::SendQuestTimerFailed( uint32 quest_id )
13780 if( quest_id )
13782 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13783 data << quest_id;
13784 GetSession()->SendPacket( &data );
13785 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13789 void Player::SendCanTakeQuestResponse( uint32 msg )
13791 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13792 data << uint32(msg);
13793 GetSession()->SendPacket( &data );
13794 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13797 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13799 if( pPlayer )
13801 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13802 data << uint64(pPlayer->GetGUID());
13803 data << uint8(msg); // valid values: 0-8
13804 GetSession()->SendPacket( &data );
13805 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13809 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13811 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13812 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13813 //data << pQuest->ReqItemId[item_idx];
13814 //data << count;
13815 GetSession()->SendPacket( &data );
13818 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13820 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13822 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13823 if (entry < 0)
13824 // client expected gameobject template id in form (id|0x80000000)
13825 entry = (-entry) | 0x80000000;
13827 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13828 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13829 data << uint32(pQuest->GetQuestId());
13830 data << uint32(entry);
13831 data << uint32(old_count + add_count);
13832 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13833 data << uint64(guid);
13834 GetSession()->SendPacket(&data);
13836 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13837 if( log_slot < MAX_QUEST_LOG_SIZE)
13838 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13841 /*********************************************************/
13842 /*** LOAD SYSTEM ***/
13843 /*********************************************************/
13845 void Player::_LoadDeclinedNames(QueryResult* result)
13847 if(!result)
13848 return;
13850 if(m_declinedname)
13851 delete m_declinedname;
13853 m_declinedname = new DeclinedName;
13854 Field *fields = result->Fetch();
13855 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13856 m_declinedname->name[i] = fields[i].GetCppString();
13858 delete result;
13861 void Player::_LoadArenaTeamInfo(QueryResult *result)
13863 // arenateamid, played_week, played_season, personal_rating
13864 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13865 if (!result)
13866 return;
13870 Field *fields = result->Fetch();
13872 uint32 arenateamid = fields[0].GetUInt32();
13873 uint32 played_week = fields[1].GetUInt32();
13874 uint32 played_season = fields[2].GetUInt32();
13875 uint32 personal_rating = fields[3].GetUInt32();
13877 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13878 if(!aTeam)
13880 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13881 continue;
13883 uint8 arenaSlot = aTeam->GetSlot();
13885 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13886 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13887 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13888 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13889 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13890 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13892 }while (result->NextRow());
13893 delete result;
13896 void Player::_LoadEquipmentSets(QueryResult *result)
13898 // 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));
13899 if (!result)
13900 return;
13902 uint32 count = 0;
13905 Field *fields = result->Fetch();
13907 EquipmentSet eqSet;
13909 eqSet.Guid = fields[0].GetUInt64();
13910 uint32 index = fields[1].GetUInt32();
13911 eqSet.Name = fields[2].GetCppString();
13912 eqSet.IconName = fields[3].GetCppString();
13913 eqSet.state = EQUIPMENT_SET_UNCHANGED;
13915 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
13916 eqSet.Items[i] = fields[4+i].GetUInt32();
13918 m_EquipmentSets[index] = eqSet;
13920 ++count;
13922 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
13923 break;
13924 } while (result->NextRow());
13925 delete result;
13928 void Player::_LoadBGData(QueryResult* result)
13930 if (!result)
13931 return;
13933 // Expecting only one row
13934 Field *fields = result->Fetch();
13935 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
13936 m_bgData.bgInstanceID = fields[0].GetUInt32();
13937 m_bgData.bgTeam = fields[1].GetUInt32();
13938 m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
13939 fields[2].GetFloat(), // X
13940 fields[3].GetFloat(), // Y
13941 fields[4].GetFloat(), // Z
13942 fields[5].GetFloat()); // Orientation
13943 m_bgData.taxiPath[0] = fields[7].GetUInt32();
13944 m_bgData.taxiPath[1] = fields[8].GetUInt32();
13945 m_bgData.mountSpell = fields[9].GetUInt32();
13947 delete result;
13950 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13952 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13953 if(!result)
13954 return false;
13956 Field *fields = result->Fetch();
13958 x = fields[0].GetFloat();
13959 y = fields[1].GetFloat();
13960 z = fields[2].GetFloat();
13961 o = fields[3].GetFloat();
13962 mapid = fields[4].GetUInt32();
13963 in_flight = !fields[5].GetCppString().empty();
13965 delete result;
13966 return true;
13969 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13971 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13972 if( !result )
13973 return false;
13975 Field *fields = result->Fetch();
13977 data = StrSplit(fields[0].GetCppString(), " ");
13979 delete result;
13981 return true;
13984 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13986 if(index >= data.size())
13987 return 0;
13989 return (uint32)atoi(data[index].c_str());
13992 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13994 float result;
13995 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13996 memcpy(&result, &temp, sizeof(result));
13998 return result;
14001 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14003 Tokens data;
14004 if(!LoadValuesArrayFromDB(data,guid))
14005 return 0;
14007 return GetUInt32ValueFromArray(data,index);
14010 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14012 float result;
14013 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14014 memcpy(&result, &temp, sizeof(result));
14016 return result;
14019 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14021 //// 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
14022 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points FROM characters WHERE guid = '%u'", guid);
14023 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14025 if(!result)
14027 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14028 return false;
14031 Field *fields = result->Fetch();
14033 uint32 dbAccountId = fields[1].GetUInt32();
14035 // check if the character's account in the db and the logged in account match.
14036 // player should be able to load/delete character only with correct account!
14037 if( dbAccountId != GetSession()->GetAccountId() )
14039 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14040 delete result;
14041 return false;
14044 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14046 m_name = fields[3].GetCppString();
14048 // check name limitations
14049 if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
14050 GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
14052 delete result;
14053 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14054 return false;
14057 if(!LoadValues( fields[2].GetString()))
14059 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
14060 delete result;
14061 return false;
14064 // overwrite possible wrong/corrupted guid
14065 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14067 // overwrite some data fields
14068 uint32 bytes0 = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0xFF000000;
14069 bytes0 |= fields[4].GetUInt8(); // race
14070 bytes0 |= fields[5].GetUInt8() << 8; // class
14071 bytes0 |= fields[6].GetUInt8() << 16; // gender
14072 SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
14074 SetUInt32Value(UNIT_FIELD_LEVEL, fields[7].GetUInt8());
14075 SetUInt32Value(PLAYER_XP, fields[8].GetUInt32());
14076 SetUInt32Value(PLAYER_FIELD_COINAGE, fields[9].GetUInt32());
14077 SetUInt32Value(PLAYER_BYTES, fields[10].GetUInt32());
14078 SetUInt32Value(PLAYER_BYTES_2, fields[11].GetUInt32());
14079 SetUInt32Value(PLAYER_BYTES_3, (GetUInt32Value(PLAYER_BYTES_3) & ~1) | fields[6].GetUInt8());
14080 SetUInt32Value(PLAYER_FLAGS, fields[12].GetUInt32());
14082 InitDisplayIds();
14084 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14085 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14087 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
14088 SetVisibleItemSlot(slot, NULL);
14090 if (m_items[slot])
14092 delete m_items[slot];
14093 m_items[slot] = NULL;
14097 // update money limits
14098 if(GetMoney() > MAX_MONEY_AMOUNT)
14099 SetMoney(MAX_MONEY_AMOUNT);
14101 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14102 outDebugValues();
14104 //Need to call it to initialize m_team (m_team can be calculated from race)
14105 //Other way is to saves m_team into characters table.
14106 setFactionForRace(getRace());
14107 SetCharm(NULL);
14109 // load home bind and check in same time class/race pair, it used later for restore broken positions
14110 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14112 delete result;
14113 return false;
14116 InitPrimaryProfessions(); // to max set before any spell loaded
14118 // init saved position, and fix it later if problematic
14119 uint32 transGUID = fields[31].GetUInt32();
14120 Relocate(fields[13].GetFloat(),fields[14].GetFloat(),fields[15].GetFloat(),fields[17].GetFloat());
14121 SetLocationMapId(fields[16].GetUInt32());
14122 SetDifficulty(fields[39].GetUInt32()); // may be changed in _LoadGroup
14124 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14126 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14128 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[40].GetUInt32();
14129 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
14130 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14132 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14134 // check arena teams integrity
14135 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14137 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14138 if(!arena_team_id)
14139 continue;
14141 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
14142 if(at->HaveMember(GetGUID()))
14143 continue;
14145 // arena team not exist or not member, cleanup fields
14146 for(int j =0; j < 6; ++j)
14147 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
14150 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14152 if(!IsPositionValid())
14154 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());
14155 RelocateToHomebind();
14157 transGUID = 0;
14159 m_movementInfo.t_x = 0.0f;
14160 m_movementInfo.t_y = 0.0f;
14161 m_movementInfo.t_z = 0.0f;
14162 m_movementInfo.t_o = 0.0f;
14165 _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
14167 if(m_bgData.bgInstanceID) //saved in BattleGround
14169 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
14171 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14173 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14174 AddBattleGroundQueueId(bgQueueTypeId);
14176 m_bgData.bgTypeID = currentBg->GetTypeID();
14178 //join player to battleground group
14179 currentBg->EventPlayerLoggedIn(this, GetGUID());
14180 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData.bgTeam);
14182 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14184 else
14186 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14187 SetLocationMapId(_loc.mapid);
14188 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14190 // We are not in BG anymore
14191 m_bgData.bgInstanceID = 0;
14194 else
14196 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14197 // if server restart after player save in BG or area
14198 // player can have current coordinates in to BG/Arean map, fix this
14199 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14201 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14202 SetLocationMapId(_loc.mapid);
14203 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14207 if (transGUID != 0)
14209 m_movementInfo.t_x = fields[27].GetFloat();
14210 m_movementInfo.t_y = fields[28].GetFloat();
14211 m_movementInfo.t_z = fields[29].GetFloat();
14212 m_movementInfo.t_o = fields[30].GetFloat();
14214 if( !MaNGOS::IsValidMapCoord(
14215 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14216 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14217 // transport size limited
14218 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14220 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14221 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14222 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14224 RelocateToHomebind();
14226 m_movementInfo.t_x = 0.0f;
14227 m_movementInfo.t_y = 0.0f;
14228 m_movementInfo.t_z = 0.0f;
14229 m_movementInfo.t_o = 0.0f;
14231 transGUID = 0;
14235 if (transGUID != 0)
14237 for (MapManager::TransportSet::const_iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14239 if( (*iter)->GetGUIDLow() == transGUID)
14241 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14242 // client without expansion support
14243 if(GetSession()->Expansion() < transMapEntry->Expansion())
14245 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14246 break;
14249 m_transport = *iter;
14250 m_transport->AddPassenger(this);
14251 SetLocationMapId(m_transport->GetMapId());
14252 break;
14256 if(!m_transport)
14258 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14259 guid,transGUID);
14261 RelocateToHomebind();
14263 m_movementInfo.t_x = 0.0f;
14264 m_movementInfo.t_y = 0.0f;
14265 m_movementInfo.t_z = 0.0f;
14266 m_movementInfo.t_o = 0.0f;
14268 transGUID = 0;
14271 else // not transport case
14273 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14274 // client without expansion support
14275 if(GetSession()->Expansion() < mapEntry->Expansion())
14277 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14278 RelocateToHomebind();
14282 // NOW player must have valid map
14283 // load the player's map here if it's not already loaded
14284 SetMap(MapManager::Instance().CreateMap(GetMapId(), this));
14286 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14287 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14289 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14290 if(at)
14291 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14292 else
14293 sLog.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14296 SaveRecallPosition();
14298 time_t now = time(NULL);
14299 time_t logoutTime = time_t(fields[23].GetUInt64());
14301 // since last logout (in seconds)
14302 uint64 time_diff = uint64(now - logoutTime);
14304 // set value, including drunk invisibility detection
14305 // calculate sobering. after 15 minutes logged out, the player will be sober again
14306 float soberFactor;
14307 if(time_diff > 15*MINUTE)
14308 soberFactor = 0;
14309 else
14310 soberFactor = 1-time_diff/(15.0f*MINUTE);
14311 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14312 SetDrunkValue(newDrunkenValue);
14314 m_rest_bonus = fields[22].GetFloat();
14315 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14316 float bubble0 = 0.031;
14317 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14318 float bubble1 = 0.125;
14320 if(time_diff > 0)
14322 float bubble = fields[24].GetUInt32() > 0
14323 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14324 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14326 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14329 m_cinematic = fields[19].GetUInt32();
14330 m_Played_time[PLAYED_TIME_TOTAL]= fields[20].GetUInt32();
14331 m_Played_time[PLAYED_TIME_LEVEL]= fields[21].GetUInt32();
14333 m_resetTalentsCost = fields[25].GetUInt32();
14334 m_resetTalentsTime = time_t(fields[26].GetUInt64());
14336 // reserve some flags
14337 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14339 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14340 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14342 m_taxi.LoadTaxiMask( fields[18].GetString() ); // must be before InitTaxiNodesForLevel
14344 uint32 extraflags = fields[32].GetUInt32();
14346 m_stableSlots = fields[33].GetUInt32();
14347 if(m_stableSlots > MAX_PET_STABLES)
14349 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14350 m_stableSlots = MAX_PET_STABLES;
14353 m_atLoginFlags = fields[34].GetUInt32();
14355 // Honor system
14356 // Update Honor kills data
14357 m_lastHonorUpdateTime = logoutTime;
14358 UpdateHonorFields();
14360 m_deathExpireTime = (time_t)fields[37].GetUInt64();
14361 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14362 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14364 std::string taxi_nodes = fields[38].GetCppString();
14366 delete result;
14368 // clear channel spell data (if saved at channel spell casting)
14369 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14370 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14372 // clear charm/summon related fields
14373 SetCharm(NULL);
14374 SetPet(NULL);
14375 SetCharmerGUID(0);
14376 SetOwnerGUID(0);
14377 SetCreatorGUID(0);
14379 // reset some aura modifiers before aura apply
14380 SetFarSightGUID(0);
14381 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14382 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14384 _LoadSkills();
14386 // make sure the unit is considered out of combat for proper loading
14387 ClearInCombat();
14389 // make sure the unit is considered not in duel for proper loading
14390 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14391 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14393 // remember loaded power/health values to restore after stats initialization and modifier applying
14394 uint32 savedHealth = GetHealth();
14395 uint32 savedPower[MAX_POWERS];
14396 for(uint32 i = 0; i < MAX_POWERS; ++i)
14397 savedPower[i] = GetPower(Powers(i));
14399 // reset stats before loading any modifiers
14400 InitStatsForLevel();
14401 InitTaxiNodesForLevel();
14402 InitGlyphsForLevel();
14403 InitRunes();
14405 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14407 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14408 //_LoadMail();
14410 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14411 _LoadGlyphAuras();
14413 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14414 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14415 m_deathState = DEAD;
14417 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14419 // after spell load, learn rewarded spell if need also
14420 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14421 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14423 // after spell and quest load
14424 InitTalentForLevel();
14425 learnDefaultSpells();
14427 // must be before inventory (some items required reputation check)
14428 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14430 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14432 // update items with duration and realtime
14433 UpdateItemDuration(time_diff, true);
14435 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14437 // unread mails and next delivery time, actual mails not loaded
14438 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14440 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14442 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14443 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14444 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14446 if(!HasTitle(curTitle))
14447 SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
14450 // Not finish taxi flight path
14451 if(m_bgData.HasTaxiPath())
14453 m_taxi.ClearTaxiDestinations();
14454 for (int i = 0; i < 2; ++i)
14455 m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
14457 else if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14459 // problems with taxi path loading
14460 TaxiNodesEntry const* nodeEntry = NULL;
14461 if(uint32 node_id = m_taxi.GetTaxiSource())
14462 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14464 if(!nodeEntry) // don't know taxi start node, to homebind
14466 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14467 RelocateToHomebind();
14469 else // have start node, to it
14471 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14472 SetLocationMapId(nodeEntry->map_id);
14473 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14476 //we can be relocated from taxi and still have an outdated Map pointer!
14477 //so we need to get a new Map pointer!
14478 SetMap(MapManager::Instance().CreateMap(GetMapId(), this));
14479 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14481 m_taxi.ClearTaxiDestinations();
14484 if(uint32 node_id = m_taxi.GetTaxiSource())
14486 // save source node as recall coord to prevent recall and fall from sky
14487 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14488 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14489 m_recallMap = nodeEntry->map_id;
14490 m_recallX = nodeEntry->x;
14491 m_recallY = nodeEntry->y;
14492 m_recallZ = nodeEntry->z;
14494 // flight will started later
14497 // has to be called after last Relocate() in Player::LoadFromDB
14498 SetFallInformation(0, GetPositionZ());
14500 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14502 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14503 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14504 if(!isAlive())
14505 RemoveAllAurasOnDeath();
14507 //apply all stat bonuses from items and auras
14508 SetCanModifyStats(true);
14509 UpdateAllStats();
14511 // restore remembered power/health values (but not more max values)
14512 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14513 for(uint32 i = 0; i < MAX_POWERS; ++i)
14514 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14516 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14517 outDebugValues();
14519 // GM state
14520 if(GetSession()->GetSecurity() > SEC_PLAYER)
14522 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14524 default:
14525 case 0: break; // disable
14526 case 1: SetGameMaster(true); break; // enable
14527 case 2: // save state
14528 if(extraflags & PLAYER_EXTRA_GM_ON)
14529 SetGameMaster(true);
14530 break;
14533 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14535 default:
14536 case 0: SetGMVisible(false); break; // invisible
14537 case 1: break; // visible
14538 case 2: // save state
14539 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14540 SetGMVisible(false);
14541 break;
14544 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14546 default:
14547 case 0: break; // disable
14548 case 1: SetAcceptTicket(true); break; // enable
14549 case 2: // save state
14550 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14551 SetAcceptTicket(true);
14552 break;
14555 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14557 default:
14558 case 0: break; // disable
14559 case 1: SetGMChat(true); break; // enable
14560 case 2: // save state
14561 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14562 SetGMChat(true);
14563 break;
14566 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14568 default:
14569 case 0: break; // disable
14570 case 1: SetAcceptWhispers(true); break; // enable
14571 case 2: // save state
14572 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14573 SetAcceptWhispers(true);
14574 break;
14578 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14580 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14581 m_achievementMgr.CheckAllAchievementCriteria();
14583 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
14585 return true;
14588 bool Player::isAllowedToLoot(Creature* creature)
14590 if(Player* recipient = creature->GetLootRecipient())
14592 if (recipient == this)
14593 return true;
14594 if( Group* otherGroup = recipient->GetGroup())
14596 Group* thisGroup = GetGroup();
14597 if(!thisGroup)
14598 return false;
14599 return thisGroup == otherGroup;
14601 return false;
14603 else
14604 // prevent other players from looting if the recipient got disconnected
14605 return !creature->hasLootRecipient();
14608 void Player::_LoadActions(QueryResult *result)
14610 m_actionButtons.clear();
14612 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14614 if(result)
14618 Field *fields = result->Fetch();
14620 uint8 button = fields[0].GetUInt8();
14621 uint32 action = fields[1].GetUInt32();
14622 uint8 type = fields[2].GetUInt8();
14624 if(ActionButton* ab = addActionButton(button, action, type))
14625 ab->uState = ACTIONBUTTON_UNCHANGED;
14626 else
14628 sLog.outError( " ...at loading, and will deleted in DB also");
14630 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14631 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14634 while( result->NextRow() );
14636 delete result;
14640 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14642 m_Auras.clear();
14643 for (int i = 0; i < TOTAL_AURAS; ++i)
14644 m_modAuras[i].clear();
14646 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14648 if(result)
14652 Field *fields = result->Fetch();
14653 uint64 caster_guid = fields[0].GetUInt64();
14654 uint32 spellid = fields[1].GetUInt32();
14655 uint32 effindex = fields[2].GetUInt32();
14656 uint32 stackcount = fields[3].GetUInt32();
14657 int32 damage = (int32)fields[4].GetUInt32();
14658 int32 maxduration = (int32)fields[5].GetUInt32();
14659 int32 remaintime = (int32)fields[6].GetUInt32();
14660 int32 remaincharges = (int32)fields[7].GetUInt32();
14662 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14663 if(!spellproto)
14665 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14666 continue;
14669 if(effindex >= 3)
14671 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14672 continue;
14675 // negative effects should continue counting down after logout
14676 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14678 if(remaintime <= int32(timediff))
14679 continue;
14681 remaintime -= timediff;
14684 // prevent wrong values of remaincharges
14685 if(spellproto->procCharges)
14687 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14688 remaincharges = spellproto->procCharges;
14690 else
14691 remaincharges = 0;
14694 for(uint32 i=0; i<stackcount; ++i)
14696 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14697 if(!damage)
14698 damage = aura->GetModifier()->m_amount;
14700 // reset stolen single target auras
14701 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14702 aura->SetIsSingleTarget(false);
14704 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14705 AddAura(aura);
14706 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14709 while( result->NextRow() );
14711 delete result;
14714 if(getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
14715 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14718 void Player::_LoadGlyphAuras()
14720 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14722 if (uint32 glyph = GetGlyph(i))
14724 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14726 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14728 if(gp->TypeFlags == gs->TypeFlags)
14730 CastSpell(this, gp->SpellId, true);
14731 continue;
14733 else
14734 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14736 else
14737 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14739 else
14740 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14742 // On any error remove glyph
14743 SetGlyph(i, 0);
14748 void Player::LoadCorpse()
14750 if( isAlive() )
14752 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14754 else
14756 if(Corpse *corpse = GetCorpse())
14758 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14760 else
14762 //Prevent Dead Player login without corpse
14763 ResurrectPlayer(0.5f);
14768 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14770 //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());
14771 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14772 //NOTE: the "order by `bag`" is important because it makes sure
14773 //the bagMap is filled before items in the bags are loaded
14774 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14775 //expected to be equipped before offhand items (TODO: fixme)
14777 uint32 zone = GetZoneId();
14779 if (result)
14781 std::list<Item*> problematicItems;
14783 // prevent items from being added to the queue when stored
14784 m_itemUpdateQueueBlocked = true;
14787 Field *fields = result->Fetch();
14788 uint32 bag_guid = fields[1].GetUInt32();
14789 uint8 slot = fields[2].GetUInt8();
14790 uint32 item_guid = fields[3].GetUInt32();
14791 uint32 item_id = fields[4].GetUInt32();
14793 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14795 if(!proto)
14797 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14798 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14799 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14800 continue;
14803 Item *item = NewItemOrBag(proto);
14805 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14807 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14808 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14809 item->FSetState(ITEM_REMOVED);
14810 item->SaveToDB(); // it also deletes item object !
14811 continue;
14814 // not allow have in alive state item limited to another map/zone
14815 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14817 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14818 item->FSetState(ITEM_REMOVED);
14819 item->SaveToDB(); // it also deletes item object !
14820 continue;
14823 // "Conjured items disappear if you are logged out for more than 15 minutes"
14824 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14826 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14827 item->FSetState(ITEM_REMOVED);
14828 item->SaveToDB(); // it also deletes item object !
14829 continue;
14832 bool success = true;
14834 if (!bag_guid)
14836 // the item is not in a bag
14837 item->SetContainer( NULL );
14838 item->SetSlot(slot);
14840 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14842 ItemPosCountVec dest;
14843 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14844 item = StoreItem(dest, item, true);
14845 else
14846 success = false;
14848 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14850 uint16 dest;
14851 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14852 QuickEquipItem(dest, item);
14853 else
14854 success = false;
14856 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14858 ItemPosCountVec dest;
14859 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14860 item = BankItem(dest, item, true);
14861 else
14862 success = false;
14865 if(success)
14867 // store bags that may contain items in them
14868 if(item->IsBag() && IsBagPos(item->GetPos()))
14869 bagMap[item_guid] = (Bag*)item;
14872 else
14874 item->SetSlot(NULL_SLOT);
14875 // the item is in a bag, find the bag
14876 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
14877 if(itr != bagMap.end() && slot < itr->second->GetBagSize())
14878 itr->second->StoreItem(slot, item, true );
14879 else
14880 success = false;
14883 // item's state may have changed after stored
14884 if (success)
14885 item->SetState(ITEM_UNCHANGED, this);
14886 else
14888 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);
14889 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14890 problematicItems.push_back(item);
14892 } while (result->NextRow());
14894 delete result;
14895 m_itemUpdateQueueBlocked = false;
14897 // send by mail problematic items
14898 while(!problematicItems.empty())
14900 // fill mail
14901 MailItemsInfo mi; // item list preparing
14903 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14905 Item* item = problematicItems.front();
14906 problematicItems.pop_front();
14908 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14911 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14913 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14916 //if(isAlive())
14917 _ApplyAllItemMods();
14920 // load mailed item which should receive current player
14921 void Player::_LoadMailedItems(Mail *mail)
14923 // data needs to be at first place for Item::LoadFromDB
14924 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);
14925 if(!result)
14926 return;
14930 Field *fields = result->Fetch();
14931 uint32 item_guid_low = fields[1].GetUInt32();
14932 uint32 item_template = fields[2].GetUInt32();
14934 mail->AddItem(item_guid_low, item_template);
14936 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14938 if(!proto)
14940 sLog.outError( "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID);
14941 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14942 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14943 continue;
14946 Item *item = NewItemOrBag(proto);
14948 if(!item->LoadFromDB(item_guid_low, 0, result))
14950 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14951 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14952 item->FSetState(ITEM_REMOVED);
14953 item->SaveToDB(); // it also deletes item object !
14954 continue;
14957 AddMItem(item);
14958 } while (result->NextRow());
14960 delete result;
14963 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14965 //set a count of unread mails
14966 //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);
14967 if (resultUnread)
14969 Field *fieldMail = resultUnread->Fetch();
14970 unReadMails = fieldMail[0].GetUInt8();
14971 delete resultUnread;
14974 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14975 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14976 if (resultDelivery)
14978 Field *fieldMail = resultDelivery->Fetch();
14979 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14980 delete resultDelivery;
14984 void Player::_LoadMail()
14986 m_mail.clear();
14987 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14988 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());
14989 if(result)
14993 Field *fields = result->Fetch();
14994 Mail *m = new Mail;
14995 m->messageID = fields[0].GetUInt32();
14996 m->messageType = fields[1].GetUInt8();
14997 m->sender = fields[2].GetUInt32();
14998 m->receiver = fields[3].GetUInt32();
14999 m->subject = fields[4].GetCppString();
15000 m->itemTextId = fields[5].GetUInt32();
15001 bool has_items = fields[6].GetBool();
15002 m->expire_time = (time_t)fields[7].GetUInt64();
15003 m->deliver_time = (time_t)fields[8].GetUInt64();
15004 m->money = fields[9].GetUInt32();
15005 m->COD = fields[10].GetUInt32();
15006 m->checked = fields[11].GetUInt32();
15007 m->stationery = fields[12].GetUInt8();
15008 m->mailTemplateId = fields[13].GetInt16();
15010 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15012 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15013 m->mailTemplateId = 0;
15016 m->state = MAIL_STATE_UNCHANGED;
15018 if (has_items)
15019 _LoadMailedItems(m);
15021 m_mail.push_back(m);
15022 } while( result->NextRow() );
15023 delete result;
15025 m_mailsLoaded = true;
15028 void Player::LoadPet()
15030 //fixme: the pet should still be loaded if the player is not in world
15031 // just not added to the map
15032 if(IsInWorld())
15034 Pet *pet = new Pet;
15035 if(!pet->LoadPetFromDB(this,0,0,true))
15036 delete pet;
15040 void Player::_LoadQuestStatus(QueryResult *result)
15042 mQuestStatus.clear();
15044 uint32 slot = 0;
15046 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15047 //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());
15049 if(result)
15053 Field *fields = result->Fetch();
15055 uint32 quest_id = fields[0].GetUInt32();
15056 // used to be new, no delete?
15057 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15058 if( pQuest )
15060 // find or create
15061 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15063 uint32 qstatus = fields[1].GetUInt32();
15064 if(qstatus < MAX_QUEST_STATUS)
15065 questStatusData.m_status = QuestStatus(qstatus);
15066 else
15068 questStatusData.m_status = QUEST_STATUS_NONE;
15069 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15072 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15073 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15075 time_t quest_time = time_t(fields[4].GetUInt64());
15077 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15079 AddTimedQuest( quest_id );
15081 if (quest_time <= sWorld.GetGameTime())
15082 questStatusData.m_timer = 1;
15083 else
15084 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
15086 else
15087 quest_time = 0;
15089 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15090 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15091 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15092 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15093 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15094 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15095 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15096 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15098 questStatusData.uState = QUEST_UNCHANGED;
15100 // add to quest log
15101 if (slot < MAX_QUEST_LOG_SIZE &&
15102 ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
15103 questStatusData.m_status == QUEST_STATUS_COMPLETE ||
15104 questStatusData.m_status == QUEST_STATUS_FAILED) &&
15105 (!questStatusData.m_rewarded || pQuest->IsDaily())))
15107 SetQuestSlot(slot, quest_id, quest_time);
15109 if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
15110 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
15112 if (questStatusData.m_status == QUEST_STATUS_FAILED)
15113 SetQuestSlotState(slot, QUEST_STATE_FAIL);
15115 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15116 if(questStatusData.m_creatureOrGOcount[idx])
15117 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
15119 ++slot;
15122 if(questStatusData.m_rewarded)
15124 // learn rewarded spell if unknown
15125 learnQuestRewardedSpells(pQuest);
15127 // set rewarded title if any
15128 if(pQuest->GetCharTitleId())
15130 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15131 SetTitle(titleEntry);
15134 if(pQuest->GetBonusTalents())
15135 m_questRewardTalentCount += pQuest->GetBonusTalents();
15138 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15141 while( result->NextRow() );
15143 delete result;
15146 // clear quest log tail
15147 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15148 SetQuestSlot(i, 0);
15151 void Player::_LoadDailyQuestStatus(QueryResult *result)
15153 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15154 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15156 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15158 if(result)
15160 uint32 quest_daily_idx = 0;
15164 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15166 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15167 break;
15170 Field *fields = result->Fetch();
15172 uint32 quest_id = fields[0].GetUInt32();
15174 // save _any_ from daily quest times (it must be after last reset anyway)
15175 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15177 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15178 if( !pQuest )
15179 continue;
15181 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15182 ++quest_daily_idx;
15184 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15186 while( result->NextRow() );
15188 delete result;
15191 m_DailyQuestChanged = false;
15194 void Player::_LoadSpells(QueryResult *result)
15196 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15198 if(result)
15202 Field *fields = result->Fetch();
15204 addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool());
15206 while( result->NextRow() );
15208 delete result;
15212 void Player::_LoadGroup(QueryResult *result)
15214 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15215 if(result)
15217 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15218 delete result;
15219 Group* group = objmgr.GetGroupByLeader(leaderGuid);
15220 if(group)
15222 uint8 subgroup = group->GetMemberGroup(GetGUID());
15223 SetGroup(group, subgroup);
15224 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
15226 // the group leader may change the instance difficulty while the player is offline
15227 SetDifficulty(group->GetDifficulty());
15233 void Player::_LoadBoundInstances(QueryResult *result)
15235 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15236 m_boundInstances[i].clear();
15238 Group *group = GetGroup();
15240 //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));
15241 if(result)
15245 Field *fields = result->Fetch();
15246 bool perm = fields[1].GetBool();
15247 uint32 mapId = fields[2].GetUInt32();
15248 uint32 instanceId = fields[0].GetUInt32();
15249 uint8 difficulty = fields[3].GetUInt8();
15250 time_t resetTime = (time_t)fields[4].GetUInt64();
15251 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15252 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15253 // and in that case it is not used
15255 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15256 if(!mapEntry || !mapEntry->IsDungeon())
15258 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15259 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15260 continue;
15263 if(!perm && group)
15265 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);
15266 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15267 continue;
15270 // since non permanent binds are always solo bind, they can always be reset
15271 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15272 if(save) BindToInstance(save, perm, true);
15273 } while(result->NextRow());
15274 delete result;
15278 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15280 // some instances only have one difficulty
15281 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15282 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15284 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15285 if(itr != m_boundInstances[difficulty].end())
15286 return &itr->second;
15287 else
15288 return NULL;
15291 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15293 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15294 UnbindInstance(itr, difficulty, unload);
15297 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15299 if(itr != m_boundInstances[difficulty].end())
15301 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15302 itr->second.save->RemovePlayer(this); // save can become invalid
15303 m_boundInstances[difficulty].erase(itr++);
15307 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15309 if(save)
15311 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15312 if(bind.save)
15314 // update the save when the group kills a boss
15315 if(permanent != bind.perm || save != bind.save)
15316 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());
15318 else
15319 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15321 if(bind.save != save)
15323 if(bind.save) bind.save->RemovePlayer(this);
15324 save->AddPlayer(this);
15327 if(permanent) save->SetCanReset(false);
15329 bind.save = save;
15330 bind.perm = permanent;
15331 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());
15332 return &bind;
15334 else
15335 return NULL;
15338 void Player::SendRaidInfo()
15340 uint32 counter = 0;
15342 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15344 size_t p_counter = data.wpos();
15345 data << uint32(counter); // placeholder
15347 time_t now = time(NULL);
15349 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15351 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15353 if(itr->second.perm)
15355 InstanceSave *save = itr->second.save;
15356 data << uint32(save->GetMapId()); // map id
15357 data << uint32(save->GetDifficulty()); // difficulty
15358 data << uint64(save->GetInstanceId()); // instance id
15359 data << uint32(save->GetResetTime() - now); // reset time
15360 data << uint32(0); // is extended
15361 ++counter;
15365 data.put<uint32>(p_counter, counter);
15366 GetSession()->SendPacket(&data);
15370 - called on every successful teleportation to a map
15372 void Player::SendSavedInstances()
15374 bool hasBeenSaved = false;
15375 WorldPacket data;
15377 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15379 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15381 if(itr->second.perm) // only permanent binds are sent
15383 hasBeenSaved = true;
15384 break;
15389 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15390 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15391 data << uint32(hasBeenSaved);
15392 GetSession()->SendPacket(&data);
15394 if(!hasBeenSaved)
15395 return;
15397 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15399 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15401 if(itr->second.perm)
15403 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15404 data << uint32(itr->second.save->GetMapId());
15405 GetSession()->SendPacket(&data);
15411 /// convert the player's binds to the group
15412 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15414 bool has_binds = false;
15415 bool has_solo = false;
15417 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15418 assert(player_guid);
15420 // copy all binds to the group, when changing leader it's assumed the character
15421 // will not have any solo binds
15423 if(player)
15425 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15427 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15429 has_binds = true;
15430 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15431 // permanent binds are not removed
15432 if(!itr->second.perm)
15434 player->UnbindInstance(itr, i, true); // increments itr
15435 has_solo = true;
15437 else
15438 ++itr;
15443 // if the player's not online we don't know what binds it has
15444 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));
15445 // the following should not get executed when changing leaders
15446 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15449 bool Player::_LoadHomeBind(QueryResult *result)
15451 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15452 if(!info)
15454 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15455 return false;
15458 bool ok = false;
15459 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15460 if (result)
15462 Field *fields = result->Fetch();
15463 m_homebindMapId = fields[0].GetUInt32();
15464 m_homebindZoneId = fields[1].GetUInt16();
15465 m_homebindX = fields[2].GetFloat();
15466 m_homebindY = fields[3].GetFloat();
15467 m_homebindZ = fields[4].GetFloat();
15468 delete result;
15470 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15472 // accept saved data only for valid position (and non instanceable), and accessable
15473 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15474 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15476 ok = true;
15478 else
15479 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15482 if(!ok)
15484 m_homebindMapId = info->mapId;
15485 m_homebindZoneId = info->zoneId;
15486 m_homebindX = info->positionX;
15487 m_homebindY = info->positionY;
15488 m_homebindZ = info->positionZ;
15490 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);
15493 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15494 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15496 return true;
15499 /*********************************************************/
15500 /*** SAVE SYSTEM ***/
15501 /*********************************************************/
15503 void Player::SaveToDB()
15505 // delay auto save at any saves (manual, in code, or autosave)
15506 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15508 //lets allow only players in world to be saved
15509 if(IsBeingTeleportedFar())
15511 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
15512 return;
15515 // first save/honor gain after midnight will also update the player's honor fields
15516 UpdateHonorFields();
15518 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15519 outDebugValues();
15521 CharacterDatabase.BeginTransaction();
15523 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15525 std::string sql_name = m_name;
15526 CharacterDatabase.escape_string(sql_name);
15528 std::ostringstream ss;
15529 ss << "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
15530 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15531 "taximask, online, cinematic, "
15532 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15533 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15534 "death_expire_time, taxi_path, arena_pending_points) VALUES ("
15535 << GetGUIDLow() << ", "
15536 << GetSession()->GetAccountId() << ", '"
15537 << sql_name << "', "
15538 << (uint32)getRace() << ", "
15539 << (uint32)getClass() << ", "
15540 << (uint32)getGender() << ", "
15541 << getLevel() << ", "
15542 << GetUInt32Value(PLAYER_XP) << ", "
15543 << GetMoney() << ", "
15544 << GetUInt32Value(PLAYER_BYTES) << ", "
15545 << GetUInt32Value(PLAYER_BYTES_2) << ", "
15546 << GetUInt32Value(PLAYER_FLAGS) << ", ";
15548 if(!IsBeingTeleported())
15550 ss << GetMapId() << ", "
15551 << (uint32)GetDifficulty() << ", "
15552 << finiteAlways(GetPositionX()) << ", "
15553 << finiteAlways(GetPositionY()) << ", "
15554 << finiteAlways(GetPositionZ()) << ", "
15555 << finiteAlways(GetOrientation()) << ", '";
15557 else
15559 ss << GetTeleportDest().mapid << ", "
15560 << (uint32)GetDifficulty() << ", "
15561 << finiteAlways(GetTeleportDest().coord_x) << ", "
15562 << finiteAlways(GetTeleportDest().coord_y) << ", "
15563 << finiteAlways(GetTeleportDest().coord_z) << ", "
15564 << finiteAlways(GetTeleportDest().orientation) << ", '";
15567 uint16 i;
15568 for( i = 0; i < m_valuesCount; ++i )
15570 ss << GetUInt32Value(i) << " ";
15573 ss << "', ";
15575 ss << m_taxi << ", "; // string with TaxiMaskSize numbers
15577 ss << (IsInWorld() ? 1 : 0) << ", ";
15579 ss << m_cinematic << ", ";
15581 ss << m_Played_time[PLAYED_TIME_TOTAL] << ", ";
15582 ss << m_Played_time[PLAYED_TIME_LEVEL] << ", ";
15584 ss << finiteAlways(m_rest_bonus) << ", ";
15585 ss << (uint64)time(NULL) << ", ";
15586 ss << (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0) << ", ";
15587 //save, far from tavern/city
15588 //save, but in tavern/city
15589 ss << m_resetTalentsCost << ", ";
15590 ss << (uint64)m_resetTalentsTime << ", ";
15592 ss << finiteAlways(m_movementInfo.t_x) << ", ";
15593 ss << finiteAlways(m_movementInfo.t_y) << ", ";
15594 ss << finiteAlways(m_movementInfo.t_z) << ", ";
15595 ss << finiteAlways(m_movementInfo.t_o) << ", ";
15596 if (m_transport)
15597 ss << m_transport->GetGUIDLow();
15598 else
15599 ss << "0";
15600 ss << ", ";
15602 ss << m_ExtraFlags << ", ";
15604 ss << uint32(m_stableSlots) << ", "; // to prevent save uint8 as char
15606 ss << uint32(m_atLoginFlags) << ", ";
15608 ss << GetZoneId() << ", ";
15610 ss << (uint64)m_deathExpireTime << ", '";
15612 ss << m_taxi.SaveTaxiDestinationsToString() << "', ";
15613 ss << "'0' "; // arena_pending_points
15614 ss << ")";
15616 CharacterDatabase.Execute( ss.str().c_str() );
15618 if(m_mailsUpdated) //save mails only when needed
15619 _SaveMail();
15621 _SaveBGData();
15622 _SaveInventory();
15623 _SaveQuestStatus();
15624 _SaveDailyQuestStatus();
15625 _SaveSpells();
15626 _SaveSpellCooldowns();
15627 _SaveActions();
15628 _SaveAuras();
15629 m_achievementMgr.SaveToDB();
15630 m_reputationMgr.SaveToDB();
15631 _SaveEquipmentSets();
15632 GetSession()->SaveTutorialsData(); // changed only while character in game
15634 CharacterDatabase.CommitTransaction();
15636 // save pet (hunter pet level and experience and all type pets health/mana).
15637 if(Pet* pet = GetPet())
15638 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15641 // fast save function for item/money cheating preventing - save only inventory and money state
15642 void Player::SaveInventoryAndGoldToDB()
15644 _SaveInventory();
15645 SaveGoldToDB();
15648 void Player::SaveGoldToDB()
15650 CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
15653 void Player::_SaveActions()
15655 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15657 switch (itr->second.uState)
15659 case ACTIONBUTTON_NEW:
15660 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type) VALUES ('%u', '%u', '%u', '%u')",
15661 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.GetAction(), (uint32)itr->second.GetType() );
15662 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15663 ++itr;
15664 break;
15665 case ACTIONBUTTON_CHANGED:
15666 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' ",
15667 (uint32)itr->second.GetAction(), (uint32)itr->second.GetType(), GetGUIDLow(), (uint32)itr->first );
15668 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15669 ++itr;
15670 break;
15671 case ACTIONBUTTON_DELETED:
15672 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15673 m_actionButtons.erase(itr++);
15674 break;
15675 default:
15676 ++itr;
15677 break;
15682 void Player::_SaveAuras()
15684 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15686 AuraMap const& auras = GetAuras();
15688 if (auras.empty())
15689 return;
15691 spellEffectPair lastEffectPair = auras.begin()->first;
15692 uint32 stackCounter = 1;
15694 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15696 if(itr == auras.end() || lastEffectPair != itr->first)
15698 AuraMap::const_iterator itr2 = itr;
15699 // save previous spellEffectPair to db
15700 itr2--;
15702 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15704 //skip all auras from spells that are passive
15705 //do not save single target auras (unless they were cast by the player)
15706 if (!itr2->second->IsPassive() && (itr2->second->GetCasterGUID() == GetGUID() || !itr2->second->IsSingleTarget()))
15708 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15709 "VALUES ('%u', '" UI64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15710 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()));
15713 if(itr == auras.end())
15714 break;
15717 if (lastEffectPair == itr->first)
15718 stackCounter++;
15719 else
15721 lastEffectPair = itr->first;
15722 stackCounter = 1;
15727 void Player::_SaveInventory()
15729 // force items in buyback slots to new state
15730 // and remove those that aren't already
15731 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
15733 Item *item = m_items[i];
15734 if (!item || item->GetState() == ITEM_NEW) continue;
15735 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15736 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15737 m_items[i]->FSetState(ITEM_NEW);
15740 // update enchantment durations
15741 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15743 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15746 // if no changes
15747 if (m_itemUpdateQueue.empty()) return;
15749 // do not save if the update queue is corrupt
15750 bool error = false;
15751 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15753 Item *item = m_itemUpdateQueue[i];
15754 if(!item || item->GetState() == ITEM_REMOVED) continue;
15755 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15757 if (test == NULL)
15759 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());
15760 error = true;
15762 else if (test != item)
15764 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());
15765 error = true;
15769 if (error)
15771 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15772 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15773 return;
15776 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15778 Item *item = m_itemUpdateQueue[i];
15779 if(!item) continue;
15781 Bag *container = item->GetContainer();
15782 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15784 switch(item->GetState())
15786 case ITEM_NEW:
15787 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());
15788 break;
15789 case ITEM_CHANGED:
15790 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());
15791 break;
15792 case ITEM_REMOVED:
15793 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15794 break;
15795 case ITEM_UNCHANGED:
15796 break;
15799 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15801 m_itemUpdateQueue.clear();
15804 void Player::_SaveMail()
15806 if (!m_mailsLoaded)
15807 return;
15809 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15811 Mail *m = (*itr);
15812 if (m->state == MAIL_STATE_CHANGED)
15814 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'",
15815 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15816 if(m->removedItems.size())
15818 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15819 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15820 m->removedItems.clear();
15822 m->state = MAIL_STATE_UNCHANGED;
15824 else if (m->state == MAIL_STATE_DELETED)
15826 if (m->HasItems())
15827 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15828 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15829 if (m->itemTextId)
15830 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15831 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15832 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15836 //deallocate deleted mails...
15837 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15839 if ((*itr)->state == MAIL_STATE_DELETED)
15841 Mail* m = *itr;
15842 m_mail.erase(itr);
15843 delete m;
15844 itr = m_mail.begin();
15846 else
15847 ++itr;
15850 m_mailsUpdated = false;
15853 void Player::_SaveQuestStatus()
15855 // we don't need transactions here.
15856 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15858 switch (i->second.uState)
15860 case QUEST_NEW :
15861 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15862 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15863 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]);
15864 break;
15865 case QUEST_CHANGED :
15866 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' ",
15867 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 );
15868 break;
15869 case QUEST_UNCHANGED:
15870 break;
15872 i->second.uState = QUEST_UNCHANGED;
15876 void Player::_SaveDailyQuestStatus()
15878 if(!m_DailyQuestChanged)
15879 return;
15881 m_DailyQuestChanged = false;
15883 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15885 // we don't need transactions here.
15886 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15887 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15888 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15889 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
15890 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15893 void Player::_SaveSpells()
15895 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15897 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15898 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15900 // add only changed/new not dependent spells
15901 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15902 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);
15904 if (itr->second->state == PLAYERSPELL_REMOVED)
15906 delete itr->second;
15907 m_spells.erase(itr++);
15909 else
15911 itr->second->state = PLAYERSPELL_UNCHANGED;
15912 ++itr;
15918 void Player::outDebugValues() const
15920 if(!sLog.IsOutDebug()) // optimize disabled debug output
15921 return;
15923 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15924 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15925 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15926 sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
15927 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15928 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15929 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15930 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15931 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15932 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15933 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15934 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15937 /*********************************************************/
15938 /*** FLOOD FILTER SYSTEM ***/
15939 /*********************************************************/
15941 void Player::UpdateSpeakTime()
15943 // ignore chat spam protection for GMs in any mode
15944 if(GetSession()->GetSecurity() > SEC_PLAYER)
15945 return;
15947 time_t current = time (NULL);
15948 if(m_speakTime > current)
15950 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15951 if(!max_count)
15952 return;
15954 ++m_speakCount;
15955 if(m_speakCount >= max_count)
15957 // prevent overwrite mute time, if message send just before mutes set, for example.
15958 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15959 if(GetSession()->m_muteTime < new_mute)
15960 GetSession()->m_muteTime = new_mute;
15962 m_speakCount = 0;
15965 else
15966 m_speakCount = 0;
15968 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15971 bool Player::CanSpeak() const
15973 return GetSession()->m_muteTime <= time (NULL);
15976 /*********************************************************/
15977 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15978 /*********************************************************/
15980 void Player::SendAttackSwingNotInRange()
15982 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15983 GetSession()->SendPacket( &data );
15986 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15988 std::ostringstream ss;
15989 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15990 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15991 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15992 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15993 sLog.outDebug(ss.str().c_str());
15994 CharacterDatabase.Execute(ss.str().c_str());
15997 void Player::SaveDataFieldToDB()
15999 std::ostringstream ss;
16000 ss<<"UPDATE characters SET data='";
16002 for(uint16 i = 0; i < m_valuesCount; ++i )
16004 ss << GetUInt32Value(i) << " ";
16006 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16008 CharacterDatabase.Execute(ss.str().c_str());
16011 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16013 std::ostringstream ss2;
16014 ss2<<"UPDATE characters SET data='";
16015 int i=0;
16016 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16018 ss2<<tokens[i]<<" ";
16020 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16022 return CharacterDatabase.Execute(ss2.str().c_str());
16025 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16027 char buf[11];
16028 snprintf(buf,11,"%u",value);
16030 if(index >= tokens.size())
16031 return;
16033 tokens[index] = buf;
16036 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16038 Tokens tokens;
16039 if(!LoadValuesArrayFromDB(tokens,guid))
16040 return;
16042 if(index >= tokens.size())
16043 return;
16045 char buf[11];
16046 snprintf(buf,11,"%u",value);
16047 tokens[index] = buf;
16049 SaveValuesArrayInDB(tokens,guid);
16052 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16054 uint32 temp;
16055 memcpy(&temp, &value, sizeof(value));
16056 Player::SetUInt32ValueInDB(index, temp, guid);
16059 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16061 // 0
16062 QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
16063 if(!result)
16064 return;
16066 Field* fields = result->Fetch();
16068 uint32 player_bytes2 = fields[0].GetUInt32();
16069 player_bytes2 &= ~0xFF;
16070 player_bytes2 |= facialHair;
16072 CharacterDatabase.PExecute("UPDATE characters SET gender = '%u', playerBytes = '%u', playerBytes2 = '%u' WHERE guid = '%u'", gender, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24), player_bytes2, GUID_LOPART(guid));
16074 delete result;
16077 void Player::SendAttackSwingDeadTarget()
16079 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16080 GetSession()->SendPacket( &data );
16083 void Player::SendAttackSwingCantAttack()
16085 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16086 GetSession()->SendPacket( &data );
16089 void Player::SendAttackSwingCancelAttack()
16091 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16092 GetSession()->SendPacket( &data );
16095 void Player::SendAttackSwingBadFacingAttack()
16097 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16098 GetSession()->SendPacket( &data );
16101 void Player::SendAutoRepeatCancel(Unit *target)
16103 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
16104 data.append(target->GetPackGUID()); // may be it's target guid
16105 GetSession()->SendPacket( &data );
16108 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16110 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16111 data << Area;
16112 data << Experience;
16113 GetSession()->SendPacket(&data);
16116 void Player::SendDungeonDifficulty(bool IsInGroup)
16118 uint8 val = 0x00000001;
16119 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16120 data << (uint32)GetDifficulty();
16121 data << uint32(val);
16122 data << uint32(IsInGroup);
16123 GetSession()->SendPacket(&data);
16126 void Player::SendResetFailedNotify(uint32 mapid)
16128 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16129 data << uint32(mapid);
16130 GetSession()->SendPacket(&data);
16133 /// Reset all solo instances and optionally send a message on success for each
16134 void Player::ResetInstances(uint8 method)
16136 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16138 // we assume that when the difficulty changes, all instances that can be reset will be
16139 uint8 dif = GetDifficulty();
16141 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16143 InstanceSave *p = itr->second.save;
16144 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16145 if(!entry || !p->CanReset())
16147 ++itr;
16148 continue;
16151 if(method == INSTANCE_RESET_ALL)
16153 // the "reset all instances" method can only reset normal maps
16154 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16156 ++itr;
16157 continue;
16161 // if the map is loaded, reset it
16162 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16163 if(map && map->IsDungeon())
16164 ((InstanceMap*)map)->Reset(method);
16166 // since this is a solo instance there should not be any players inside
16167 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16168 SendResetInstanceSuccess(p->GetMapId());
16170 p->DeleteFromDB();
16171 m_boundInstances[dif].erase(itr++);
16173 // the following should remove the instance save from the manager and delete it as well
16174 p->RemovePlayer(this);
16178 void Player::SendResetInstanceSuccess(uint32 MapId)
16180 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16181 data << MapId;
16182 GetSession()->SendPacket(&data);
16185 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16187 // TODO: find what other fail reasons there are besides players in the instance
16188 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16189 data << reason;
16190 data << MapId;
16191 GetSession()->SendPacket(&data);
16194 /*********************************************************/
16195 /*** Update timers ***/
16196 /*********************************************************/
16198 ///checks the 15 afk reports per 5 minutes limit
16199 void Player::UpdateAfkReport(time_t currTime)
16201 if(m_bgData.bgAfkReportedTimer <= currTime)
16203 m_bgData.bgAfkReportedCount = 0;
16204 m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
16208 void Player::UpdateContestedPvP(uint32 diff)
16210 if(!m_contestedPvPTimer||isInCombat())
16211 return;
16212 if(m_contestedPvPTimer <= diff)
16214 ResetContestedPvP();
16216 else
16217 m_contestedPvPTimer -= diff;
16220 void Player::UpdatePvPFlag(time_t currTime)
16222 if(!IsPvP())
16223 return;
16224 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16225 return;
16227 UpdatePvP(false);
16230 void Player::UpdateDuelFlag(time_t currTime)
16232 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16233 return;
16235 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16236 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16238 duel->startTimer = 0;
16239 duel->startTime = currTime;
16240 duel->opponent->duel->startTimer = 0;
16241 duel->opponent->duel->startTime = currTime;
16244 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16246 if(!pet)
16247 pet = GetPet();
16249 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16251 //returning of reagents only for players, so best done here
16252 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16253 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16255 if(spellInfo)
16257 for(uint32 i = 0; i < 7; ++i)
16259 if(spellInfo->Reagent[i] > 0)
16261 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16262 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16263 if( msg == EQUIP_ERR_OK )
16265 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16266 if(IsInWorld())
16267 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16272 m_temporaryUnsummonedPetNumber = 0;
16275 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16276 return;
16278 // only if current pet in slot
16279 switch(pet->getPetType())
16281 case MINI_PET:
16282 m_miniPet = 0;
16283 break;
16284 case GUARDIAN_PET:
16285 RemoveGuardian(pet);
16286 break;
16287 default:
16288 if(GetPetGUID() == pet->GetGUID())
16289 SetPet(NULL);
16290 break;
16293 pet->CombatStop();
16295 if(returnreagent)
16297 switch(pet->GetEntry())
16299 //warlock pets except imp are removed(?) when logging out
16300 case 1860:
16301 case 1863:
16302 case 417:
16303 case 17252:
16304 mode = PET_SAVE_NOT_IN_SLOT;
16305 break;
16309 pet->SavePetToDB(mode);
16311 pet->AddObjectToRemoveList();
16312 pet->m_removed = true;
16314 if(pet->isControlled())
16316 RemovePetActionBar();
16318 if(GetGroup())
16319 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16323 void Player::RemoveMiniPet()
16325 if(Pet* pet = GetMiniPet())
16327 pet->Remove(PET_SAVE_AS_DELETED);
16328 m_miniPet = 0;
16332 Pet* Player::GetMiniPet()
16334 if(!m_miniPet)
16335 return NULL;
16336 return ObjectAccessor::GetPet(m_miniPet);
16339 void Player::Uncharm()
16341 Unit* charm = GetCharm();
16342 if(!charm)
16343 return;
16345 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16346 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16349 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16351 *data << (uint8)msgtype;
16352 *data << (uint32)language;
16353 *data << (uint64)GetGUID();
16354 *data << (uint32)language; //language 2.1.0 ?
16355 *data << (uint64)GetGUID();
16356 *data << (uint32)(text.length()+1);
16357 *data << text;
16358 *data << (uint8)chatTag();
16361 void Player::Say(const std::string& text, const uint32 language)
16363 WorldPacket data(SMSG_MESSAGECHAT, 200);
16364 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16365 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16368 void Player::Yell(const std::string& text, const uint32 language)
16370 WorldPacket data(SMSG_MESSAGECHAT, 200);
16371 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16372 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16375 void Player::TextEmote(const std::string& text)
16377 WorldPacket data(SMSG_MESSAGECHAT, 200);
16378 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16379 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16382 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16384 if (language != LANG_ADDON) // if not addon data
16385 language = LANG_UNIVERSAL; // whispers should always be readable
16387 Player *rPlayer = objmgr.GetPlayer(receiver);
16389 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16390 if(!rPlayer->isDND() || isGameMaster())
16392 WorldPacket data(SMSG_MESSAGECHAT, 200);
16393 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16394 rPlayer->GetSession()->SendPacket(&data);
16396 data.Initialize(SMSG_MESSAGECHAT, 200);
16397 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16398 GetSession()->SendPacket(&data);
16400 else
16402 // announce to player that player he is whispering to is dnd and cannot receive his message
16403 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16406 if(!isAcceptWhispers())
16408 SetAcceptWhispers(true);
16409 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16412 // announce to player that player he is whispering to is afk
16413 if(rPlayer->isAFK())
16414 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16416 // if player whisper someone, auto turn of dnd to be able to receive an answer
16417 if(isDND() && !rPlayer->isGameMaster())
16418 ToggleDND();
16421 void Player::PetSpellInitialize()
16423 Pet* pet = GetPet();
16425 if(!pet)
16426 return;
16428 sLog.outDebug("Pet Spells Groups");
16430 CharmInfo *charmInfo = pet->GetCharmInfo();
16432 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16433 data << uint64(pet->GetGUID());
16434 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16435 data << uint32(0);
16436 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16438 // action bar loop
16439 charmInfo->BuildActionBar(&data);
16441 size_t spellsCountPos = data.wpos();
16443 // spells count
16444 uint8 addlist = 0;
16445 data << uint8(addlist); // placeholder
16447 if (pet->IsPermanentPetFor(this))
16449 // spells loop
16450 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16452 if(itr->second.state == PETSPELL_REMOVED)
16453 continue;
16455 data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
16456 ++addlist;
16460 data.put<uint8>(spellsCountPos, addlist);
16462 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16463 data << uint8(cooldownsCount);
16465 time_t curTime = time(NULL);
16467 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16469 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16471 data << uint32(itr->first); // spellid
16472 data << uint16(0); // spell category?
16473 data << uint32(cooldown); // cooldown
16474 data << uint32(0); // category cooldown
16477 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16479 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16481 data << uint32(itr->first); // spellid
16482 data << uint16(0); // spell category?
16483 data << uint32(0); // cooldown
16484 data << uint32(cooldown); // category cooldown
16487 GetSession()->SendPacket(&data);
16490 void Player::PossessSpellInitialize()
16492 Unit* charm = GetCharm();
16494 if(!charm)
16495 return;
16497 CharmInfo *charmInfo = charm->GetCharmInfo();
16499 if(!charmInfo)
16501 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16502 return;
16505 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16506 data << uint64(charm->GetGUID());
16507 data << uint16(0);
16508 data << uint32(0);
16509 data << uint32(0);
16511 charmInfo->BuildActionBar(&data);
16513 data << uint8(0); // spells count
16514 data << uint8(0); // cooldowns count
16516 GetSession()->SendPacket(&data);
16519 void Player::CharmSpellInitialize()
16521 Unit* charm = GetCharm();
16523 if(!charm)
16524 return;
16526 CharmInfo *charmInfo = charm->GetCharmInfo();
16527 if(!charmInfo)
16529 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16530 return;
16533 uint8 addlist = 0;
16535 if(charm->GetTypeId() != TYPEID_PLAYER)
16537 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16539 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16541 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16543 if(charmInfo->GetCharmSpell(i)->GetAction())
16544 ++addlist;
16549 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
16550 data << uint64(charm->GetGUID());
16551 data << uint16(0);
16552 data << uint32(0);
16554 if(charm->GetTypeId() != TYPEID_PLAYER)
16555 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16556 else
16557 data << uint8(0) << uint8(0) << uint16(0);
16559 charmInfo->BuildActionBar(&data);
16561 data << uint8(addlist);
16563 if(addlist)
16565 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16567 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16568 if(cspell->GetAction())
16569 data << uint32(cspell->packedData);
16573 data << uint8(0); // cooldowns count
16575 GetSession()->SendPacket(&data);
16578 void Player::RemovePetActionBar()
16580 WorldPacket data(SMSG_PET_SPELLS, 8);
16581 data << uint64(0);
16582 SendDirectMessage(&data);
16585 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16587 if (!mod || !spellInfo)
16588 return false;
16590 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16592 // prevent apply to any spell except spell that trigger expire
16593 if(spell)
16595 if(mod->lastAffected != spell)
16596 return false;
16598 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16599 return false;
16602 return spellmgr.IsAffectedByMod(spellInfo, mod);
16605 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16607 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16609 for(int eff=0;eff<96;++eff)
16611 uint64 _mask = 0;
16612 uint64 _mask2= 0;
16613 if (eff<64) _mask = uint64(1) << (eff- 0);
16614 else _mask2= uint64(1) << (eff-64);
16615 if ( mod->mask & _mask || mod->mask2 & _mask2)
16617 int32 val = 0;
16618 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16620 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16621 val += (*itr)->value;
16623 val += apply ? mod->value : -(mod->value);
16624 WorldPacket data(Opcode, (1+1+4));
16625 data << uint8(eff);
16626 data << uint8(mod->op);
16627 data << int32(val);
16628 SendDirectMessage(&data);
16632 if (apply)
16633 m_spellMods[mod->op].push_back(mod);
16634 else
16636 if (mod->charges == -1)
16637 --m_SpellModRemoveCount;
16638 m_spellMods[mod->op].remove(mod);
16639 delete mod;
16643 void Player::RemoveSpellMods(Spell const* spell)
16645 if(!spell || (m_SpellModRemoveCount == 0))
16646 return;
16648 for(int i=0;i<MAX_SPELLMOD;++i)
16650 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16652 SpellModifier *mod = *itr;
16653 ++itr;
16655 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16657 RemoveAurasDueToSpell(mod->spellId);
16658 if (m_spellMods[i].empty())
16659 break;
16660 else
16661 itr = m_spellMods[i].begin();
16667 // send Proficiency
16668 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16670 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16671 data << pr1 << pr2;
16672 GetSession()->SendPacket (&data);
16675 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16677 QueryResult *result = NULL;
16678 if(type==10)
16679 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16680 else
16681 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16682 if(result)
16684 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.
16685 { // and SendPetitionQueryOpcode reads data from the DB
16686 Field *fields = result->Fetch();
16687 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16688 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16690 // send update if charter owner in game
16691 Player* owner = objmgr.GetPlayer(ownerguid);
16692 if(owner)
16693 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16695 } while ( result->NextRow() );
16697 delete result;
16699 if(type==10)
16700 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16701 else
16702 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16705 CharacterDatabase.BeginTransaction();
16706 if(type == 10)
16708 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16709 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16711 else
16713 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16714 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16716 CharacterDatabase.CommitTransaction();
16719 void Player::LeaveAllArenaTeams(uint64 guid)
16721 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));
16722 if(!result)
16723 return;
16727 Field *fields = result->Fetch();
16728 uint32 at_id = fields[0].GetUInt32();
16729 if(at_id != 0)
16731 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16732 if(at)
16733 at->DelMember(guid);
16735 } while (result->NextRow());
16737 delete result;
16740 void Player::SetRestBonus (float rest_bonus_new)
16742 // Prevent resting on max level
16743 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16744 rest_bonus_new = 0;
16746 if(rest_bonus_new < 0)
16747 rest_bonus_new = 0;
16749 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16751 if(rest_bonus_new > rest_bonus_max)
16752 m_rest_bonus = rest_bonus_max;
16753 else
16754 m_rest_bonus = rest_bonus_new;
16756 // update data for client
16757 if(m_rest_bonus>10)
16758 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16759 else if(m_rest_bonus<=1)
16760 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16762 //RestTickUpdate
16763 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16766 void Player::HandleStealthedUnitsDetection()
16768 std::list<Unit*> stealthedUnits;
16770 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16771 Cell cell(p);
16772 cell.data.Part.reserved = ALL_DISTRICT;
16773 cell.SetNoCreate();
16775 MaNGOS::AnyStealthedCheck u_check;
16776 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16778 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16779 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16781 CellLock<GridReadGuard> cell_lock(cell, p);
16782 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16783 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16785 WorldObject const* viewPoint = GetViewPoint();
16787 for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
16789 if((*i)==this)
16790 continue;
16792 bool hasAtClient = HaveAtClient((*i));
16793 bool hasDetected = (*i)->isVisibleForOrDetect(this, viewPoint, true);
16795 if (hasDetected)
16797 if(!hasAtClient)
16799 (*i)->SendUpdateToPlayer(this);
16800 m_clientGUIDs.insert((*i)->GetGUID());
16802 #ifdef MANGOS_DEBUG
16803 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16804 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16805 #endif
16807 // target aura duration for caster show only if target exist at caster client
16808 // send data at target visibility change (adding to client)
16809 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16810 SendAurasForTarget(*i);
16813 else
16815 if(hasAtClient)
16817 (*i)->DestroyForPlayer(this);
16818 m_clientGUIDs.erase((*i)->GetGUID());
16824 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
16826 if(nodes.size() < 2)
16827 return false;
16829 // 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
16830 if(GetSession()->isLogingOut() || isInCombat())
16832 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16833 data << uint32(ERR_TAXIPLAYERBUSY);
16834 GetSession()->SendPacket(&data);
16835 return false;
16838 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16839 return false;
16841 // taximaster case
16842 if(npc)
16844 // not let cheating with start flight mounted
16845 if(IsMounted())
16847 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16848 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16849 GetSession()->SendPacket(&data);
16850 return false;
16853 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16855 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16856 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16857 GetSession()->SendPacket(&data);
16858 return false;
16861 // 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
16862 if(IsNonMeleeSpellCasted(false))
16864 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16865 data << uint32(ERR_TAXIPLAYERBUSY);
16866 GetSession()->SendPacket(&data);
16867 return false;
16870 // cast case or scripted call case
16871 else
16873 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
16875 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16876 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
16878 if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
16879 if (spell->m_spellInfo->Id != spellid)
16880 InterruptSpell(CURRENT_GENERIC_SPELL,false);
16882 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
16884 if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
16885 if (spell->m_spellInfo->Id != spellid)
16886 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
16889 uint32 sourcenode = nodes[0];
16891 // starting node too far away (cheat?)
16892 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16893 if (!node)
16895 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16896 data << uint32(ERR_TAXINOSUCHPATH);
16897 GetSession()->SendPacket(&data);
16898 return false;
16901 // check node starting pos data set case if provided
16902 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
16904 if (node->map_id != GetMapId() ||
16905 (node->x - GetPositionX())*(node->x - GetPositionX())+
16906 (node->y - GetPositionY())*(node->y - GetPositionY())+
16907 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16908 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
16910 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16911 data << uint32(ERR_TAXITOOFARAWAY);
16912 GetSession()->SendPacket(&data);
16913 return false;
16916 // node must have pos if taxi master case (npc != NULL)
16917 else if (npc)
16919 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16920 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16921 GetSession()->SendPacket(&data);
16922 return false;
16925 // Prepare to flight start now
16927 // stop combat at start taxi flight if any
16928 CombatStop();
16930 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16931 TradeCancel(true);
16933 // clean not finished taxi path if any
16934 m_taxi.ClearTaxiDestinations();
16936 // 0 element current node
16937 m_taxi.AddTaxiDestination(sourcenode);
16939 // fill destinations path tail
16940 uint32 sourcepath = 0;
16941 uint32 totalcost = 0;
16943 uint32 prevnode = sourcenode;
16944 uint32 lastnode = 0;
16946 for(uint32 i = 1; i < nodes.size(); ++i)
16948 uint32 path, cost;
16950 lastnode = nodes[i];
16951 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16953 if(!path)
16955 m_taxi.ClearTaxiDestinations();
16956 return false;
16959 totalcost += cost;
16961 if(prevnode == sourcenode)
16962 sourcepath = path;
16964 m_taxi.AddTaxiDestination(lastnode);
16966 prevnode = lastnode;
16969 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
16970 uint32 mount_display_id = objmgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
16972 // in spell case allow 0 model
16973 if (mount_display_id == 0 && spellid == 0 || sourcepath == 0)
16975 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16976 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16977 GetSession()->SendPacket(&data);
16978 m_taxi.ClearTaxiDestinations();
16979 return false;
16982 uint32 money = GetMoney();
16984 if (npc)
16985 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16987 if(money < totalcost)
16989 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16990 data << uint32(ERR_TAXINOTENOUGHMONEY);
16991 GetSession()->SendPacket(&data);
16992 m_taxi.ClearTaxiDestinations();
16993 return false;
16996 //Checks and preparations done, DO FLIGHT
16997 ModifyMoney(-(int32)totalcost);
16998 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
16999 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
17001 // prevent stealth flight
17002 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17004 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17005 data << uint32(ERR_TAXIOK);
17006 GetSession()->SendPacket(&data);
17008 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17010 GetSession()->SendDoFlight(mount_display_id, sourcepath);
17012 return true;
17015 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
17017 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
17018 if(!entry)
17019 return false;
17021 std::vector<uint32> nodes;
17023 nodes.resize(2);
17024 nodes[0] = entry->from;
17025 nodes[1] = entry->to;
17027 return ActivateTaxiPathTo(nodes,NULL,spellid);
17030 void Player::ContinueTaxiFlight()
17032 uint32 sourceNode = m_taxi.GetTaxiSource();
17033 if (!sourceNode)
17034 return;
17036 sLog.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
17038 uint32 mountDisplayId = objmgr.GetTaxiMountDisplayId(sourceNode, GetTeam(),true);
17039 uint32 path = m_taxi.GetCurrentTaxiPath();
17041 // search appropriate start path node
17042 uint32 startNode = 0;
17044 TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
17046 float distPrev = MAP_SIZE*MAP_SIZE;
17047 float distNext =
17048 (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
17049 (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
17050 (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
17052 for(uint32 i = 1; i < nodeList.size(); ++i)
17054 TaxiPathNode const& node = nodeList[i];
17055 TaxiPathNode const& prevNode = nodeList[i-1];
17057 // skip nodes at another map
17058 if(node.mapid != GetMapId())
17059 continue;
17061 distPrev = distNext;
17063 distNext =
17064 (node.x-GetPositionX())*(node.x-GetPositionX())+
17065 (node.y-GetPositionY())*(node.y-GetPositionY())+
17066 (node.z-GetPositionZ())*(node.z-GetPositionZ());
17068 float distNodes =
17069 (node.x-prevNode.x)*(node.x-prevNode.x)+
17070 (node.y-prevNode.y)*(node.y-prevNode.y)+
17071 (node.z-prevNode.z)*(node.z-prevNode.z);
17073 if(distNext + distPrev < distNodes)
17075 startNode = i;
17076 break;
17080 GetSession()->SendDoFlight(mountDisplayId, path, startNode);
17083 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17085 // last check 2.0.10
17086 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17087 data << GetGUID();
17088 data << uint8(0x0); // flags (0x1, 0x2)
17089 time_t curTime = time(NULL);
17090 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17092 if (itr->second->state == PLAYERSPELL_REMOVED)
17093 continue;
17094 uint32 unSpellId = itr->first;
17095 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17096 if (!spellInfo)
17098 ASSERT(spellInfo);
17099 continue;
17102 // Not send cooldown for this spells
17103 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17104 continue;
17106 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17108 data << uint32(unSpellId);
17109 data << uint32(unTimeMs); // in m.secs
17110 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17113 GetSession()->SendPacket(&data);
17116 void Player::InitDataForForm(bool reapplyMods)
17118 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17119 if(ssEntry && ssEntry->attackSpeed)
17121 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17122 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17123 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17125 else
17126 SetRegularAttackTime();
17128 switch(m_form)
17130 case FORM_CAT:
17132 if(getPowerType()!=POWER_ENERGY)
17133 setPowerType(POWER_ENERGY);
17134 break;
17136 case FORM_BEAR:
17137 case FORM_DIREBEAR:
17139 if(getPowerType()!=POWER_RAGE)
17140 setPowerType(POWER_RAGE);
17141 break;
17143 default: // 0, for example
17145 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17146 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17147 setPowerType(Powers(cEntry->powerType));
17148 break;
17152 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17153 if (!reapplyMods)
17154 UpdateEquipSpellsAtFormChange();
17156 UpdateAttackPowerAndDamage();
17157 UpdateAttackPowerAndDamage(true);
17160 void Player::InitDisplayIds()
17162 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
17163 if(!info)
17165 sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
17166 return;
17169 uint8 gender = getGender();
17170 switch(gender)
17172 case GENDER_FEMALE:
17173 SetDisplayId(info->displayId_f );
17174 SetNativeDisplayId(info->displayId_f );
17175 break;
17176 case GENDER_MALE:
17177 SetDisplayId(info->displayId_m );
17178 SetNativeDisplayId(info->displayId_m );
17179 break;
17180 default:
17181 sLog.outError("Invalid gender %u for player",gender);
17182 return;
17186 // Return true is the bought item has a max count to force refresh of window by caller
17187 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot)
17189 // cheating attempt
17190 if (count < 1) count = 1;
17192 if (!isAlive())
17193 return false;
17195 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
17196 if (!pProto)
17198 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17199 return false;
17202 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
17203 if (!pCreature)
17205 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17206 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17207 return false;
17210 VendorItemData const* vItems = pCreature->GetVendorItems();
17211 if(!vItems || vItems->Empty())
17213 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17214 return false;
17217 size_t vendor_slot = vItems->FindItemSlot(item);
17218 if (vendor_slot >= vItems->GetItemCount())
17220 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17221 return false;
17224 VendorItem const* crItem = vItems->m_items[vendor_slot];
17226 // check current item amount if it limited
17227 if (crItem->maxcount != 0)
17229 if (pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17231 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17232 return false;
17236 if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17238 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17239 return false;
17242 if (crItem->ExtendedCost)
17244 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17245 if (!iece)
17247 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17248 return false;
17251 // honor points price
17252 if (GetHonorPoints() < (iece->reqhonorpoints * count))
17254 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17255 return false;
17258 // arena points price
17259 if (GetArenaPoints() < (iece->reqarenapoints * count))
17261 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17262 return false;
17265 // item base price
17266 for (uint8 i = 0; i < 5; ++i)
17268 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17270 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17271 return false;
17275 // check for personal arena rating requirement
17276 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17278 // probably not the proper equip err
17279 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17280 return false;
17284 uint32 price = pProto->BuyPrice * count;
17286 // reputation discount
17287 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17289 if (GetMoney() < price)
17291 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17292 return false;
17295 if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
17297 ItemPosCountVec dest;
17298 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17299 if (msg != EQUIP_ERR_OK)
17301 SendEquipError( msg, NULL, NULL );
17302 return false;
17305 ModifyMoney( -(int32)price );
17306 if (crItem->ExtendedCost) // case for new honor system
17308 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17309 if (iece->reqhonorpoints)
17310 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17311 if (iece->reqarenapoints)
17312 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17313 for (uint8 i = 0; i < 5; ++i)
17315 if (iece->reqitem[i])
17316 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17320 if (Item *it = StoreNewItem( dest, item, true ))
17322 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17324 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17325 data << pCreature->GetGUID();
17326 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17327 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17328 data << (uint32)count;
17329 GetSession()->SendPacket(&data);
17331 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17334 else if (IsEquipmentPos(bag, slot))
17336 if (pProto->BuyCount * count != 1)
17338 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17339 return false;
17342 uint16 dest;
17343 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17344 if (msg != EQUIP_ERR_OK)
17346 SendEquipError( msg, NULL, NULL );
17347 return false;
17350 ModifyMoney( -(int32)price );
17351 if (crItem->ExtendedCost) // case for new honor system
17353 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17354 if (iece->reqhonorpoints)
17355 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17356 if (iece->reqarenapoints)
17357 ModifyArenaPoints( - int32(iece->reqarenapoints));
17358 for (uint8 i = 0; i < 5; ++i)
17360 if(iece->reqitem[i])
17361 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17365 if (Item *it = EquipNewItem( dest, item, true ))
17367 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17369 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17370 data << pCreature->GetGUID();
17371 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17372 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17373 data << (uint32)count;
17374 GetSession()->SendPacket(&data);
17376 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17378 AutoUnequipOffhandIfNeed();
17381 else
17383 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17384 return false;
17387 return crItem->maxcount != 0;
17390 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17392 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17393 // the personal rating of the arena team must match the required limit as well
17394 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17395 uint32 max_personal_rating = 0;
17396 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17398 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17400 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17401 uint32 t_rating = at->GetRating();
17402 p_rating = p_rating<t_rating? p_rating : t_rating;
17403 if(max_personal_rating < p_rating)
17404 max_personal_rating = p_rating;
17407 return max_personal_rating;
17410 void Player::UpdateHomebindTime(uint32 time)
17412 // GMs never get homebind timer online
17413 if (m_InstanceValid || isGameMaster())
17415 if(m_HomebindTimer) // instance valid, but timer not reset
17417 // hide reminder
17418 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17419 data << uint32(0);
17420 data << uint32(0);
17421 GetSession()->SendPacket(&data);
17423 // instance is valid, reset homebind timer
17424 m_HomebindTimer = 0;
17426 else if (m_HomebindTimer > 0)
17428 if (time >= m_HomebindTimer)
17430 // teleport to nearest graveyard
17431 RepopAtGraveyard();
17433 else
17434 m_HomebindTimer -= time;
17436 else
17438 // instance is invalid, start homebind timer
17439 m_HomebindTimer = 60000;
17440 // send message to player
17441 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17442 data << m_HomebindTimer;
17443 data << uint32(1);
17444 GetSession()->SendPacket(&data);
17445 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17449 void Player::UpdatePvP(bool state, bool ovrride)
17451 if(!state || ovrride)
17453 SetPvP(state);
17454 pvpInfo.endTimer = 0;
17456 else
17458 if(pvpInfo.endTimer != 0)
17459 pvpInfo.endTimer = time(NULL);
17460 else
17461 SetPvP(state);
17465 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17467 // init cooldown values
17468 uint32 cat = 0;
17469 int32 rec = -1;
17470 int32 catrec = -1;
17472 // some special item spells without correct cooldown in SpellInfo
17473 // cooldown information stored in item prototype
17474 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17476 if(itemId)
17478 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17480 for(int idx = 0; idx < 5; ++idx)
17482 if(proto->Spells[idx].SpellId == spellInfo->Id)
17484 cat = proto->Spells[idx].SpellCategory;
17485 rec = proto->Spells[idx].SpellCooldown;
17486 catrec = proto->Spells[idx].SpellCategoryCooldown;
17487 break;
17493 // if no cooldown found above then base at DBC data
17494 if(rec < 0 && catrec < 0)
17496 cat = spellInfo->Category;
17497 rec = spellInfo->RecoveryTime;
17498 catrec = spellInfo->CategoryRecoveryTime;
17501 time_t curTime = time(NULL);
17503 time_t catrecTime;
17504 time_t recTime;
17506 // overwrite time for selected category
17507 if(infinityCooldown)
17509 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17510 // but not allow ignore until reset or re-login
17511 catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
17512 recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
17514 else
17516 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17517 // prevent 0 cooldowns set by another way
17518 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17519 rec = GetAttackTime(RANGED_ATTACK);
17521 // Now we have cooldown data (if found any), time to apply mods
17522 if(rec > 0)
17523 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17525 if(catrec > 0)
17526 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17528 // replace negative cooldowns by 0
17529 if (rec < 0) rec = 0;
17530 if (catrec < 0) catrec = 0;
17532 // no cooldown after applying spell mods
17533 if( rec == 0 && catrec == 0)
17534 return;
17536 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17537 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17540 // self spell cooldown
17541 if(recTime > 0)
17542 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17544 // category spells
17545 if (cat && catrec > 0)
17547 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17548 if(i_scstore != sSpellCategoryStore.end())
17550 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17552 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17553 continue;
17555 AddSpellCooldown(*i_scset, itemId, catrecTime);
17561 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17563 SpellCooldown sc;
17564 sc.end = end_time;
17565 sc.itemid = itemid;
17566 m_spellCooldowns[spellid] = sc;
17569 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17571 // start cooldowns at server side, if any
17572 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17574 // Send activate cooldown timer (possible 0) at client side
17575 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17576 data << spellInfo->Id;
17577 data << GetGUID();
17578 SendDirectMessage(&data);
17581 void Player::UpdatePotionCooldown(Spell* spell)
17583 // no potion used i combat or still in combat
17584 if(!m_lastPotionId || isInCombat())
17585 return;
17587 // Call not from spell cast, send cooldown event for item spells if no in combat
17588 if(!spell)
17590 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17591 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17592 for(int idx = 0; idx < 5; ++idx)
17593 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17594 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17595 SendCooldownEvent(spellInfo,m_lastPotionId);
17597 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17598 else
17599 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17601 m_lastPotionId = 0;
17604 //slot to be excluded while counting
17605 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17607 if(!enchantmentcondition)
17608 return true;
17610 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17612 if(!Condition)
17613 return true;
17615 uint8 curcount[4] = {0, 0, 0, 0};
17617 //counting current equipped gem colors
17618 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17620 if(i == slot)
17621 continue;
17622 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17623 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17625 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17627 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17628 if(!enchant_id)
17629 continue;
17631 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17632 if(!enchantEntry)
17633 continue;
17635 uint32 gemid = enchantEntry->GemID;
17636 if(!gemid)
17637 continue;
17639 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17640 if(!gemProto)
17641 continue;
17643 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17644 if(!gemProperty)
17645 continue;
17647 uint8 GemColor = gemProperty->color;
17649 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17651 if(tmpcolormask & GemColor)
17652 ++curcount[b];
17658 bool activate = true;
17660 for(int i = 0; i < 5; ++i)
17662 if(!Condition->Color[i])
17663 continue;
17665 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17667 // if have <CompareColor> use them as count, else use <value> from Condition
17668 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17670 switch(Condition->Comparator[i])
17672 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17673 activate &= (_cur_gem < _cmp_gem) ? true : false;
17674 break;
17675 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17676 activate &= (_cur_gem > _cmp_gem) ? true : false;
17677 break;
17678 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17679 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17680 break;
17684 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");
17686 return activate;
17689 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17691 //cycle all equipped items
17692 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17694 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17695 if(slot == exceptslot)
17696 continue;
17698 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17700 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17701 continue;
17703 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17705 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17706 if(!enchant_id)
17707 continue;
17709 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17710 if(!enchantEntry)
17711 continue;
17713 uint32 condition = enchantEntry->EnchantmentCondition;
17714 if(condition)
17716 //was enchant active with/without item?
17717 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17718 //should it now be?
17719 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17721 // ignore item gem conditions
17722 //if state changed, (dis)apply enchant
17723 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17730 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17731 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17733 //cycle all equipped items
17734 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17736 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17737 if(slot == exceptslot)
17738 continue;
17740 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17742 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17743 continue;
17745 //cycle all (gem)enchants
17746 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17748 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17749 if(!enchant_id) //if no enchant go to next enchant(slot)
17750 continue;
17752 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17753 if(!enchantEntry)
17754 continue;
17756 //only metagems to be (de)activated, so only enchants with condition
17757 uint32 condition = enchantEntry->EnchantmentCondition;
17758 if(condition)
17759 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17764 void Player::SetBattleGroundEntryPoint()
17766 // Taxi path store
17767 if (!m_taxi.empty())
17769 m_bgData.mountSpell = 0;
17770 m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
17771 m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
17773 // On taxi we don't need check for dungeon
17774 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
17775 return;
17777 else
17779 m_bgData.ClearTaxiPath();
17781 // Mount spell id storing
17782 if (IsMounted())
17784 AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED);
17785 if (!auras.empty())
17786 m_bgData.mountSpell = (*auras.begin())->GetId();
17788 else
17789 m_bgData.mountSpell = 0;
17791 // If map is dungeon find linked graveyard
17792 if(GetMap()->IsDungeon())
17794 if (const WorldSafeLocsEntry* entry = objmgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
17796 m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
17797 return;
17799 else
17800 sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
17802 // If new entry point is not BG or arena set it
17803 else if (!GetMap()->IsBattleGroundOrArena())
17805 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
17806 return;
17810 // In error cases use homebind position
17811 m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
17814 void Player::LeaveBattleground(bool teleportToEntryPoint)
17816 if(BattleGround *bg = GetBattleGround())
17818 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17820 // call after remove to be sure that player resurrected for correct cast
17821 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17823 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17825 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
17826 if(IsBeingTeleportedFar())
17828 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
17829 return;
17832 CastSpell(this, 26013, true); // Deserter
17838 bool Player::CanJoinToBattleground() const
17840 // check Deserter debuff
17841 if(GetDummyAura(26013))
17842 return false;
17844 return true;
17847 bool Player::CanReportAfkDueToLimit()
17849 // a player can complain about 15 people per 5 minutes
17850 if(m_bgData.bgAfkReportedCount++ >= 15)
17851 return false;
17853 return true;
17856 ///This player has been blamed to be inactive in a battleground
17857 void Player::ReportedAfkBy(Player* reporter)
17859 BattleGround *bg = GetBattleGround();
17860 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17861 return;
17863 // check if player has 'Idle' or 'Inactive' debuff
17864 if(m_bgData.bgAfkReporter.find(reporter->GetGUIDLow())==m_bgData.bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17866 m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
17867 // 3 players have to complain to apply debuff
17868 if(m_bgData.bgAfkReporter.size() >= 3)
17870 // cast 'Idle' spell
17871 CastSpell(this, 43680, true);
17872 m_bgData.bgAfkReporter.clear();
17877 WorldObject const* Player::GetViewPoint() const
17879 if(uint64 far_sight = GetFarSight())
17881 WorldObject const* viewPoint = ObjectAccessor::GetWorldObject(*this,far_sight);
17882 return viewPoint ? viewPoint : this; // always expected not NULL
17884 else
17885 return this;
17888 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17890 // gamemaster in GM mode see all, including ghosts
17891 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17892 return true;
17894 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17895 if (InBattleGround())
17897 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17898 return false;
17899 return true;
17902 // Live player see live player or dead player with not realized corpse
17903 if(pl->isAlive() || pl->m_deathTimer > 0)
17905 return isAlive() || m_deathTimer > 0;
17908 // Ghost see other friendly ghosts, that's for sure
17909 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17910 return true;
17912 // Dead player see live players near own corpse
17913 if(isAlive())
17915 Corpse *corpse = pl->GetCorpse();
17916 if(corpse)
17918 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17919 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17920 return true;
17924 // and not see any other
17925 return false;
17928 bool Player::IsVisibleGloballyFor( Player* u ) const
17930 if(!u)
17931 return false;
17933 // Always can see self
17934 if (u==this)
17935 return true;
17937 // Visible units, always are visible for all players
17938 if (GetVisibility() == VISIBILITY_ON)
17939 return true;
17941 // GMs are visible for higher gms (or players are visible for gms)
17942 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17943 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17945 // non faction visibility non-breakable for non-GMs
17946 if (GetVisibility() == VISIBILITY_OFF)
17947 return false;
17949 // non-gm stealth/invisibility not hide from global player lists
17950 return true;
17953 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target)
17955 if(HaveAtClient(target))
17957 if(!target->isVisibleForInState(this, viewPoint, true))
17959 target->DestroyForPlayer(this);
17960 m_clientGUIDs.erase(target->GetGUID());
17962 #ifdef MANGOS_DEBUG
17963 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17964 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17965 #endif
17968 else
17970 if(target->isVisibleForInState(this, viewPoint, false))
17972 target->SendUpdateToPlayer(this);
17973 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17974 m_clientGUIDs.insert(target->GetGUID());
17976 #ifdef MANGOS_DEBUG
17977 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17978 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17979 #endif
17981 // target aura duration for caster show only if target exist at caster client
17982 // send data at target visibility change (adding to client)
17983 if(target!=this && target->isType(TYPEMASK_UNIT))
17984 SendAurasForTarget((Unit*)target);
17986 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17987 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17992 template<class T>
17993 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17995 s64.insert(target->GetGUID());
17998 template<>
17999 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
18001 if(!target->IsTransport())
18002 s64.insert(target->GetGUID());
18005 template<class T>
18006 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
18008 if(HaveAtClient(target))
18010 if(!target->isVisibleForInState(this,viewPoint,true))
18012 target->BuildOutOfRangeUpdateBlock(&data);
18013 m_clientGUIDs.erase(target->GetGUID());
18015 #ifdef MANGOS_DEBUG
18016 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18017 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));
18018 #endif
18021 else
18023 if(target->isVisibleForInState(this,viewPoint,false))
18025 visibleNow.insert(target);
18026 target->BuildUpdate(data_updates);
18027 target->BuildCreateUpdateBlockForPlayer(&data, this);
18028 UpdateVisibilityOf_helper(m_clientGUIDs,target);
18030 #ifdef MANGOS_DEBUG
18031 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18032 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));
18033 #endif
18038 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18039 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18040 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18041 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18042 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18044 void Player::InitPrimaryProfessions()
18046 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
18049 void Player::SendComboPoints()
18051 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
18052 if (combotarget)
18054 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
18055 data.append(combotarget->GetPackGUID());
18056 data << uint8(m_comboPoints);
18057 GetSession()->SendPacket(&data);
18061 void Player::AddComboPoints(Unit* target, int8 count)
18063 if(!count)
18064 return;
18066 // without combo points lost (duration checked in aura)
18067 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18069 if(target->GetGUID() == m_comboTarget)
18071 m_comboPoints += count;
18073 else
18075 if(m_comboTarget)
18076 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
18077 target2->RemoveComboPointHolder(GetGUIDLow());
18079 m_comboTarget = target->GetGUID();
18080 m_comboPoints = count;
18082 target->AddComboPointHolder(GetGUIDLow());
18085 if (m_comboPoints > 5) m_comboPoints = 5;
18086 if (m_comboPoints < 0) m_comboPoints = 0;
18088 SendComboPoints();
18091 void Player::ClearComboPoints()
18093 if(!m_comboTarget)
18094 return;
18096 // without combopoints lost (duration checked in aura)
18097 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18099 m_comboPoints = 0;
18101 SendComboPoints();
18103 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18104 target->RemoveComboPointHolder(GetGUIDLow());
18106 m_comboTarget = 0;
18109 void Player::SetGroup(Group *group, int8 subgroup)
18111 if(group == NULL)
18112 m_group.unlink();
18113 else
18115 // never use SetGroup without a subgroup unless you specify NULL for group
18116 assert(subgroup >= 0);
18117 m_group.link(group, this);
18118 m_group.setSubGroup((uint8)subgroup);
18122 void Player::SendInitialPacketsBeforeAddToMap()
18124 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
18125 data << uint32(0); // unknown, may be rest state time or experience
18126 GetSession()->SendPacket(&data);
18128 GetSocial()->SendSocialList();
18130 // Homebind
18131 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
18132 data << m_homebindX << m_homebindY << m_homebindZ;
18133 data << (uint32) m_homebindMapId;
18134 data << (uint32) m_homebindZoneId;
18135 GetSession()->SendPacket(&data);
18137 // SMSG_SET_PROFICIENCY
18138 // SMSG_UPDATE_AURA_DURATION
18140 SendTalentsInfoData(false);
18141 SendInitialSpells();
18143 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
18144 data << uint32(0); // count, for(count) uint32;
18145 GetSession()->SendPacket(&data);
18147 SendInitialActionButtons();
18148 m_reputationMgr.SendInitialReputations();
18149 m_achievementMgr.SendAllAchievementData();
18151 SendEquipmentSetList();
18153 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
18154 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18155 data << (float)0.01666667f; // game speed
18156 data << uint32(0); // added in 3.1.2
18157 GetSession()->SendPacket( &data );
18159 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18160 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || HasAuraType(SPELL_AURA_FLY) || isInFlight())
18161 m_movementInfo.AddMovementFlag(MOVEMENTFLAG_FLYING2);
18163 m_mover = this;
18166 void Player::SendInitialPacketsAfterAddToMap()
18168 // update zone
18169 uint32 newzone, newarea;
18170 GetZoneAndAreaId(newzone,newarea);
18171 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
18173 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18174 data << uint32(0x00000000); // on blizz it increments periodically
18175 GetSession()->SendPacket(&data);
18177 CastSpell(this, 836, true); // LOGINEFFECT
18179 // set some aura effects that send packet to player client after add player to map
18180 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18181 // same auras state lost at far teleport, send it one more time in this case also
18182 static const AuraType auratypes[] =
18184 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18185 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18186 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18188 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18190 Unit::AuraList const& auraList = GetAurasByType(*itr);
18191 if(!auraList.empty())
18192 auraList.front()->ApplyModifier(true,true);
18195 if(HasAuraType(SPELL_AURA_MOD_STUN))
18196 SetMovement(MOVE_ROOT);
18198 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18199 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18201 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
18202 data2.append(GetPackGUID());
18203 data2 << (uint32)2;
18204 SendMessageToSet(&data2,true);
18207 SendAurasForTarget(this);
18208 SendEnchantmentDurations(); // must be after add to map
18209 SendItemDurations(); // must be after add to map
18212 void Player::SendUpdateToOutOfRangeGroupMembers()
18214 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18215 return;
18216 if(Group* group = GetGroup())
18217 group->UpdatePlayerOutOfRange(this);
18219 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18220 m_auraUpdateMask = 0;
18221 if(Pet *pet = GetPet())
18222 pet->ResetAuraUpdateMask();
18225 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18227 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18228 data << uint32(mapid);
18229 data << uint8(reason); // transfer abort reason
18230 switch(reason)
18232 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18233 case TRANSFER_ABORT_DIFFICULTY:
18234 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18235 data << uint8(arg);
18236 break;
18238 GetSession()->SendPacket(&data);
18241 void Player::SendInstanceResetWarning( uint32 mapid, uint32 difficulty, uint32 time )
18243 // type of warning, based on the time remaining until reset
18244 uint32 type;
18245 if(time > 3600)
18246 type = RAID_INSTANCE_WELCOME;
18247 else if(time > 900 && time <= 3600)
18248 type = RAID_INSTANCE_WARNING_HOURS;
18249 else if(time > 300 && time <= 900)
18250 type = RAID_INSTANCE_WARNING_MIN;
18251 else
18252 type = RAID_INSTANCE_WARNING_MIN_SOON;
18254 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
18255 data << uint32(type);
18256 data << uint32(mapid);
18257 data << uint32(difficulty); // difficulty
18258 data << uint32(time);
18259 if(type == RAID_INSTANCE_WELCOME)
18261 data << uint8(0); // is your (1)
18262 data << uint8(0); // is extended (1), ignored if prev field is 0
18264 GetSession()->SendPacket(&data);
18267 void Player::ApplyEquipCooldown( Item * pItem )
18269 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
18271 _Spell const& spellData = pItem->GetProto()->Spells[i];
18273 // no spell
18274 if( !spellData.SpellId )
18275 continue;
18277 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18278 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18279 continue;
18281 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18283 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18284 data << pItem->GetGUID();
18285 data << uint32(spellData.SpellId);
18286 GetSession()->SendPacket(&data);
18290 void Player::resetSpells()
18292 // not need after this call
18293 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18294 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
18296 // make full copy of map (spells removed and marked as deleted at another spell remove
18297 // and we can't use original map for safe iterative with visit each spell at loop end
18298 PlayerSpellMap smap = GetSpellMap();
18300 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18301 removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
18303 learnDefaultSpells();
18304 learnQuestRewardedSpells();
18307 void Player::learnDefaultSpells()
18309 // learn default race/class spells
18310 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18311 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18313 uint32 tspell = *itr;
18314 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18315 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18316 addSpell(tspell,true,true,true,false);
18317 else // but send in normal spell in game learn case
18318 learnSpell(tspell,true);
18322 void Player::learnQuestRewardedSpells(Quest const* quest)
18324 uint32 spell_id = quest->GetRewSpellCast();
18326 // skip quests without rewarded spell
18327 if( !spell_id )
18328 return;
18330 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18331 if(!spellInfo)
18332 return;
18334 // check learned spells state
18335 bool found = false;
18336 for(int i=0; i < 3; ++i)
18338 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18340 found = true;
18341 break;
18345 // skip quests with not teaching spell or already known spell
18346 if(!found)
18347 return;
18349 // prevent learn non first rank unknown profession and second specialization for same profession)
18350 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18351 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18353 // not have first rank learned (unlearned prof?)
18354 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18355 if( !HasSpell(first_spell) )
18356 return;
18358 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18359 if(!learnedInfo)
18360 return;
18362 // specialization
18363 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18365 // search other specialization for same prof
18366 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18368 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18369 continue;
18371 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18372 if(!itrInfo)
18373 return;
18375 // compare only specializations
18376 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18377 continue;
18379 // compare same chain spells
18380 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18381 continue;
18383 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18384 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18385 return;
18390 CastSpell( this, spell_id, true);
18393 void Player::learnQuestRewardedSpells()
18395 // learn spells received from quest completing
18396 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18398 // skip no rewarded quests
18399 if(!itr->second.m_rewarded)
18400 continue;
18402 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18403 if( !quest )
18404 continue;
18406 learnQuestRewardedSpells(quest);
18410 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18412 uint32 raceMask = getRaceMask();
18413 uint32 classMask = getClassMask();
18414 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18416 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18417 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18418 continue;
18419 // Check race if set
18420 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18421 continue;
18422 // Check class if set
18423 if (pAbility->classmask && !(pAbility->classmask & classMask))
18424 continue;
18426 if (sSpellStore.LookupEntry(pAbility->spellId))
18428 // need unlearn spell
18429 if (skill_value < pAbility->req_skill_value)
18430 removeSpell(pAbility->spellId);
18431 // need learn
18432 else if (!IsInWorld())
18433 addSpell(pAbility->spellId,true,true,true,false);
18434 else
18435 learnSpell(pAbility->spellId,true);
18440 void Player::SendAurasForTarget(Unit *target)
18442 if(target->GetVisibleAuras()->empty()) // speedup things
18443 return;
18445 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18446 data.append(target->GetPackGUID());
18448 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18449 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18451 for(uint32 j = 0; j < 3; ++j)
18453 if(Aura *aura = target->GetAura(itr->second, j))
18455 data << uint8(aura->GetAuraSlot());
18456 data << uint32(aura->GetId());
18458 if(aura->GetId())
18460 uint8 auraFlags = aura->GetAuraFlags();
18461 // flags
18462 data << uint8(auraFlags);
18463 // level
18464 data << uint8(aura->GetAuraLevel());
18465 // charges
18466 data << uint8(aura->GetAuraCharges());
18468 if(!(auraFlags & AFLAG_NOT_CASTER))
18470 data << uint8(0); // packed GUID of someone (caster?)
18473 if(auraFlags & AFLAG_DURATION) // include aura duration
18475 data << uint32(aura->GetAuraMaxDuration());
18476 data << uint32(aura->GetAuraDuration());
18479 break;
18484 GetSession()->SendPacket(&data);
18487 void Player::SetDailyQuestStatus( uint32 quest_id )
18489 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18491 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18493 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18494 m_lastDailyQuestTime = time(NULL); // last daily quest time
18495 m_DailyQuestChanged = true;
18496 break;
18501 void Player::ResetDailyQuestStatus()
18503 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18504 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18506 // DB data deleted in caller
18507 m_DailyQuestChanged = false;
18508 m_lastDailyQuestTime = 0;
18511 BattleGround* Player::GetBattleGround() const
18513 if(GetBattleGroundId()==0)
18514 return NULL;
18516 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
18519 bool Player::InArena() const
18521 BattleGround *bg = GetBattleGround();
18522 if(!bg || !bg->isArena())
18523 return false;
18525 return true;
18528 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18530 // get a template bg instead of running one
18531 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18532 if(!bg)
18533 return false;
18535 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18536 return false;
18538 return true;
18541 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18543 //returned to hardcoded version of this function, because there is no way to code it dynamic
18544 uint32 level = getLevel();
18545 if( bgTypeId == BATTLEGROUND_AV )
18546 level--;
18548 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18549 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18551 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18552 return QUEUE_ID_MAX_LEVEL_80;
18554 return BGQueueIdBasedOnLevel(queue_id);
18557 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18559 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18560 if(!vendor_faction || !vendor_faction->faction)
18561 return 1.0f;
18563 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18564 if(rank <= REP_NEUTRAL)
18565 return 1.0f;
18567 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18570 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18572 uint32 racemask = getRaceMask();
18573 uint32 classmask = getClassMask();
18575 SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
18576 if (bounds.first==bounds.second)
18577 return true;
18579 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
18581 // skip wrong race skills
18582 if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18583 continue;
18585 // skip wrong class skills
18586 if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18587 continue;
18589 return true;
18592 return false;
18595 bool Player::HasQuestForGO(int32 GOId) const
18597 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18599 uint32 questid = GetQuestSlotQuestId(i);
18600 if ( questid == 0 )
18601 continue;
18603 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18604 if(qs_itr == mQuestStatus.end())
18605 continue;
18607 QuestStatusData const& qs = qs_itr->second;
18609 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18611 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18612 if(!qinfo)
18613 continue;
18615 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18616 continue;
18618 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
18620 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18621 continue;
18623 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18624 return true;
18628 return false;
18631 void Player::UpdateForQuestWorldObjects()
18633 if(m_clientGUIDs.empty())
18634 return;
18636 UpdateData udata;
18637 WorldPacket packet;
18638 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18640 if(IS_GAMEOBJECT_GUID(*itr))
18642 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18643 if(obj)
18644 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18646 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
18648 Creature *obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
18649 if(!obj)
18650 continue;
18652 // check if this unit requires quest specific flags
18653 if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
18654 continue;
18656 SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(obj->GetEntry());
18657 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
18659 if(itr->second.questStart || itr->second.questEnd)
18661 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
18662 break;
18667 udata.BuildPacket(&packet);
18668 GetSession()->SendPacket(&packet);
18671 void Player::SummonIfPossible(bool agree)
18673 if(!agree)
18675 m_summon_expire = 0;
18676 return;
18679 // expire and auto declined
18680 if(m_summon_expire < time(NULL))
18681 return;
18683 // stop taxi flight at summon
18684 if(isInFlight())
18686 GetMotionMaster()->MovementExpired();
18687 m_taxi.ClearTaxiDestinations();
18690 // drop flag at summon
18691 // 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
18692 if(BattleGround *bg = GetBattleGround())
18693 bg->EventPlayerDroppedFlag(this);
18695 m_summon_expire = 0;
18697 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
18699 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18702 void Player::RemoveItemDurations( Item *item )
18704 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18706 if(*itr==item)
18708 m_itemDuration.erase(itr);
18709 break;
18714 void Player::AddItemDurations( Item *item )
18716 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18718 m_itemDuration.push_back(item);
18719 item->SendTimeUpdate(this);
18723 void Player::AutoUnequipOffhandIfNeed()
18725 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18726 if(!offItem)
18727 return;
18729 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18730 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18731 return;
18733 ItemPosCountVec off_dest;
18734 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18735 if( off_msg == EQUIP_ERR_OK )
18737 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18738 StoreItem( off_dest, offItem, true );
18740 else
18742 MailItemsInfo mi;
18743 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18744 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18745 CharacterDatabase.BeginTransaction();
18746 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18747 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18748 CharacterDatabase.CommitTransaction();
18750 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18751 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18755 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18757 if(spellInfo->EquippedItemClass < 0)
18758 return true;
18760 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18761 // for optimize check 2 used cases only
18762 switch(spellInfo->EquippedItemClass)
18764 case ITEM_CLASS_WEAPON:
18766 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18767 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18768 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18769 return true;
18770 break;
18772 case ITEM_CLASS_ARMOR:
18774 // tabard not have dependent spells
18775 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18776 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18777 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18778 return true;
18780 // shields can be equipped to offhand slot
18781 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18782 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18783 return true;
18785 // ranged slot can have some armor subclasses
18786 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18787 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18788 return true;
18790 break;
18792 default:
18793 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18794 break;
18797 return false;
18800 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18802 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18803 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18804 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18805 return true;
18807 // Check no reagent use mask
18808 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18809 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18810 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18811 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18812 return true;
18814 return false;
18817 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18819 AuraMap& auras = GetAuras();
18820 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
18822 Aura* aura = itr->second;
18824 // skip passive (passive item dependent spells work in another way) and not self applied auras
18825 SpellEntry const* spellInfo = aura->GetSpellProto();
18826 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18828 ++itr;
18829 continue;
18832 // skip if not item dependent or have alternative item
18833 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18835 ++itr;
18836 continue;
18839 // no alt item, remove aura, restart check
18840 RemoveAurasDueToSpell(aura->GetId());
18841 itr = auras.begin();
18844 // currently casted spells can be dependent from item
18845 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
18846 if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
18847 if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
18848 InterruptSpell(CurrentSpellTypes(i));
18851 uint32 Player::GetResurrectionSpellId()
18853 // search priceless resurrection possibilities
18854 uint32 prio = 0;
18855 uint32 spell_id = 0;
18856 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18857 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18859 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18860 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18862 switch((*itr)->GetId())
18864 case 20707: spell_id = 3026; break; // rank 1
18865 case 20762: spell_id = 20758; break; // rank 2
18866 case 20763: spell_id = 20759; break; // rank 3
18867 case 20764: spell_id = 20760; break; // rank 4
18868 case 20765: spell_id = 20761; break; // rank 5
18869 case 27239: spell_id = 27240; break; // rank 6
18870 case 47883: spell_id = 47882; break; // rank 7
18871 default:
18872 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
18873 continue;
18876 prio = 3;
18878 // Twisting Nether // prio: 2 (max)
18879 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18881 prio = 2;
18882 spell_id = 23700;
18886 // Reincarnation (passive spell) // prio: 1
18887 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18888 spell_id = 21169;
18890 return spell_id;
18893 // Used in triggers for check "Only to targets that grant experience or honor" req
18894 bool Player::isHonorOrXPTarget(Unit* pVictim)
18896 uint32 v_level = pVictim->getLevel();
18897 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18899 // Victim level less gray level
18900 if(v_level<=k_grey)
18901 return false;
18903 if(pVictim->GetTypeId() == TYPEID_UNIT)
18905 if (((Creature*)pVictim)->isTotem() ||
18906 ((Creature*)pVictim)->isPet() ||
18907 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18908 return false;
18910 return true;
18913 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18915 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18917 // prepare data for near group iteration (PvP and !PvP cases)
18918 uint32 xp = 0;
18919 bool honored_kill = false;
18921 if(Group *pGroup = GetGroup())
18923 uint32 count = 0;
18924 uint32 sum_level = 0;
18925 Player* member_with_max_level = NULL;
18926 Player* not_gray_member_with_max_level = NULL;
18928 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18930 if(member_with_max_level)
18932 /// not get Xp in PvP or no not gray players in group
18933 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18935 /// skip in check PvP case (for speed, not used)
18936 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18937 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18938 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18940 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18942 Player* pGroupGuy = itr->getSource();
18943 if(!pGroupGuy)
18944 continue;
18946 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18947 continue; // member (alive or dead) or his corpse at req. distance
18949 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18950 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18951 honored_kill = true;
18953 // xp and reputation only in !PvP case
18954 if(!PvP)
18956 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18958 // if is in dungeon then all receive full reputation at kill
18959 // rewarded any alive/dead/near_corpse group member
18960 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18962 // XP updated only for alive group member
18963 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18964 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18966 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18968 pGroupGuy->GiveXP(itr_xp, pVictim);
18969 if(Pet* pet = pGroupGuy->GetPet())
18970 pet->GivePetXP(itr_xp/2);
18973 // quest objectives updated only for alive group member or dead but with not released body
18974 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18976 // normal creature (not pet/etc) can be only in !PvP case
18977 if(pVictim->GetTypeId()==TYPEID_UNIT)
18978 pGroupGuy->KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
18984 else // if (!pGroup)
18986 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18988 // honor can be in PvP and !PvP (racial leader) cases
18989 if(RewardHonor(pVictim,1))
18990 honored_kill = true;
18992 // xp and reputation only in !PvP case
18993 if(!PvP)
18995 RewardReputation(pVictim,1);
18996 GiveXP(xp, pVictim);
18998 if(Pet* pet = GetPet())
18999 pet->GivePetXP(xp);
19001 // normal creature (not pet/etc) can be only in !PvP case
19002 if(pVictim->GetTypeId()==TYPEID_UNIT)
19003 KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19006 return xp || honored_kill;
19009 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
19011 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
19013 // prepare data for near group iteration
19014 if(Group *pGroup = GetGroup())
19016 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19018 Player* pGroupGuy = itr->getSource();
19019 if(!pGroupGuy)
19020 continue;
19022 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
19023 continue; // member (alive or dead) or his corpse at req. distance
19025 // quest objectives updated only for alive group member or dead but with not released body
19026 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19027 pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
19030 else // if (!pGroup)
19031 KilledMonsterCredit(creature_id, creature_guid);
19034 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
19036 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
19037 return true;
19039 if (isAlive())
19040 return false;
19042 Corpse* corpse = GetCorpse();
19043 if (!corpse)
19044 return false;
19046 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
19049 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
19051 Item* item = GetWeaponForAttack(attType,true);
19053 // unarmed only with base attack
19054 if(attType != BASE_ATTACK && !item)
19055 return 0;
19057 // weapon skill or (unarmed for base attack)
19058 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
19059 return GetBaseSkillValue(skill);
19062 void Player::ResurectUsingRequestData()
19064 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
19065 if(IS_PLAYER_GUID(m_resurrectGUID))
19066 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
19068 //we cannot resurrect player when we triggered far teleport
19069 //player will be resurrected upon teleportation
19070 if(IsBeingTeleportedFar())
19072 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
19073 return;
19076 ResurrectPlayer(0.0f,false);
19078 if(GetMaxHealth() > m_resurrectHealth)
19079 SetHealth( m_resurrectHealth );
19080 else
19081 SetHealth( GetMaxHealth() );
19083 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
19084 SetPower(POWER_MANA, m_resurrectMana );
19085 else
19086 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
19088 SetPower(POWER_RAGE, 0 );
19090 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
19092 SpawnCorpseBones();
19095 void Player::SetClientControl(Unit* target, uint8 allowMove)
19097 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
19098 data.append(target->GetPackGUID());
19099 data << uint8(allowMove);
19100 GetSession()->SendPacket(&data);
19103 void Player::UpdateZoneDependentAuras( uint32 newZone )
19105 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19106 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
19107 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19108 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
19109 if( !HasAura(itr->second->spellId,0) )
19110 CastSpell(this,itr->second->spellId,true);
19113 void Player::UpdateAreaDependentAuras( uint32 newArea )
19115 // remove auras from spells with area limitations
19116 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
19118 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19119 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
19120 RemoveAura(iter);
19121 else
19122 ++iter;
19125 // some auras applied at subzone enter
19126 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
19127 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19128 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
19129 if( !HasAura(itr->second->spellId,0) )
19130 CastSpell(this,itr->second->spellId,true);
19133 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
19135 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19136 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19138 return copseReclaimDelay[0];
19141 time_t now = time(NULL);
19142 // 0..2 full period
19143 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
19144 return copseReclaimDelay[count];
19147 void Player::UpdateCorpseReclaimDelay()
19149 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
19151 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19152 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19153 return;
19155 time_t now = time(NULL);
19156 if(now < m_deathExpireTime)
19158 // full and partly periods 1..3
19159 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
19160 if(count < MAX_DEATH_COUNT)
19161 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19162 else
19163 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19165 else
19166 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19169 void Player::SendCorpseReclaimDelay(bool load)
19171 Corpse* corpse = GetCorpse();
19172 if(!corpse)
19173 return;
19175 uint32 delay;
19176 if(load)
19178 if(corpse->GetGhostTime() > m_deathExpireTime)
19179 return;
19181 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19183 uint32 count;
19184 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19185 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19187 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19188 if(count>=MAX_DEATH_COUNT)
19189 count = MAX_DEATH_COUNT-1;
19191 else
19192 count=0;
19194 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19196 time_t now = time(NULL);
19197 if(now >= expected_time)
19198 return;
19200 delay = expected_time-now;
19202 else
19203 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19205 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19206 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19207 data << uint32(delay*IN_MILISECONDS);
19208 GetSession()->SendPacket( &data );
19211 Player* Player::GetNextRandomRaidMember(float radius)
19213 Group *pGroup = GetGroup();
19214 if(!pGroup)
19215 return NULL;
19217 std::vector<Player*> nearMembers;
19218 nearMembers.reserve(pGroup->GetMembersCount());
19220 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19222 Player* Target = itr->getSource();
19224 // IsHostileTo check duel and controlled by enemy
19225 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19226 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19227 nearMembers.push_back(Target);
19230 if (nearMembers.empty())
19231 return NULL;
19233 uint32 randTarget = urand(0,nearMembers.size()-1);
19234 return nearMembers[randTarget];
19237 PartyResult Player::CanUninviteFromGroup() const
19239 const Group* grp = GetGroup();
19240 if(!grp)
19241 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19243 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19244 return PARTY_RESULT_YOU_NOT_LEADER;
19246 if(InBattleGround())
19247 return PARTY_RESULT_INVITE_RESTRICTED;
19249 return PARTY_RESULT_OK;
19252 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
19254 //we must move references from m_group to m_originalGroup
19255 SetOriginalGroup(GetGroup(), GetSubGroup());
19257 m_group.unlink();
19258 m_group.link(group, this);
19259 m_group.setSubGroup((uint8)subgroup);
19262 void Player::RemoveFromBattleGroundRaid()
19264 //remove existing reference
19265 m_group.unlink();
19266 if( Group* group = GetOriginalGroup() )
19268 m_group.link(group, this);
19269 m_group.setSubGroup(GetOriginalSubGroup());
19271 SetOriginalGroup(NULL);
19274 void Player::SetOriginalGroup(Group *group, int8 subgroup)
19276 if( group == NULL )
19277 m_originalGroup.unlink();
19278 else
19280 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19281 assert(subgroup >= 0);
19282 m_originalGroup.link(group, this);
19283 m_originalGroup.setSubGroup((uint8)subgroup);
19287 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19289 LiquidData liquid_status;
19290 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
19291 if (!res)
19293 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
19294 // Small hack for enable breath in WMO
19295 if (IsInWater())
19296 m_MirrorTimerFlags|=UNDERWATER_INWATER;
19297 return;
19300 // All liquids type - check under water position
19301 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
19303 if ( res & LIQUID_MAP_UNDER_WATER)
19304 m_MirrorTimerFlags |= UNDERWATER_INWATER;
19305 else
19306 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
19309 // Allow travel in dark water on taxi or transport
19310 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
19311 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
19312 else
19313 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
19315 // in lava check, anywhere in lava level
19316 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
19318 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19319 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
19320 else
19321 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
19323 // in slime check, anywhere in slime level
19324 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
19326 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19327 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
19328 else
19329 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
19333 void Player::SetCanParry( bool value )
19335 if(m_canParry==value)
19336 return;
19338 m_canParry = value;
19339 UpdateParryPercentage();
19342 void Player::SetCanBlock( bool value )
19344 if(m_canBlock==value)
19345 return;
19347 m_canBlock = value;
19348 UpdateBlockPercentage();
19351 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19353 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19354 if(itr->pos == pos)
19355 return true;
19357 return false;
19360 bool Player::CanUseBattleGroundObject()
19362 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19363 // maybe gameobject code should handle that ForceReaction usage
19364 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19365 return ( //InBattleGround() && // in battleground - not need, check in other cases
19366 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19367 //player cannot use object when he is invulnerable (immune)
19368 !isTotalImmune() && // not totally immune
19369 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19370 !HasStealthAura() && // not stealthed
19371 !HasInvisibilityAura() && // not invisible
19372 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19373 isAlive() // live player
19377 bool Player::CanCaptureTowerPoint()
19379 return ( !HasStealthAura() && // not stealthed
19380 !HasInvisibilityAura() && // not invisible
19381 isAlive() // live player
19385 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19387 uint32 level = getLevel();
19389 if(level > GT_MAX_LEVEL)
19390 level = GT_MAX_LEVEL; // max level in this dbc
19392 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19393 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19394 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19396 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19397 return 0;
19399 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19401 if(!bsc) // shouldn't happen
19402 return 0xFFFFFFFF;
19404 float cost = 0;
19406 if(hairstyle != newhairstyle)
19407 cost += bsc->cost; // full price
19409 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19410 cost += bsc->cost * 0.5f; // +1/2 of price
19412 if(facialhair != newfacialhair)
19413 cost += bsc->cost * 0.75f; // +3/4 of price
19415 return uint32(cost);
19418 void Player::InitGlyphsForLevel()
19420 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19421 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19422 if(gs->Order)
19423 SetGlyphSlot(gs->Order - 1, gs->Id);
19425 uint32 level = getLevel();
19426 uint32 value = 0;
19428 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19429 if(level >= 15)
19430 value |= (0x01 | 0x02);
19431 if(level >= 30)
19432 value |= 0x08;
19433 if(level >= 50)
19434 value |= 0x04;
19435 if(level >= 70)
19436 value |= 0x10;
19437 if(level >= 80)
19438 value |= 0x20;
19440 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19443 void Player::EnterVehicle(Vehicle *vehicle)
19445 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19446 if(!ve)
19447 return;
19449 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19450 if(!veSeat)
19451 return;
19453 vehicle->SetCharmerGUID(GetGUID());
19454 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19455 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
19456 vehicle->setFaction(getFaction());
19458 SetCharm(vehicle); // charm
19459 SetFarSightGUID(vehicle->GetGUID()); // set view
19461 SetClientControl(vehicle, 1); // redirect controls to vehicle
19462 SetMover(vehicle);
19464 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19465 GetSession()->SendPacket(&data);
19467 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19468 data.append(GetPackGUID());
19469 data << uint32(0); // counter?
19470 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19471 data << uint16(0); // special flags
19472 data << uint32(getMSTime()); // time
19473 data << vehicle->GetPositionX(); // x
19474 data << vehicle->GetPositionY(); // y
19475 data << vehicle->GetPositionZ(); // z
19476 data << vehicle->GetOrientation(); // o
19477 // transport part, TODO: load/calculate seat offsets
19478 data << uint64(vehicle->GetGUID()); // transport guid
19479 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19480 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19481 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19482 data << float(0); // transport orientation
19483 data << uint32(getMSTime()); // transport time
19484 data << uint8(0); // seat
19485 // end of transport part
19486 data << uint32(0); // fall time
19487 GetSession()->SendPacket(&data);
19489 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
19490 data << uint64(vehicle->GetGUID());
19491 data << uint16(0);
19492 data << uint32(0);
19493 data << uint32(0x00000101);
19495 for(uint32 i = 0; i < 10; ++i)
19496 data << uint16(0) << uint8(0) << uint8(i+8);
19498 data << uint8(0);
19499 data << uint8(0);
19500 GetSession()->SendPacket(&data);
19503 void Player::ExitVehicle(Vehicle *vehicle)
19505 vehicle->SetCharmerGUID(0);
19506 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19507 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
19508 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19510 SetCharm(NULL);
19511 SetFarSightGUID(0);
19513 SetClientControl(vehicle, 0);
19514 SetMover(NULL);
19516 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19517 data.append(GetPackGUID());
19518 data << uint32(0); // counter?
19519 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19520 data << uint16(0x40); // special flags
19521 data << uint32(getMSTime()); // time
19522 data << vehicle->GetPositionX(); // x
19523 data << vehicle->GetPositionY(); // y
19524 data << vehicle->GetPositionZ(); // z
19525 data << vehicle->GetOrientation(); // o
19526 data << uint32(0); // fall time
19527 GetSession()->SendPacket(&data);
19529 RemovePetActionBar();
19531 // maybe called at dummy aura remove?
19532 // CastSpell(this, 45472, true); // Parachute
19535 bool Player::isTotalImmune()
19537 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19539 uint32 immuneMask = 0;
19540 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19542 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19543 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19544 return true;
19546 return false;
19549 bool Player::HasTitle(uint32 bitIndex)
19551 if (bitIndex > MAX_TITLE_INDEX)
19552 return false;
19554 uint32 fieldIndexOffset = bitIndex / 32;
19555 uint32 flag = 1 << (bitIndex % 32);
19556 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19559 void Player::SetTitle(CharTitlesEntry const* title, bool lost)
19561 uint32 fieldIndexOffset = title->bit_index / 32;
19562 uint32 flag = 1 << (title->bit_index % 32);
19564 if(lost)
19566 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
19567 return;
19569 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19571 else
19573 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
19574 return;
19576 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19579 WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
19580 data << uint32(title->bit_index);
19581 data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
19582 GetSession()->SendPacket(&data);
19585 void Player::ConvertRune(uint8 index, uint8 newType)
19587 SetCurrentRune(index, newType);
19589 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19590 data << uint8(index);
19591 data << uint8(newType);
19592 GetSession()->SendPacket(&data);
19595 void Player::ResyncRunes(uint8 count)
19597 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19598 for(uint32 i = 0; i < count; ++i)
19600 data << uint8(GetCurrentRune(i)); // rune type
19601 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19603 GetSession()->SendPacket(&data);
19606 void Player::AddRunePower(uint8 index)
19608 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19609 data << uint32(1 << index); // mask (0x00-0x3F probably)
19610 GetSession()->SendPacket(&data);
19613 void Player::InitRunes()
19615 if(getClass() != CLASS_DEATH_KNIGHT)
19616 return;
19618 m_runes = new Runes;
19620 m_runes->runeState = 0;
19622 for(uint32 i = 0; i < MAX_RUNES; ++i)
19624 SetBaseRune(i, i / 2); // init base types
19625 SetCurrentRune(i, i / 2); // init current types
19626 SetRuneCooldown(i, 0); // reset cooldowns
19627 m_runes->SetRuneState(i);
19630 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19631 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19634 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19636 Loot loot;
19637 loot.FillLoot (loot_id,store,this,true);
19639 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19640 for(uint32 i = 0; i < max_slot; ++i)
19642 LootItem* lootItem = loot.LootItemInSlot(i,this);
19644 ItemPosCountVec dest;
19645 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19646 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19647 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19648 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19649 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19650 if(msg != EQUIP_ERR_OK)
19652 SendEquipError( msg, NULL, NULL );
19653 continue;
19656 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19657 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19661 uint32 Player::CalculateTalentsPoints() const
19663 uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
19665 if(getClass() != CLASS_DEATH_KNIGHT)
19666 return uint32(base_talent * sWorld.getRate(RATE_TALENT));
19668 uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
19669 talentPointsForLevel += m_questRewardTalentCount;
19671 if(talentPointsForLevel > base_talent)
19672 talentPointsForLevel = base_talent;
19674 return uint32(talentPointsForLevel * sWorld.getRate(RATE_TALENT));
19677 bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
19679 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
19680 uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
19681 return v_map != 571 || HasSpell(54197); // Cold Weather Flying
19684 struct DoPlayerLearnSpell
19686 DoPlayerLearnSpell(Player& _player) : player(_player) {}
19687 void operator() (uint32 spell_id) { player.learnSpell(spell_id,false); }
19688 Player& player;
19691 void Player::learnSpellHighRank(uint32 spellid)
19693 learnSpell(spellid,false);
19695 DoPlayerLearnSpell worker(*this);
19696 spellmgr.doForHighRanks(spellid,worker);
19699 void Player::_LoadSkills()
19701 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19703 // reset skill modifiers and set correct unlearn flags
19704 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
19706 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19708 // set correct unlearn bit
19709 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19710 if(!id) continue;
19712 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19713 if(!pSkill) continue;
19715 // enable unlearn button for primary professions only
19716 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19717 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19718 else
19719 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19721 // set fixed skill ranges
19722 switch(GetSkillRangeType(pSkill,false))
19724 case SKILL_RANGE_LANGUAGE: // 300..300
19725 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19726 break;
19727 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19728 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19729 break;
19730 default:
19731 break;
19734 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19735 learnSkillRewardedSpells(id, vskill);
19738 // special settings
19739 if(getClass()==CLASS_DEATH_KNIGHT)
19741 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19742 if(base_level < 1)
19743 base_level = 1;
19744 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19745 if(base_skill < 1)
19746 base_skill = 1; // skill mast be known and then > 0 in any case
19748 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19749 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19750 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19751 SetSkill(SKILL_AXES, base_skill,base_skill);
19752 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19753 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19754 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19755 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19756 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19757 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19758 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19759 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19760 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19761 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19762 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19763 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19767 uint32 Player::GetPhaseMaskForSpawn() const
19769 uint32 phase = PHASEMASK_NORMAL;
19770 if(!isGameMaster())
19771 phase = GetPhaseMask();
19772 else
19774 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19775 if(!phases.empty())
19776 phase = phases.front()->GetMiscValue();
19779 // some aura phases include 1 normal map in addition to phase itself
19780 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19781 return n_phase;
19783 return PHASEMASK_NORMAL;
19786 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19788 ItemPrototype const* pProto = pItem->GetProto();
19790 // proto based limitations
19791 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19792 return res;
19794 // check unique-equipped on gems
19795 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19797 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19798 if(!enchant_id)
19799 continue;
19800 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19801 if(!enchantEntry)
19802 continue;
19804 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19805 if(!pGem)
19806 continue;
19808 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19809 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19810 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19812 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19813 return res;
19816 return EQUIP_ERR_OK;
19819 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19821 // check unique-equipped on item
19822 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19824 // there is an equip limit on this item
19825 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19826 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19829 // check unique-equipped limit
19830 if (itemProto->ItemLimitCategory)
19832 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19833 if(!limitEntry)
19834 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19836 if(limit_count > limitEntry->maxCount)
19837 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19839 // there is an equip limit on this item
19840 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19841 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19844 return EQUIP_ERR_OK;
19847 void Player::HandleFall(MovementInfo const& movementInfo)
19849 // calculate total z distance of the fall
19850 float z_diff = m_lastFallZ - movementInfo.z;
19851 sLog.outDebug("zDiff = %f", z_diff);
19853 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19854 // 14.57 can be calculated by resolving damageperc formula below to 0
19855 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19856 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19857 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19859 //Safe fall, fall height reduction
19860 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19862 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19864 if(damageperc >0 )
19866 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19868 float height = movementInfo.z;
19869 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19871 if (damage > 0)
19873 //Prevent fall damage from being more than the player maximum health
19874 if (damage > GetMaxHealth())
19875 damage = GetMaxHealth();
19877 // Gust of Wind
19878 if (GetDummyAura(43621))
19879 damage = GetMaxHealth()/2;
19881 uint32 original_health = GetHealth();
19882 uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
19884 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
19885 if (isAlive() && final_damage < original_health)
19886 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19889 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19890 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);
19895 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19897 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
19900 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
19902 uint32 CurTalentPoints = GetFreeTalentPoints();
19904 if(CurTalentPoints == 0)
19905 return;
19907 if (talentRank >= MAX_TALENT_RANK)
19908 return;
19910 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
19912 if(!talentInfo)
19913 return;
19915 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
19917 if(!talentTabInfo)
19918 return;
19920 // prevent learn talent for different class (cheating)
19921 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
19922 return;
19924 // find current max talent rank
19925 int32 curtalent_maxrank = 0;
19926 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19928 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19930 curtalent_maxrank = k + 1;
19931 break;
19935 // we already have same or higher talent rank learned
19936 if(curtalent_maxrank >= (talentRank + 1))
19937 return;
19939 // check if we have enough talent points
19940 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19941 return;
19943 // Check if it requires another talent
19944 if (talentInfo->DependsOn > 0)
19946 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19948 bool hasEnoughRank = false;
19949 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19951 if (depTalentInfo->RankID[i] != 0)
19952 if (HasSpell(depTalentInfo->RankID[i]))
19953 hasEnoughRank = true;
19955 if (!hasEnoughRank)
19956 return;
19960 // Find out how many points we have in this field
19961 uint32 spentPoints = 0;
19963 uint32 tTab = talentInfo->TalentTab;
19964 if (talentInfo->Row > 0)
19966 unsigned int numRows = sTalentStore.GetNumRows();
19967 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19969 // Someday, someone needs to revamp
19970 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19971 if (tmpTalent) // the way talents are tracked
19973 if (tmpTalent->TalentTab == tTab)
19975 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19977 if (tmpTalent->RankID[j] != 0)
19979 if (HasSpell(tmpTalent->RankID[j]))
19981 spentPoints += j + 1;
19990 // not have required min points spent in talent tree
19991 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
19992 return;
19994 // spell not set in talent.dbc
19995 uint32 spellid = talentInfo->RankID[talentRank];
19996 if( spellid == 0 )
19998 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19999 return;
20002 // already known
20003 if(HasSpell(spellid))
20004 return;
20006 // learn! (other talent ranks will unlearned at learning)
20007 learnSpell(spellid, false);
20008 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20010 // update free talent points
20011 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20014 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
20016 Pet *pet = GetPet();
20018 if(!pet)
20019 return;
20021 if(petGuid != pet->GetGUID())
20022 return;
20024 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
20026 if(CurTalentPoints == 0)
20027 return;
20029 if (talentRank >= MAX_PET_TALENT_RANK)
20030 return;
20032 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
20034 if(!talentInfo)
20035 return;
20037 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
20039 if(!talentTabInfo)
20040 return;
20042 CreatureInfo const *ci = pet->GetCreatureInfo();
20044 if(!ci)
20045 return;
20047 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20049 if(!pet_family)
20050 return;
20052 if(pet_family->petTalentType < 0) // not hunter pet
20053 return;
20055 // prevent learn talent for different family (cheating)
20056 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20057 return;
20059 // find current max talent rank
20060 int32 curtalent_maxrank = 0;
20061 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20063 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20065 curtalent_maxrank = k + 1;
20066 break;
20070 // we already have same or higher talent rank learned
20071 if(curtalent_maxrank >= (talentRank + 1))
20072 return;
20074 // check if we have enough talent points
20075 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20076 return;
20078 // Check if it requires another talent
20079 if (talentInfo->DependsOn > 0)
20081 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20083 bool hasEnoughRank = false;
20084 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20086 if (depTalentInfo->RankID[i] != 0)
20087 if (pet->HasSpell(depTalentInfo->RankID[i]))
20088 hasEnoughRank = true;
20090 if (!hasEnoughRank)
20091 return;
20095 // Find out how many points we have in this field
20096 uint32 spentPoints = 0;
20098 uint32 tTab = talentInfo->TalentTab;
20099 if (talentInfo->Row > 0)
20101 unsigned int numRows = sTalentStore.GetNumRows();
20102 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20104 // Someday, someone needs to revamp
20105 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20106 if (tmpTalent) // the way talents are tracked
20108 if (tmpTalent->TalentTab == tTab)
20110 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20112 if (tmpTalent->RankID[j] != 0)
20114 if (pet->HasSpell(tmpTalent->RankID[j]))
20116 spentPoints += j + 1;
20125 // not have required min points spent in talent tree
20126 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
20127 return;
20129 // spell not set in talent.dbc
20130 uint32 spellid = talentInfo->RankID[talentRank];
20131 if( spellid == 0 )
20133 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20134 return;
20137 // already known
20138 if(pet->HasSpell(spellid))
20139 return;
20141 // learn! (other talent ranks will unlearned at learning)
20142 pet->learnSpell(spellid);
20143 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20145 // update free talent points
20146 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20149 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
20151 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
20153 if(apply)
20154 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
20155 else
20156 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
20160 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
20162 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
20163 SetFallInformation(minfo.fallTime, minfo.z);
20166 void Player::UnsummonPetTemporaryIfAny()
20168 Pet* pet = GetPet();
20169 if(!pet)
20170 return;
20172 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
20174 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
20175 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
20178 RemovePet(pet, PET_SAVE_AS_CURRENT);
20181 void Player::ResummonPetTemporaryUnSummonedIfAny()
20183 if(!m_temporaryUnsummonedPetNumber)
20184 return;
20186 // not resummon in not appropriate state
20187 if(IsPetNeedBeTemporaryUnsummoned())
20188 return;
20190 if(GetPetGUID())
20191 return;
20193 Pet* NewPet = new Pet;
20194 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
20195 delete NewPet;
20197 m_temporaryUnsummonedPetNumber = 0;
20200 bool Player::canSeeSpellClickOn(Creature const *c) const
20202 if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
20203 return false;
20205 SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(c->GetEntry());
20206 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
20207 if(itr->second.IsFitToRequirements(this))
20208 return true;
20210 return false;
20213 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
20215 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
20216 *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
20217 *data << uint8(m_activeSpec); // talent group index (0 or 1)
20219 if(m_specsCount)
20221 // loop through all specs (only 1 for now)
20222 for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
20224 uint8 talentIdCount = 0;
20225 size_t pos = data->wpos();
20226 *data << uint8(talentIdCount); // [PH], talentIdCount
20228 // find class talent tabs (all players have 3 talent tabs)
20229 uint32 const* talentTabIds = GetTalentTabPages(getClass());
20231 for(uint32 i = 0; i < 3; ++i)
20233 uint32 talentTabId = talentTabIds[i];
20235 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20237 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20238 if(!talentInfo)
20239 continue;
20241 // skip another tab talents
20242 if(talentInfo->TalentTab != talentTabId)
20243 continue;
20245 // find max talent rank
20246 int32 curtalent_maxrank = -1;
20247 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20249 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20251 curtalent_maxrank = k;
20252 break;
20256 // not learned talent
20257 if(curtalent_maxrank < 0)
20258 continue;
20260 *data << uint32(talentInfo->TalentID); // Talent.dbc
20261 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20263 ++talentIdCount;
20267 data->put<uint8>(pos, talentIdCount); // put real count
20269 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
20271 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
20272 *data << uint16(GetGlyph(i)); // GlyphProperties.dbc
20277 void Player::BuildPetTalentsInfoData(WorldPacket *data)
20279 uint32 unspentTalentPoints = 0;
20280 size_t pointsPos = data->wpos();
20281 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
20283 uint8 talentIdCount = 0;
20284 size_t countPos = data->wpos();
20285 *data << uint8(talentIdCount); // [PH], talentIdCount
20287 Pet *pet = GetPet();
20288 if(!pet)
20289 return;
20291 unspentTalentPoints = pet->GetFreeTalentPoints();
20293 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
20295 CreatureInfo const *ci = pet->GetCreatureInfo();
20296 if(!ci)
20297 return;
20299 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20300 if(!pet_family || pet_family->petTalentType < 0)
20301 return;
20303 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
20305 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
20306 if(!talentTabInfo)
20307 continue;
20309 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20310 continue;
20312 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20314 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20315 if(!talentInfo)
20316 continue;
20318 // skip another tab talents
20319 if(talentInfo->TalentTab != talentTabId)
20320 continue;
20322 // find max talent rank
20323 int32 curtalent_maxrank = -1;
20324 for(int32 k = 4; k > -1; --k)
20326 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20328 curtalent_maxrank = k;
20329 break;
20333 // not learned talent
20334 if(curtalent_maxrank < 0)
20335 continue;
20337 *data << uint32(talentInfo->TalentID); // Talent.dbc
20338 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20340 ++talentIdCount;
20343 data->put<uint8>(countPos, talentIdCount); // put real count
20345 break;
20349 void Player::SendTalentsInfoData(bool pet)
20351 WorldPacket data(SMSG_TALENTS_INFO, 50);
20352 data << uint8(pet ? 1 : 0);
20353 if(pet)
20354 BuildPetTalentsInfoData(&data);
20355 else
20356 BuildPlayerTalentsInfoData(&data);
20357 GetSession()->SendPacket(&data);
20360 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
20362 uint32 slotUsedMask = 0;
20363 size_t slotUsedMaskPos = data->wpos();
20364 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
20366 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20368 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
20370 if(!item)
20371 continue;
20373 slotUsedMask |= (1 << i);
20375 *data << uint32(item->GetEntry()); // item entry
20377 uint16 enchantmentMask = 0;
20378 size_t enchantmentMaskPos = data->wpos();
20379 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
20381 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
20383 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
20385 if(!enchId)
20386 continue;
20388 enchantmentMask |= (1 << j);
20390 *data << uint16(enchId); // enchantmentId?
20393 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
20395 *data << uint16(0); // ?
20396 *data << uint8(0); // PGUID!
20397 *data << uint32(0); // seed?
20400 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
20403 void Player::SendEquipmentSetList()
20405 uint32 count = 0;
20406 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
20407 size_t count_pos = data.wpos();
20408 data << uint32(count); // count placeholder
20409 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20411 if(itr->second.state==EQUIPMENT_SET_DELETED)
20412 continue;
20413 data.appendPackGUID(itr->second.Guid);
20414 data << uint32(itr->first);
20415 data << itr->second.Name;
20416 data << itr->second.IconName;
20417 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20418 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
20420 ++count; // client have limit but it checked at loading and set
20422 data.put<uint32>(count_pos, count);
20423 GetSession()->SendPacket(&data);
20426 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
20428 if(eqset.Guid != 0)
20430 bool found = false;
20432 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20434 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
20436 found = true;
20437 break;
20441 if(!found) // something wrong...
20443 sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
20444 return;
20448 EquipmentSet& eqslot = m_EquipmentSets[index];
20450 EquipmentSetUpdateState old_state = eqslot.state;
20452 eqslot = eqset;
20454 if(eqset.Guid == 0)
20456 eqslot.Guid = objmgr.GenerateEquipmentSetGuid();
20458 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
20459 data << uint32(index);
20460 data.appendPackGUID(eqslot.Guid);
20461 GetSession()->SendPacket(&data);
20464 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
20467 void Player::_SaveEquipmentSets()
20469 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
20471 uint32 index = itr->first;
20472 EquipmentSet& eqset = itr->second;
20473 switch(eqset.state)
20475 case EQUIPMENT_SET_UNCHANGED:
20476 ++itr;
20477 break; // nothing do
20478 case EQUIPMENT_SET_CHANGED:
20479 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'",
20480 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],
20481 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);
20482 eqset.state = EQUIPMENT_SET_UNCHANGED;
20483 ++itr;
20484 break;
20485 case EQUIPMENT_SET_NEW:
20486 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')",
20487 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],
20488 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]);
20489 eqset.state = EQUIPMENT_SET_UNCHANGED;
20490 ++itr;
20491 break;
20492 case EQUIPMENT_SET_DELETED:
20493 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
20494 m_EquipmentSets.erase(itr++);
20495 break;
20500 void Player::_SaveBGData()
20502 CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
20503 if (m_bgData.bgInstanceID)
20505 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
20506 CharacterDatabase.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
20507 GetGUIDLow(), m_bgData.bgInstanceID, m_bgData.bgTeam, m_bgData.joinPos.coord_x, m_bgData.joinPos.coord_y, m_bgData.joinPos.coord_z,
20508 m_bgData.joinPos.orientation, m_bgData.joinPos.mapid, m_bgData.taxiPath[0], m_bgData.taxiPath[1], m_bgData.mountSpell);
20512 void Player::DeleteEquipmentSet(uint64 setGuid)
20514 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20516 if(itr->second.Guid == setGuid)
20518 if(itr->second.state == EQUIPMENT_SET_NEW)
20519 m_EquipmentSets.erase(itr);
20520 else
20521 itr->second.state = EQUIPMENT_SET_DELETED;
20522 break;
20527 void Player::ActivateSpec(uint32 specNum)
20529 if(GetActiveSpec() == specNum)
20530 return;
20532 resetTalents(true);
20535 void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
20537 m_atLoginFlags &= ~f;
20539 if(in_db_also)
20540 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
20543 void Player::SendClearCooldown( uint32 spell_id, Unit* target )
20545 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
20546 data << uint32(spell_id);
20547 data << uint64(target->GetGUID());
20548 SendDirectMessage(&data);
20551 void Player::BuildTeleportAckMsg( WorldPacket *data, float x, float y, float z, float ang ) const
20553 data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
20554 data->append(GetPackGUID());
20555 *data << uint32(0); // this value increments every time
20556 *data << uint32(m_movementInfo.GetMovementFlags()); // movement flags
20557 *data << uint16(0); // 2.3.0
20558 *data << uint32(getMSTime()); // time
20559 *data << x;
20560 *data << y;
20561 *data << z;
20562 *data << ang;
20563 *data << uint32(0);
20566 bool Player::HasMovementFlag( MovementFlags f ) const
20568 return m_movementInfo.HasMovementFlag(f);
20571 void Player::SetFarSightGUID( uint64 guid )
20573 if(GetFarSight()==guid)
20574 return;
20576 SetUInt64Value(PLAYER_FARSIGHT, guid);
20578 // need triggering load grids around new view point
20579 ObjectAccessor::UpdateVisibilityForPlayer(this);