Don't use singleton to access static functions.
[getmangos.git] / src / game / Player.cpp
blob6590cd1c2524134d6a391c1b240f2da5d6a23091
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 "BattleGroundAV.h"
55 #include "BattleGroundMgr.h"
56 #include "ArenaTeam.h"
57 #include "Chat.h"
58 #include "Database/DatabaseImpl.h"
59 #include "Spell.h"
60 #include "SocialMgr.h"
61 #include "AchievementMgr.h"
63 #include <cmath>
65 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
67 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
68 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
69 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
71 #define SKILL_VALUE(x) PAIR32_LOPART(x)
72 #define SKILL_MAX(x) PAIR32_HIPART(x)
73 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
75 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
76 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
77 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
79 enum CharacterFlags
81 CHARACTER_FLAG_NONE = 0x00000000,
82 CHARACTER_FLAG_UNK1 = 0x00000001,
83 CHARACTER_FLAG_UNK2 = 0x00000002,
84 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
85 CHARACTER_FLAG_UNK4 = 0x00000008,
86 CHARACTER_FLAG_UNK5 = 0x00000010,
87 CHARACTER_FLAG_UNK6 = 0x00000020,
88 CHARACTER_FLAG_UNK7 = 0x00000040,
89 CHARACTER_FLAG_UNK8 = 0x00000080,
90 CHARACTER_FLAG_UNK9 = 0x00000100,
91 CHARACTER_FLAG_UNK10 = 0x00000200,
92 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
93 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
94 CHARACTER_FLAG_UNK13 = 0x00001000,
95 CHARACTER_FLAG_GHOST = 0x00002000,
96 CHARACTER_FLAG_RENAME = 0x00004000,
97 CHARACTER_FLAG_UNK16 = 0x00008000,
98 CHARACTER_FLAG_UNK17 = 0x00010000,
99 CHARACTER_FLAG_UNK18 = 0x00020000,
100 CHARACTER_FLAG_UNK19 = 0x00040000,
101 CHARACTER_FLAG_UNK20 = 0x00080000,
102 CHARACTER_FLAG_UNK21 = 0x00100000,
103 CHARACTER_FLAG_UNK22 = 0x00200000,
104 CHARACTER_FLAG_UNK23 = 0x00400000,
105 CHARACTER_FLAG_UNK24 = 0x00800000,
106 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
107 CHARACTER_FLAG_DECLINED = 0x02000000,
108 CHARACTER_FLAG_UNK27 = 0x04000000,
109 CHARACTER_FLAG_UNK28 = 0x08000000,
110 CHARACTER_FLAG_UNK29 = 0x10000000,
111 CHARACTER_FLAG_UNK30 = 0x20000000,
112 CHARACTER_FLAG_UNK31 = 0x40000000,
113 CHARACTER_FLAG_UNK32 = 0x80000000
116 enum CharacterCustomizeFlags
118 CHAR_CUSTOMIZE_FLAG_NONE = 0x00000000,
119 CHAR_CUSTOMIZE_FLAG_CUSTOMIZE = 0x00000001, // name, gender, etc...
120 CHAR_CUSTOMIZE_FLAG_FACTION = 0x00010000, // name, gender, faction, etc...
121 CHAR_CUSTOMIZE_FLAG_RACE = 0x00100000 // name, gender, race, etc...
124 // corpse reclaim times
125 #define DEATH_EXPIRE_STEP (5*MINUTE)
126 #define MAX_DEATH_COUNT 3
128 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
130 //== PlayerTaxi ================================================
132 PlayerTaxi::PlayerTaxi()
134 // Taxi nodes
135 memset(m_taximask, 0, sizeof(m_taximask));
138 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
140 // class specific initial known nodes
141 switch(chrClass)
143 case CLASS_DEATH_KNIGHT:
145 for(int i = 0; i < TaxiMaskSize; ++i)
146 m_taximask[i] |= sOldContinentsNodesMask[i];
147 break;
151 // race specific initial known nodes: capital and taxi hub masks
152 switch(race)
154 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
155 case RACE_ORC: SetTaximaskNode(23); break; // Orc
156 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
157 case RACE_NIGHTELF: SetTaximaskNode(26);
158 SetTaximaskNode(27); break; // Night Elf
159 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
160 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
161 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
162 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
163 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
164 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
167 // new continent starting masks (It will be accessible only at new map)
168 switch(Player::TeamForRace(race))
170 case ALLIANCE: SetTaximaskNode(100); break;
171 case HORDE: SetTaximaskNode(99); break;
173 // level dependent taxi hubs
174 if(level>=68)
175 SetTaximaskNode(213); //Shattered Sun Staging Area
178 void PlayerTaxi::LoadTaxiMask(const char* data)
180 Tokens tokens = StrSplit(data, " ");
182 int index;
183 Tokens::iterator iter;
184 for (iter = tokens.begin(), index = 0;
185 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
187 // load and set bits only for existed taxi nodes
188 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
192 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
194 if(all)
196 for (uint8 i=0; i<TaxiMaskSize; ++i)
197 data << uint32(sTaxiNodesMask[i]); // all existed nodes
199 else
201 for (uint8 i=0; i<TaxiMaskSize; ++i)
202 data << uint32(m_taximask[i]); // known nodes
206 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
208 ClearTaxiDestinations();
210 Tokens tokens = StrSplit(values," ");
212 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
214 uint32 node = uint32(atol(iter->c_str()));
215 AddTaxiDestination(node);
218 if(m_TaxiDestinations.empty())
219 return true;
221 // Check integrity
222 if(m_TaxiDestinations.size() < 2)
223 return false;
225 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
227 uint32 cost;
228 uint32 path;
229 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
230 if(!path)
231 return false;
234 // can't load taxi path without mount set (quest taxi path?)
235 if(!objmgr.GetTaxiMountDisplayId(GetTaxiSource(),team,true))
236 return false;
238 return true;
241 std::string PlayerTaxi::SaveTaxiDestinationsToString()
243 if(m_TaxiDestinations.empty())
244 return "";
246 std::ostringstream ss;
248 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
249 ss << m_TaxiDestinations[i] << " ";
251 return ss.str();
254 uint32 PlayerTaxi::GetCurrentTaxiPath() const
256 if(m_TaxiDestinations.size() < 2)
257 return 0;
259 uint32 path;
260 uint32 cost;
262 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
264 return path;
267 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
269 ss << "'";
270 for(int i = 0; i < TaxiMaskSize; ++i)
271 ss << taxi.m_taximask[i] << " ";
272 ss << "'";
273 return ss;
276 //== Player ====================================================
278 UpdateMask Player::updateVisualBits;
280 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
282 m_transport = 0;
284 m_speakTime = 0;
285 m_speakCount = 0;
287 m_objectType |= TYPEMASK_PLAYER;
288 m_objectTypeId = TYPEID_PLAYER;
290 m_valuesCount = PLAYER_END;
292 m_session = session;
294 m_divider = 0;
296 m_ExtraFlags = 0;
297 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
298 SetAcceptTicket(true);
300 // players always accept
301 if(GetSession()->GetSecurity() == SEC_PLAYER)
302 SetAcceptWhispers(true);
304 m_curSelection = 0;
305 m_lootGuid = 0;
307 m_comboTarget = 0;
308 m_comboPoints = 0;
310 m_usedTalentCount = 0;
311 m_questRewardTalentCount = 0;
313 m_regenTimer = 0;
314 m_weaponChangeTimer = 0;
316 m_zoneUpdateId = 0;
317 m_zoneUpdateTimer = 0;
319 m_areaUpdateId = 0;
321 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
323 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
324 // this must help in case next save after mass player load after server startup
325 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
327 clearResurrectRequestData();
329 m_SpellModRemoveCount = 0;
331 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
333 m_social = NULL;
335 // group is initialized in the reference constructor
336 SetGroupInvite(NULL);
337 m_groupUpdateMask = 0;
338 m_auraUpdateMask = 0;
340 duel = NULL;
342 m_GuildIdInvited = 0;
343 m_ArenaTeamIdInvited = 0;
345 m_atLoginFlags = AT_LOGIN_NONE;
347 mSemaphoreTeleport_Near = false;
348 mSemaphoreTeleport_Far = false;
350 m_DelayedOperations = 0;
351 m_bCanDelayTeleport = false;
352 m_bHasDelayedTeleport = false;
353 m_teleport_options = 0;
355 pTrader = 0;
356 ClearTrade();
358 m_cinematic = 0;
360 PlayerTalkClass = new PlayerMenu( GetSession() );
361 m_currentBuybackSlot = BUYBACK_SLOT_START;
363 m_DailyQuestChanged = false;
364 m_lastDailyQuestTime = 0;
366 for (int i=0; i<MAX_TIMERS; ++i)
367 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
369 m_MirrorTimerFlags = UNDERWATER_NONE;
370 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
371 m_isInWater = false;
372 m_drunkTimer = 0;
373 m_drunk = 0;
374 m_restTime = 0;
375 m_deathTimer = 0;
376 m_deathExpireTime = 0;
378 m_swingErrorMsg = 0;
380 m_DetectInvTimer = 1*IN_MILISECONDS;
382 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
384 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
385 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
388 m_logintime = time(NULL);
389 m_Last_tick = m_logintime;
390 m_WeaponProficiency = 0;
391 m_ArmorProficiency = 0;
392 m_canParry = false;
393 m_canBlock = false;
394 m_canDualWield = false;
395 m_canTitanGrip = false;
396 m_ammoDPS = 0.0f;
398 m_temporaryUnsummonedPetNumber = 0;
399 //cache for UNIT_CREATED_BY_SPELL to allow
400 //returning reagents for temporarily removed pets
401 //when dying/logging out
402 m_oldpetspell = 0;
404 ////////////////////Rest System/////////////////////
405 time_inn_enter=0;
406 inn_pos_mapid=0;
407 inn_pos_x=0;
408 inn_pos_y=0;
409 inn_pos_z=0;
410 m_rest_bonus=0;
411 rest_type=REST_TYPE_NO;
412 ////////////////////Rest System/////////////////////
414 m_mailsLoaded = false;
415 m_mailsUpdated = false;
416 unReadMails = 0;
417 m_nextMailDelivereTime = 0;
419 m_resetTalentsCost = 0;
420 m_resetTalentsTime = 0;
421 m_itemUpdateQueueBlocked = false;
423 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
424 m_forced_speed_changes[i] = 0;
426 m_stableSlots = 0;
428 /////////////////// Instance System /////////////////////
430 m_HomebindTimer = 0;
431 m_InstanceValid = true;
432 m_dungeonDifficulty = DUNGEON_DIFFICULTY_NORMAL;
433 m_raidDifficulty = RAID_DIFFICULTY_10MAN_NORMAL;
435 m_lastPotionId = 0;
437 m_activeSpec = 0;
438 m_specsCount = 1;
440 for (int i = 0; i < BASEMOD_END; ++i)
442 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
443 m_auraBaseMod[i][PCT_MOD] = 1.0f;
446 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
447 m_baseRatingValue[i] = 0;
449 m_baseSpellPower = 0;
450 m_baseFeralAP = 0;
451 m_baseManaRegen = 0;
452 m_armorPenetrationPct = 0.0f;
454 // Honor System
455 m_lastHonorUpdateTime = time(NULL);
457 // Player summoning
458 m_summon_expire = 0;
459 m_summon_mapid = 0;
460 m_summon_x = 0.0f;
461 m_summon_y = 0.0f;
462 m_summon_z = 0.0f;
464 m_mover = this;
466 m_miniPet = 0;
467 m_contestedPvPTimer = 0;
469 m_declinedname = NULL;
470 m_runes = NULL;
472 m_lastFallTime = 0;
473 m_lastFallZ = 0;
476 Player::~Player ()
478 CleanupsBeforeDelete();
480 // it must be unloaded already in PlayerLogout and accessed only for loggined player
481 //m_social = NULL;
483 // Note: buy back item already deleted from DB when player was saved
484 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
486 if(m_items[i])
487 delete m_items[i];
489 CleanupChannels();
491 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
492 delete itr->second;
494 //all mailed items should be deleted, also all mail should be deallocated
495 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
496 delete *itr;
498 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
499 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
501 delete PlayerTalkClass;
503 if (m_transport)
505 m_transport->RemovePassenger(this);
508 for(size_t x = 0; x < ItemSetEff.size(); x++)
509 if(ItemSetEff[x])
510 delete ItemSetEff[x];
512 // clean up player-instance binds, may unload some instance saves
513 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
514 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
515 itr->second.save->RemovePlayer(this);
517 delete m_declinedname;
518 delete m_runes;
521 void Player::CleanupsBeforeDelete()
523 if(m_uint32Values) // only for fully created Object
525 TradeCancel(false);
526 DuelComplete(DUEL_INTERUPTED);
528 Unit::CleanupsBeforeDelete();
531 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 )
533 //FIXME: outfitId not used in player creating
535 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
537 m_name = name;
539 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
540 if(!info)
542 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
543 return false;
546 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
547 m_items[i] = NULL;
549 SetLocationMapId(info->mapId);
550 Relocate(info->positionX,info->positionY,info->positionZ);
552 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
553 if(!cEntry)
555 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
556 return false;
559 SetMap(MapManager::Instance().CreateMap(info->mapId, this));
561 uint8 powertype = cEntry->powerType;
563 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
564 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
566 setFactionForRace(race);
568 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
570 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
571 InitDisplayIds();
572 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
573 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
574 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
575 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
576 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
578 // -1 is default value
579 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
581 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
582 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
583 SetByteValue(PLAYER_BYTES_3, 0, gender);
585 SetUInt32Value( PLAYER_GUILDID, 0 );
586 SetUInt32Value( PLAYER_GUILDRANK, 0 );
587 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
589 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
590 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
591 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 0 ); // 0=disabled
592 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
593 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
594 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
595 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
596 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
598 // set starting level
599 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
600 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
601 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
603 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
605 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
606 if(gm_level > start_level)
607 start_level = gm_level;
610 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
612 InitRunes();
614 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
615 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
616 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
618 // Played time
619 m_Last_tick = time(NULL);
620 m_Played_time[PLAYED_TIME_TOTAL] = 0;
621 m_Played_time[PLAYED_TIME_LEVEL] = 0;
623 // base stats and related field values
624 InitStatsForLevel();
625 InitTaxiNodesForLevel();
626 InitGlyphsForLevel();
627 InitTalentForLevel();
628 InitPrimaryProfessions(); // to max set before any spell added
630 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
631 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
632 SetHealth(GetMaxHealth());
633 if (getPowerType()==POWER_MANA)
635 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
636 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
639 if(getPowerType() == POWER_RUNIC_POWER)
641 SetPower(POWER_RUNE, 8);
642 SetMaxPower(POWER_RUNE, 8);
643 SetPower(POWER_RUNIC_POWER, 0);
644 SetMaxPower(POWER_RUNIC_POWER, 1000);
647 // original spells
648 learnDefaultSpells();
650 // original action bar
651 for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
652 addActionButton(action_itr->button,action_itr->action,action_itr->type);
654 // original items
655 CharStartOutfitEntry const* oEntry = NULL;
656 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
658 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
660 if(entry->RaceClassGender == RaceClassGender)
662 oEntry = entry;
663 break;
668 if(oEntry)
670 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
672 if(oEntry->ItemId[j] <= 0)
673 continue;
675 uint32 item_id = oEntry->ItemId[j];
677 // Hack for not existed item id in dbc 3.0.3
678 if(item_id==40582)
679 continue;
681 ItemPrototype const* iProto = ObjectMgr::GetItemPrototype(item_id);
682 if(!iProto)
684 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
685 continue;
688 // BuyCount by default
689 uint32 count = iProto->BuyCount;
691 // special amount for foor/drink
692 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
694 switch(iProto->Spells[0].SpellCategory)
696 case 11: // food
697 count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4;
698 break;
699 case 59: // drink
700 count = 2;
701 break;
703 if(iProto->Stackable < count)
704 count = iProto->Stackable;
707 StoreNewItemInBestSlots(item_id, count);
711 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
712 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
714 // bags and main-hand weapon must equipped at this moment
715 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
716 // or ammo not equipped in special bag
717 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
719 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
721 uint16 eDest;
722 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
723 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
724 if( msg == EQUIP_ERR_OK )
726 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
727 EquipItem( eDest, pItem, true);
729 // move other items to more appropriate slots (ammo not equipped in special bag)
730 else
732 ItemPosCountVec sDest;
733 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
734 if( msg == EQUIP_ERR_OK )
736 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
737 pItem = StoreItem( sDest, pItem, true);
740 // if this is ammo then use it
741 msg = CanUseAmmo( pItem->GetEntry() );
742 if( msg == EQUIP_ERR_OK )
743 SetAmmo( pItem->GetEntry() );
747 // all item positions resolved
749 return true;
752 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
754 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
756 // attempt equip by one
757 while(titem_amount > 0)
759 uint16 eDest;
760 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
761 if( msg != EQUIP_ERR_OK )
762 break;
764 EquipNewItem( eDest, titem_id, true);
765 AutoUnequipOffhandIfNeed();
766 --titem_amount;
769 if(titem_amount == 0)
770 return true; // equipped
772 // attempt store
773 ItemPosCountVec sDest;
774 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
775 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
776 if( msg == EQUIP_ERR_OK )
778 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
779 return true; // stored
782 // item can't be added
783 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
784 return false;
787 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
789 if (int(MaxValue) == DISABLED_MIRROR_TIMER)
791 if (int(CurrentValue) != DISABLED_MIRROR_TIMER)
792 StopMirrorTimer(Type);
793 return;
795 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
796 data << (uint32)Type;
797 data << CurrentValue;
798 data << MaxValue;
799 data << Regen;
800 data << (uint8)0;
801 data << (uint32)0; // spell id
802 GetSession()->SendPacket( &data );
805 void Player::StopMirrorTimer(MirrorTimerType Type)
807 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
808 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
809 data << (uint32)Type;
810 GetSession()->SendPacket( &data );
813 uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
815 if(!isAlive() || isGameMaster())
816 return 0;
818 // Absorb, resist some environmental damage type
819 uint32 absorb = 0;
820 uint32 resist = 0;
821 if (type == DAMAGE_LAVA)
822 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
823 else if (type == DAMAGE_SLIME)
824 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
826 damage-=absorb+resist;
828 DealDamageMods(this,damage,&absorb);
830 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
831 data << uint64(GetGUID());
832 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
833 data << uint32(damage);
834 data << uint32(absorb);
835 data << uint32(resist);
836 SendMessageToSet(&data, true);
838 uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
840 if(!isAlive())
842 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
844 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
845 DurabilityLossAll(0.10f,false);
846 // durability lost message
847 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
848 GetSession()->SendPacket(&data2);
851 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
854 return final_damage;
857 int32 Player::getMaxTimer(MirrorTimerType timer)
859 switch (timer)
861 case FATIGUE_TIMER:
862 if (GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_TIMERBAR_FATIGUE_GMLEVEL))
863 return DISABLED_MIRROR_TIMER;
864 return sWorld.getConfig(CONFIG_TIMERBAR_FATIGUE_MAX)*IN_MILISECONDS;
865 case BREATH_TIMER:
867 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) ||
868 GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_TIMERBAR_BREATH_GMLEVEL))
869 return DISABLED_MIRROR_TIMER;
870 int32 UnderWaterTime = sWorld.getConfig(CONFIG_TIMERBAR_BREATH_MAX)*IN_MILISECONDS;
871 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
872 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
873 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
874 return UnderWaterTime;
876 case FIRE_TIMER:
878 if (!isAlive() || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_TIMERBAR_FIRE_GMLEVEL))
879 return DISABLED_MIRROR_TIMER;
880 return sWorld.getConfig(CONFIG_TIMERBAR_FIRE_MAX)*IN_MILISECONDS;
882 default:
883 return 0;
885 return 0;
888 void Player::UpdateMirrorTimers()
890 // Desync flags for update on next HandleDrowning
891 if (m_MirrorTimerFlags)
892 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
895 void Player::HandleDrowning(uint32 time_diff)
897 if (!m_MirrorTimerFlags)
898 return;
900 // In water
901 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
903 // Breath timer not activated - activate it
904 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
906 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
907 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
909 else // If activated - do tick
911 m_MirrorTimer[BREATH_TIMER]-=time_diff;
912 // Timer limit - need deal damage
913 if (m_MirrorTimer[BREATH_TIMER] < 0)
915 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
916 // Calculate and deal damage
917 // TODO: Check this formula
918 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
919 EnvironmentalDamage(DAMAGE_DROWNING, damage);
921 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
922 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
925 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
927 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
928 // Need breath regen
929 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
930 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
931 StopMirrorTimer(BREATH_TIMER);
932 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
933 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
936 // In dark water
937 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
939 // Fatigue timer not activated - activate it
940 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
942 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
943 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
945 else
947 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
948 // Timer limit - need deal damage or teleport ghost to graveyard
949 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
951 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
952 if (isAlive()) // Calculate and deal damage
954 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
955 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
957 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
958 RepopAtGraveyard();
960 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
961 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
964 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
966 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
967 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
968 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
969 StopMirrorTimer(FATIGUE_TIMER);
970 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
971 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
974 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
976 // Breath timer not activated - activate it
977 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
978 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
979 else
981 m_MirrorTimer[FIRE_TIMER]-=time_diff;
982 if (m_MirrorTimer[FIRE_TIMER] < 0)
984 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
985 // Calculate and deal damage
986 // TODO: Check this formula
987 uint32 damage = urand(600, 700);
988 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
989 EnvironmentalDamage(DAMAGE_LAVA, damage);
990 else
991 EnvironmentalDamage(DAMAGE_SLIME, damage);
995 else
996 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
998 // Recheck timers flag
999 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1000 for (int i = 0; i< MAX_TIMERS; ++i)
1001 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1003 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1004 break;
1006 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1009 ///The player sobers by 256 every 10 seconds
1010 void Player::HandleSobering()
1012 m_drunkTimer = 0;
1014 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1015 SetDrunkValue(drunk);
1018 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1020 if(value >= 23000)
1021 return DRUNKEN_SMASHED;
1022 if(value >= 12800)
1023 return DRUNKEN_DRUNK;
1024 if(value & 0xFFFE)
1025 return DRUNKEN_TIPSY;
1026 return DRUNKEN_SOBER;
1029 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1031 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1033 m_drunk = newDrunkenValue;
1034 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1036 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1038 // special drunk invisibility detection
1039 if(newDrunkenState >= DRUNKEN_DRUNK)
1040 m_detectInvisibilityMask |= (1<<6);
1041 else
1042 m_detectInvisibilityMask &= ~(1<<6);
1044 if(newDrunkenState == oldDrunkenState)
1045 return;
1047 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1048 data << uint64(GetGUID());
1049 data << uint32(newDrunkenState);
1050 data << uint32(itemId);
1052 SendMessageToSet(&data, true);
1055 void Player::Update( uint32 p_time )
1057 if(!IsInWorld())
1058 return;
1060 // undelivered mail
1061 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1063 SendNewMail();
1064 ++unReadMails;
1066 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1067 m_nextMailDelivereTime = 0;
1070 //used to implement delayed far teleports
1071 SetCanDelayTeleport(true);
1072 Unit::Update( p_time );
1073 SetCanDelayTeleport(false);
1075 // update player only attacks
1076 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1078 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1081 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1083 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1086 time_t now = time (NULL);
1088 UpdatePvPFlag(now);
1090 UpdateContestedPvP(p_time);
1092 UpdateDuelFlag(now);
1094 CheckDuelDistance(now);
1096 UpdateAfkReport(now);
1098 // Update items that have just a limited lifetime
1099 if (now>m_Last_tick)
1100 UpdateItemDuration(uint32(now- m_Last_tick));
1102 if (!m_timedquests.empty())
1104 std::set<uint32>::iterator iter = m_timedquests.begin();
1105 while (iter != m_timedquests.end())
1107 QuestStatusData& q_status = mQuestStatus[*iter];
1108 if( q_status.m_timer <= p_time )
1110 uint32 quest_id = *iter;
1111 ++iter; // current iter will be removed in FailQuest
1112 FailQuest(quest_id);
1114 else
1116 q_status.m_timer -= p_time;
1117 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1118 ++iter;
1123 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1125 Unit *pVictim = getVictim();
1126 if (pVictim && !IsNonMeleeSpellCasted(false))
1128 // default combat reach 10
1129 // TODO add weapon,skill check
1131 float pldistance = ATTACK_DISTANCE;
1133 if (isAttackReady(BASE_ATTACK))
1135 if(!IsWithinDistInMap(pVictim, pldistance))
1137 setAttackTimer(BASE_ATTACK,100);
1138 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1140 SendAttackSwingNotInRange();
1141 m_swingErrorMsg = 1;
1144 //120 degrees of radiant range
1145 else if( !HasInArc( 2*M_PI/3, pVictim ))
1147 setAttackTimer(BASE_ATTACK,100);
1148 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1150 SendAttackSwingBadFacingAttack();
1151 m_swingErrorMsg = 2;
1154 else
1156 m_swingErrorMsg = 0; // reset swing error state
1158 // prevent base and off attack in same time, delay attack at 0.2 sec
1159 if(haveOffhandWeapon())
1161 uint32 off_att = getAttackTimer(OFF_ATTACK);
1162 if(off_att < ATTACK_DISPLAY_DELAY)
1163 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1165 AttackerStateUpdate(pVictim, BASE_ATTACK);
1166 resetAttackTimer(BASE_ATTACK);
1170 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1172 if(!IsWithinDistInMap(pVictim, pldistance))
1174 setAttackTimer(OFF_ATTACK,100);
1176 else if( !HasInArc( 2*M_PI/3, pVictim ))
1178 setAttackTimer(OFF_ATTACK,100);
1180 else
1182 // prevent base and off attack in same time, delay attack at 0.2 sec
1183 uint32 base_att = getAttackTimer(BASE_ATTACK);
1184 if(base_att < ATTACK_DISPLAY_DELAY)
1185 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1186 // do attack
1187 AttackerStateUpdate(pVictim, OFF_ATTACK);
1188 resetAttackTimer(OFF_ATTACK);
1192 Unit *owner = pVictim->GetOwner();
1193 Unit *u = owner ? owner : pVictim;
1194 if(u->IsPvP() && (!duel || duel->opponent != u))
1196 UpdatePvP(true);
1197 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1202 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1204 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1206 int time_inn = time(NULL)-GetTimeInnEnter();
1207 if (time_inn >= 10) //freeze update
1209 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1210 //speed collect rest bonus (section/in hour)
1211 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1212 UpdateInnerTime(time(NULL));
1217 if (m_regenTimer)
1219 if(p_time >= m_regenTimer)
1220 m_regenTimer = 0;
1221 else
1222 m_regenTimer -= p_time;
1225 if (m_weaponChangeTimer > 0)
1227 if(p_time >= m_weaponChangeTimer)
1228 m_weaponChangeTimer = 0;
1229 else
1230 m_weaponChangeTimer -= p_time;
1233 if (m_zoneUpdateTimer > 0)
1235 if(p_time >= m_zoneUpdateTimer)
1237 uint32 newzone, newarea;
1238 GetZoneAndAreaId(newzone,newarea);
1240 if( m_zoneUpdateId != newzone )
1241 UpdateZone(newzone,newarea); // also update area
1242 else
1244 // use area updates as well
1245 // needed for free far all arenas for example
1246 if( m_areaUpdateId != newarea )
1247 UpdateArea(newarea);
1249 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1252 else
1253 m_zoneUpdateTimer -= p_time;
1256 if (isAlive())
1258 // if no longer casting, set regen power as soon as it is up.
1259 if (!IsUnderLastManaUseEffect())
1260 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
1262 if (!m_regenTimer)
1263 RegenerateAll();
1266 if (m_deathState == JUST_DIED)
1268 KillPlayer();
1271 if(m_nextSave > 0)
1273 if(p_time >= m_nextSave)
1275 // m_nextSave reseted in SaveToDB call
1276 SaveToDB();
1277 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1279 else
1281 m_nextSave -= p_time;
1285 //Handle Water/drowning
1286 HandleDrowning(p_time);
1288 //Handle detect stealth players
1289 if (m_DetectInvTimer > 0)
1291 if (p_time >= m_DetectInvTimer)
1293 HandleStealthedUnitsDetection();
1294 m_DetectInvTimer = 3000;
1296 else
1297 m_DetectInvTimer -= p_time;
1300 // Played time
1301 if (now > m_Last_tick)
1303 uint32 elapsed = uint32(now - m_Last_tick);
1304 m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
1305 m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
1306 m_Last_tick = now;
1309 if (m_drunk)
1311 m_drunkTimer += p_time;
1313 if (m_drunkTimer > 10*IN_MILISECONDS)
1314 HandleSobering();
1317 // not auto-free ghost from body in instances
1318 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1320 if(p_time >= m_deathTimer)
1322 m_deathTimer = 0;
1323 BuildPlayerRepop();
1324 RepopAtGraveyard();
1326 else
1327 m_deathTimer -= p_time;
1330 UpdateEnchantTime(p_time);
1331 UpdateHomebindTime(p_time);
1333 // group update
1334 SendUpdateToOutOfRangeGroupMembers();
1336 Pet* pet = GetPet();
1337 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1339 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1342 //we should execute delayed teleports only for alive(!) players
1343 //because we don't want player's ghost teleported from graveyard
1344 if(IsHasDelayedTeleport() && isAlive())
1345 TeleportTo(m_teleport_dest, m_teleport_options);
1348 void Player::setDeathState(DeathState s)
1350 uint32 ressSpellId = 0;
1352 bool cur = isAlive();
1354 if(s == JUST_DIED && cur)
1356 // drunken state is cleared on death
1357 SetDrunkValue(0);
1358 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1359 ClearComboPoints();
1361 clearResurrectRequestData();
1363 // remove form before other mods to prevent incorrect stats calculation
1364 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1366 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1367 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1369 // remove uncontrolled pets
1370 RemoveMiniPet();
1372 // save value before aura remove in Unit::setDeathState
1373 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1375 // passive spell
1376 if(!ressSpellId)
1377 ressSpellId = GetResurrectionSpellId();
1378 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1379 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1380 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1382 Unit::setDeathState(s);
1384 // restore resurrection spell id for player after aura remove
1385 if(s == JUST_DIED && cur && ressSpellId)
1386 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1388 if(isAlive() && !cur)
1390 //clear aura case after resurrection by another way (spells will be applied before next death)
1391 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1393 // restore default warrior stance
1394 if(getClass()== CLASS_WARRIOR)
1395 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1399 bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1401 // 0 1 2 3 4 5 6 7
1402 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
1403 // 8 9 10 11 12 13 14
1404 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
1405 // 15 16 17 18 19 20
1406 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive "
1408 Field *fields = result->Fetch();
1410 uint32 guid = fields[0].GetUInt32();
1411 uint8 pRace = fields[2].GetUInt8();
1412 uint8 pClass = fields[3].GetUInt8();
1414 PlayerInfo const *info = objmgr.GetPlayerInfo(pRace, pClass);
1415 if(!info)
1417 sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
1418 return false;
1421 *p_data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
1422 *p_data << fields[1].GetString(); // name
1423 *p_data << uint8(pRace); // race
1424 *p_data << uint8(pClass); // class
1425 *p_data << uint8(fields[4].GetUInt8()); // gender
1427 uint32 playerBytes = fields[5].GetUInt32();
1428 *p_data << uint8(playerBytes); // skin
1429 *p_data << uint8(playerBytes >> 8); // face
1430 *p_data << uint8(playerBytes >> 16); // hair style
1431 *p_data << uint8(playerBytes >> 24); // hair color
1433 uint32 playerBytes2 = fields[6].GetUInt32();
1434 *p_data << uint8(playerBytes2 & 0xFF); // facial hair
1436 *p_data << uint8(fields[7].GetUInt8()); // level
1437 *p_data << uint32(fields[8].GetUInt32()); // zone
1438 *p_data << uint32(fields[9].GetUInt32()); // map
1440 *p_data << fields[10].GetFloat(); // x
1441 *p_data << fields[11].GetFloat(); // y
1442 *p_data << fields[12].GetFloat(); // z
1444 *p_data << uint32(fields[13].GetUInt32()); // guild id
1446 uint32 char_flags = 0;
1447 uint32 playerFlags = fields[14].GetUInt32();
1448 uint32 atLoginFlags = fields[15].GetUInt32();
1449 if(playerFlags & PLAYER_FLAGS_HIDE_HELM)
1450 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1451 if(playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
1452 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1453 if(playerFlags & PLAYER_FLAGS_GHOST)
1454 char_flags |= CHARACTER_FLAG_GHOST;
1455 if(atLoginFlags & AT_LOGIN_RENAME)
1456 char_flags |= CHARACTER_FLAG_RENAME;
1457 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
1459 if(!fields[20].GetCppString().empty())
1460 char_flags |= CHARACTER_FLAG_DECLINED;
1462 else
1463 char_flags |= CHARACTER_FLAG_DECLINED;
1465 *p_data << uint32(char_flags); // character flags
1466 // character customize flags
1467 *p_data << uint32(atLoginFlags & AT_LOGIN_CUSTOMIZE ? CHAR_CUSTOMIZE_FLAG_CUSTOMIZE : CHAR_CUSTOMIZE_FLAG_NONE);
1468 *p_data << uint8(1); // unknown
1470 // Pets info
1472 uint32 petDisplayId = 0;
1473 uint32 petLevel = 0;
1474 uint32 petFamily = 0;
1476 // show pet at selection character in character list only for non-ghost character
1477 if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1479 uint32 entry = fields[16].GetUInt32();
1480 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1481 if(cInfo)
1483 petDisplayId = fields[17].GetUInt32();
1484 petLevel = fields[18].GetUInt32();
1485 petFamily = cInfo->family;
1489 *p_data << uint32(petDisplayId);
1490 *p_data << uint32(petLevel);
1491 *p_data << uint32(petFamily);
1494 // TODO: do not access data field here
1495 Tokens data = StrSplit(fields[19].GetCppString(), " ");
1497 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1499 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1500 uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
1501 const ItemPrototype * proto = ObjectMgr::GetItemPrototype(item_id);
1502 if(!proto)
1504 *p_data << uint32(0);
1505 *p_data << uint8(0);
1506 *p_data << uint32(0);
1507 continue;
1510 SpellItemEnchantmentEntry const *enchant = NULL;
1512 uint32 enchants = GetUInt32ValueFromArray(data, visualbase + 1);
1513 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1515 // values stored in 2 uint16
1516 uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16);
1517 if(!enchantId)
1518 continue;
1520 if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId)))
1521 break;
1524 *p_data << uint32(proto->DisplayInfoID);
1525 *p_data << uint8(proto->InventoryType);
1526 *p_data << uint32(enchant ? enchant->aura_id : 0);
1528 *p_data << uint32(0); // first bag display id
1529 *p_data << uint8(0); // first bag inventory type
1530 *p_data << uint32(0); // enchant?
1532 return true;
1535 bool Player::ToggleAFK()
1537 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1539 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1541 // afk player not allowed in battleground
1542 if(state && InBattleGround())
1543 LeaveBattleground();
1545 return state;
1548 bool Player::ToggleDND()
1550 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1552 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1555 uint8 Player::chatTag() const
1557 // it's bitmask
1558 // 0x8 - ??
1559 // 0x4 - gm
1560 // 0x2 - dnd
1561 // 0x1 - afk
1562 if(isGMChat())
1563 return 4;
1564 else if(isDND())
1565 return 3;
1566 if(isAFK())
1567 return 1;
1568 else
1569 return 0;
1572 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1574 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1576 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1577 return false;
1580 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1581 Pet* pet = GetPet();
1583 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1585 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1586 // don't let gm level > 1 either
1587 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1588 return false;
1590 // client without expansion support
1591 if(GetSession()->Expansion() < mEntry->Expansion())
1593 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1595 if(GetTransport())
1596 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1598 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1600 return false; // normal client can't teleport to this map...
1602 else
1604 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1607 // if we were on a transport, leave
1608 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1610 m_transport->RemovePassenger(this);
1611 m_transport = NULL;
1612 m_movementInfo.t_x = 0.0f;
1613 m_movementInfo.t_y = 0.0f;
1614 m_movementInfo.t_z = 0.0f;
1615 m_movementInfo.t_o = 0.0f;
1616 m_movementInfo.t_seat = -1;
1617 m_movementInfo.t_time = 0;
1620 // The player was ported to another map and looses the duel immediately.
1621 // We have to perform this check before the teleport, otherwise the
1622 // ObjectAccessor won't find the flag.
1623 if (duel && GetMapId()!=mapid)
1625 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1626 if (obj)
1627 DuelComplete(DUEL_FLED);
1630 // reset movement flags at teleport, because player will continue move with these flags after teleport
1631 m_movementInfo.SetMovementFlags(MOVEMENTFLAG_NONE);
1633 if ((GetMapId() == mapid) && (!m_transport))
1635 //lets reset far teleport flag if it wasn't reset during chained teleports
1636 SetSemaphoreTeleportFar(false);
1637 //setup delayed teleport flag
1638 SetDelayedTeleportFlag(IsCanDelayTeleport());
1639 //if teleport spell is casted in Unit::Update() func
1640 //then we need to delay it until update process will be finished
1641 if(IsHasDelayedTeleport())
1643 SetSemaphoreTeleportNear(true);
1644 //lets save teleport destination for player
1645 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1646 m_teleport_options = options;
1647 return true;
1650 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1652 //same map, only remove pet if out of range for new position
1653 if(pet && !pet->IsWithinDist3d(x,y,z, OWNER_MAX_DISTANCE))
1654 UnsummonPetTemporaryIfAny();
1657 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1658 CombatStop();
1660 // this will be used instead of the current location in SaveToDB
1661 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1662 SetFallInformation(0, z);
1664 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1665 // at client packet MSG_MOVE_TELEPORT_ACK
1666 SetSemaphoreTeleportNear(true);
1667 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1668 if(!GetSession()->PlayerLogout())
1670 WorldPacket data;
1671 BuildTeleportAckMsg(&data, x, y, z, orientation);
1672 GetSession()->SendPacket(&data);
1675 else
1677 // far teleport to another map
1678 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1679 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1681 // Check enter rights before map getting to avoid creating instance copy for player
1682 // this check not dependent from map instance copy and same for all instance copies of selected map
1683 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1684 return false;
1686 // If the map is not created, assume it is possible to enter it.
1687 // It will be created in the WorldPortAck.
1688 Map *map = MapManager::Instance().FindMap(mapid);
1689 if (!map || map->CanEnter(this))
1691 //lets reset near teleport flag if it wasn't reset during chained teleports
1692 SetSemaphoreTeleportNear(false);
1693 //setup delayed teleport flag
1694 SetDelayedTeleportFlag(IsCanDelayTeleport());
1695 //if teleport spell is casted in Unit::Update() func
1696 //then we need to delay it until update process will be finished
1697 if(IsHasDelayedTeleport())
1699 SetSemaphoreTeleportFar(true);
1700 //lets save teleport destination for player
1701 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1702 m_teleport_options = options;
1703 return true;
1706 SetSelection(0);
1708 CombatStop();
1710 ResetContestedPvP();
1712 // remove player from battleground on far teleport (when changing maps)
1713 if(BattleGround const* bg = GetBattleGround())
1715 // Note: at battleground join battleground id set before teleport
1716 // and we already will found "current" battleground
1717 // just need check that this is targeted map or leave
1718 if(bg->GetMapId() != mapid)
1719 LeaveBattleground(false); // don't teleport to entry point
1722 // remove pet on map change
1723 if (pet)
1724 UnsummonPetTemporaryIfAny();
1726 // remove all dyn objects
1727 RemoveAllDynObjects();
1729 // stop spellcasting
1730 // not attempt interrupt teleportation spell at caster teleport
1731 if(!(options & TELE_TO_SPELL))
1732 if(IsNonMeleeSpellCasted(true))
1733 InterruptNonMeleeSpells(true);
1735 //remove auras before removing from map...
1736 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1738 if(!GetSession()->PlayerLogout())
1740 // send transfer packets
1741 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1742 data << uint32(mapid);
1743 if (m_transport)
1745 data << m_transport->GetEntry() << GetMapId();
1747 GetSession()->SendPacket(&data);
1749 data.Initialize(SMSG_NEW_WORLD, (20));
1750 if (m_transport)
1752 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1754 else
1756 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1758 GetSession()->SendPacket( &data );
1759 SendSavedInstances();
1762 // remove from old map now
1763 if(oldmap)
1764 oldmap->Remove(this, false);
1766 // new final coordinates
1767 float final_x = x;
1768 float final_y = y;
1769 float final_z = z;
1770 float final_o = orientation;
1772 if(m_transport)
1774 final_x += m_movementInfo.t_x;
1775 final_y += m_movementInfo.t_y;
1776 final_z += m_movementInfo.t_z;
1777 final_o += m_movementInfo.t_o;
1780 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1781 SetFallInformation(0, final_z);
1782 // if the player is saved before worldportack (at logout for example)
1783 // this will be used instead of the current location in SaveToDB
1785 // move packet sent by client always after far teleport
1786 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1787 SetSemaphoreTeleportFar(true);
1789 else
1790 return false;
1792 return true;
1795 bool Player::TeleportToBGEntryPoint()
1797 ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
1798 ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
1799 return TeleportTo(m_bgData.joinPos);
1802 void Player::ProcessDelayedOperations()
1804 if(m_DelayedOperations == 0)
1805 return;
1807 if(m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
1809 ResurrectPlayer(0.0f, false);
1811 if(GetMaxHealth() > m_resurrectHealth)
1812 SetHealth( m_resurrectHealth );
1813 else
1814 SetHealth( GetMaxHealth() );
1816 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
1817 SetPower(POWER_MANA, m_resurrectMana );
1818 else
1819 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
1821 SetPower(POWER_RAGE, 0 );
1822 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
1824 SpawnCorpseBones();
1827 if(m_DelayedOperations & DELAYED_SAVE_PLAYER)
1829 SaveToDB();
1832 if(m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
1834 CastSpell(this, 26013, true); // Deserter
1837 if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
1839 if (m_bgData.mountSpell)
1841 CastSpell(this, m_bgData.mountSpell, true);
1842 m_bgData.mountSpell = 0;
1846 if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
1848 if (m_bgData.HasTaxiPath())
1850 m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
1851 m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
1852 m_bgData.ClearTaxiPath();
1854 ContinueTaxiFlight();
1858 //we have executed ALL delayed ops, so clear the flag
1859 m_DelayedOperations = 0;
1862 void Player::AddToWorld()
1864 ///- Do not add/remove the player from the object storage
1865 ///- It will crash when updating the ObjectAccessor
1866 ///- The player should only be added when logging in
1867 Unit::AddToWorld();
1869 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1871 if(m_items[i])
1872 m_items[i]->AddToWorld();
1876 void Player::RemoveFromWorld()
1878 // cleanup
1879 if(IsInWorld())
1881 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1882 Uncharm();
1883 UnsummonAllTotems();
1884 RemoveMiniPet();
1887 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1889 if(m_items[i])
1890 m_items[i]->RemoveFromWorld();
1893 ///- Do not add/remove the player from the object storage
1894 ///- It will crash when updating the ObjectAccessor
1895 ///- The player should only be removed when logging out
1896 Unit::RemoveFromWorld();
1899 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1901 float addRage;
1903 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1905 if(attacker)
1907 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1909 // talent who gave more rage on attack
1910 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1912 else
1914 addRage = damage/rageconversion*2.5;
1916 // Berserker Rage effect
1917 if(HasAura(18499,0))
1918 addRage *= 1.3;
1921 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1923 ModifyPower(POWER_RAGE, uint32(addRage*10));
1926 void Player::RegenerateAll(uint32 diff)
1928 // Not in combat or they have regeneration
1929 if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1930 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1932 RegenerateHealth(diff);
1933 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1935 Regenerate(POWER_RAGE, diff);
1936 if(getClass() == CLASS_DEATH_KNIGHT)
1937 Regenerate(POWER_RUNIC_POWER, diff);
1941 Regenerate(POWER_ENERGY, diff);
1943 Regenerate(POWER_MANA, diff);
1945 if (getClass() == CLASS_DEATH_KNIGHT)
1946 Regenerate(POWER_RUNE, diff);
1948 m_regenTimer = REGEN_TIME_FULL;
1951 // diff contains the time in milliseconds since last regen.
1952 void Player::Regenerate(Powers power, uint32 diff)
1954 uint32 curValue = GetPower(power);
1955 uint32 maxValue = GetMaxPower(power);
1957 float addvalue = 0.0f;
1959 switch (power)
1961 case POWER_MANA:
1963 bool recentCast = IsUnderLastManaUseEffect();
1964 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1965 if (recentCast)
1967 // Mangos Updates Mana in intervals of 2s, which is correct
1968 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1970 else
1972 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1974 } break;
1975 case POWER_RAGE: // Regenerate rage
1977 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1978 addvalue = 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
1979 } break;
1980 case POWER_ENERGY: // Regenerate energy (rogue)
1981 addvalue = 20;
1982 break;
1983 case POWER_RUNIC_POWER:
1985 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1986 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1987 } break;
1988 case POWER_RUNE:
1990 if (getClass() != CLASS_DEATH_KNIGHT)
1991 break;
1993 for(uint32 i = 0; i < MAX_RUNES; ++i)
1995 if(uint16 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1996 SetRuneCooldown(i, (cd < diff) ? 0 : cd - diff);
1998 } break;
1999 case POWER_FOCUS:
2000 case POWER_HAPPINESS:
2001 case POWER_HEALTH:
2002 break;
2005 // Mana regen calculated in Player::UpdateManaRegen()
2006 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
2007 if(power != POWER_MANA)
2009 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
2010 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
2011 if ((*i)->GetModifier()->m_miscvalue == power)
2012 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
2015 // addvalue computed on a 2sec basis. => update to diff time
2016 addvalue *= float(diff) / REGEN_TIME_FULL;
2018 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
2020 curValue += uint32(addvalue);
2021 if (curValue > maxValue)
2022 curValue = maxValue;
2024 else
2026 if(curValue <= uint32(addvalue))
2027 curValue = 0;
2028 else
2029 curValue -= uint32(addvalue);
2031 SetPower(power, curValue);
2034 void Player::RegenerateHealth(uint32 diff)
2036 uint32 curValue = GetHealth();
2037 uint32 maxValue = GetMaxHealth();
2039 if (curValue >= maxValue) return;
2041 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
2043 float addvalue = 0.0f;
2045 // polymorphed case
2046 if ( IsPolymorphed() )
2047 addvalue = GetMaxHealth()/3;
2048 // normal regen case (maybe partly in combat case)
2049 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
2051 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
2052 if (!isInCombat())
2054 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
2055 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
2056 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
2058 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
2059 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
2061 if(!IsStandState())
2062 addvalue *= 1.5;
2065 // always regeneration bonus (including combat)
2066 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
2068 if(addvalue < 0)
2069 addvalue = 0;
2071 addvalue *= (float)diff / REGEN_TIME_FULL;
2073 ModifyHealth(int32(addvalue));
2076 Creature* Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
2078 // unit checks
2079 if (!guid || !IsInWorld() || isInFlight())
2080 return NULL;
2082 // exist (we need look pets also for some interaction (quest/etc)
2083 Creature *unit = GetMap()->GetCreatureOrPetOrVehicle(guid);
2084 if (!unit)
2085 return NULL;
2087 // appropriate npc type
2088 if (npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
2089 return NULL;
2091 // if a dead unit should be able to talk - the creature must be alive and have special flags
2092 if (!unit->isAlive())
2093 return NULL;
2095 if (isAlive() && unit->isInvisibleForAlive())
2096 return NULL;
2098 // not allow interaction under control, but allow with own pets
2099 if (unit->GetCharmerGUID())
2100 return NULL;
2102 // not enemy
2103 if (unit->IsHostileTo(this))
2104 return NULL;
2106 // not unfriendly
2107 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
2108 if(factionTemplate->faction)
2109 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
2110 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
2111 return NULL;
2113 // not too far
2114 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
2115 return NULL;
2117 return unit;
2120 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
2122 if(GameObject *go = GetMap()->GetGameObject(guid))
2124 if(go->GetGoType() == type)
2126 float maxdist;
2127 switch(type)
2129 // TODO: find out how the client calculates the maximal usage distance to spellless working
2130 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2131 case GAMEOBJECT_TYPE_GUILD_BANK:
2132 case GAMEOBJECT_TYPE_MAILBOX:
2133 maxdist = 10.0f;
2134 break;
2135 case GAMEOBJECT_TYPE_FISHINGHOLE:
2136 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2137 break;
2138 default:
2139 maxdist = INTERACTION_DISTANCE;
2140 break;
2143 if (go->IsWithinDistInMap(this, maxdist))
2144 return go;
2146 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,
2147 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2150 return NULL;
2153 bool Player::IsUnderWater() const
2155 return IsInWater() &&
2156 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2159 void Player::SetInWater(bool apply)
2161 if(m_isInWater==apply)
2162 return;
2164 //define player in water by opcodes
2165 //move player's guid into HateOfflineList of those mobs
2166 //which can't swim and move guid back into ThreatList when
2167 //on surface.
2168 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2169 m_isInWater = apply;
2171 // remove auras that need water/land
2172 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2174 getHostileRefManager().updateThreatTables();
2177 void Player::SetGameMaster(bool on)
2179 if(on)
2181 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2182 setFaction(35);
2183 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2185 if (Pet* pet = GetPet())
2187 pet->setFaction(35);
2188 pet->getHostileRefManager().setOnlineOfflineState(false);
2191 for (int8 i = 0; i < MAX_TOTEM; ++i)
2192 if(m_TotemSlot[i])
2193 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2194 totem->setFaction(35);
2196 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2197 ResetContestedPvP();
2199 getHostileRefManager().setOnlineOfflineState(false);
2200 CombatStopWithPets();
2202 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2204 else
2206 // restore phase
2207 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2208 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2210 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2211 setFactionForRace(getRace());
2212 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2214 if (Pet* pet = GetPet())
2216 pet->setFaction(getFaction());
2217 pet->getHostileRefManager().setOnlineOfflineState(true);
2220 for (int8 i = 0; i < MAX_TOTEM; ++i)
2221 if(m_TotemSlot[i])
2222 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2223 totem->setFaction(getFaction());
2225 // restore FFA PvP Server state
2226 if(sWorld.IsFFAPvPRealm())
2227 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2229 // restore FFA PvP area state, remove not allowed for GM mounts
2230 UpdateArea(m_areaUpdateId);
2232 getHostileRefManager().setOnlineOfflineState(true);
2235 UpdateVisibilityForPlayer();
2238 void Player::SetGMVisible(bool on)
2240 if(on)
2242 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2244 // Reapply stealth/invisibility if active or show if not any
2245 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2246 SetVisibility(VISIBILITY_GROUP_STEALTH);
2247 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2248 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2249 else
2250 SetVisibility(VISIBILITY_ON);
2252 else
2254 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2256 SetAcceptWhispers(false);
2257 SetGameMaster(true);
2259 SetVisibility(VISIBILITY_OFF);
2263 bool Player::IsGroupVisibleFor(Player* p) const
2265 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2267 default: return IsInSameGroupWith(p);
2268 case 1: return IsInSameRaidWith(p);
2269 case 2: return GetTeam()==p->GetTeam();
2273 bool Player::IsInSameGroupWith(Player const* p) const
2275 return (p==this || (GetGroup() != NULL &&
2276 GetGroup()->SameSubGroup((Player*)this, (Player*)p)));
2279 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2280 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2281 void Player::UninviteFromGroup()
2283 Group* group = GetGroupInvite();
2284 if(!group)
2285 return;
2287 group->RemoveInvite(this);
2289 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2291 if(group->IsCreated())
2293 group->Disband(true);
2294 objmgr.RemoveGroup(group);
2296 else
2297 group->RemoveAllInvites();
2299 delete group;
2303 void Player::RemoveFromGroup(Group* group, uint64 guid)
2305 if(group)
2307 if (group->RemoveMember(guid, 0) <= 1)
2309 // group->Disband(); already disbanded in RemoveMember
2310 objmgr.RemoveGroup(group);
2311 delete group;
2312 // removemember sets the player's group pointer to NULL
2317 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2319 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2320 data << uint64(victim ? victim->GetGUID() : 0); // guid
2321 data << uint32(GivenXP+RestXP); // given experience
2322 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2323 if(victim)
2325 data << uint32(GivenXP); // experience without rested bonus
2326 data << float(1); // 1 - none 0 - 100% group bonus output
2328 data << uint8(0); // new 2.4.0
2329 GetSession()->SendPacket(&data);
2332 void Player::GiveXP(uint32 xp, Unit* victim)
2334 if ( xp < 1 )
2335 return;
2337 if(!isAlive())
2338 return;
2340 uint32 level = getLevel();
2342 // XP to money conversion processed in Player::RewardQuest
2343 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2344 return;
2346 if(victim)
2348 // handle SPELL_AURA_MOD_KILL_XP_PCT auras
2349 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT);
2350 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2351 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2353 else
2355 // handle SPELL_AURA_MOD_QUEST_XP_PCT auras
2356 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT);
2357 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2358 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2362 // XP resting bonus for kill
2363 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2365 SendLogXPGain(xp,victim,rested_bonus_xp);
2367 uint32 curXP = GetUInt32Value(PLAYER_XP);
2368 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2369 uint32 newXP = curXP + xp + rested_bonus_xp;
2371 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2373 newXP -= nextLvlXP;
2375 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2376 GiveLevel(level + 1);
2378 level = getLevel();
2379 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2382 SetUInt32Value(PLAYER_XP, newXP);
2385 // Update player to next level
2386 // Current player experience not update (must be update by caller)
2387 void Player::GiveLevel(uint32 level)
2389 if ( level == getLevel() )
2390 return;
2392 PlayerLevelInfo info;
2393 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2395 PlayerClassLevelInfo classInfo;
2396 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2398 // send levelup info to client
2399 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2400 data << uint32(level);
2401 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2402 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2403 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2404 data << uint32(0);
2405 data << uint32(0);
2406 data << uint32(0);
2407 data << uint32(0);
2408 data << uint32(0);
2409 data << uint32(0);
2410 // end for
2411 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2412 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2414 GetSession()->SendPacket(&data);
2416 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2418 //update level, max level of skills
2419 m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
2421 _ApplyAllLevelScaleItemMods(false);
2423 SetLevel(level);
2425 UpdateSkillsForLevel ();
2427 // save base values (bonuses already included in stored stats
2428 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2429 SetCreateStat(Stats(i), info.stats[i]);
2431 SetCreateHealth(classInfo.basehealth);
2432 SetCreateMana(classInfo.basemana);
2434 InitTalentForLevel();
2435 InitTaxiNodesForLevel();
2436 InitGlyphsForLevel();
2438 UpdateAllStats();
2440 // set current level health and mana/energy to maximum after applying all mods.
2441 SetHealth(GetMaxHealth());
2442 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2443 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2444 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2445 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2446 SetPower(POWER_FOCUS, 0);
2447 SetPower(POWER_HAPPINESS, 0);
2449 _ApplyAllLevelScaleItemMods(true);
2451 // update level to hunter/summon pet
2452 if (Pet* pet = GetPet())
2453 pet->SynchronizeLevelWithOwner();
2455 if (MailLevelReward const* mailReward = objmgr.GetMailLevelReward(level,getRaceMask()))
2456 MailDraft(mailReward->mailTemplateId).SendMailTo(this,MailSender(MAIL_CREATURE,mailReward->senderEntry));
2458 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2461 void Player::InitTalentForLevel()
2463 uint32 level = getLevel();
2464 // talents base at level diff ( talents = level - 9 but some can be used already)
2465 if(level < 10)
2467 // Remove all talent points
2468 if(m_usedTalentCount > 0) // Free any used talents
2470 resetTalents(true);
2471 SetFreeTalentPoints(0);
2474 else
2476 uint32 talentPointsForLevel = CalculateTalentsPoints();
2478 // if used more that have then reset
2479 if(m_usedTalentCount > talentPointsForLevel)
2481 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2482 resetTalents(true);
2483 else
2484 SetFreeTalentPoints(0);
2486 // else update amount of free points
2487 else
2488 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2491 if(!GetSession()->PlayerLoading())
2492 SendTalentsInfoData(false); // update at client
2495 void Player::InitStatsForLevel(bool reapplyMods)
2497 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2498 _RemoveAllStatBonuses();
2500 PlayerClassLevelInfo classInfo;
2501 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2503 PlayerLevelInfo info;
2504 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2506 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2507 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2509 UpdateSkillsForLevel ();
2511 // set default cast time multiplier
2512 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2514 // reset size before reapply auras
2515 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2517 // save base values (bonuses already included in stored stats
2518 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2519 SetCreateStat(Stats(i), info.stats[i]);
2521 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2522 SetStat(Stats(i), info.stats[i]);
2524 SetCreateHealth(classInfo.basehealth);
2526 //set create powers
2527 SetCreateMana(classInfo.basemana);
2529 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2531 InitStatBuffMods();
2533 //reset rating fields values
2534 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2535 SetUInt32Value(index, 0);
2537 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2538 for (int i = 0; i < 7; ++i)
2540 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2541 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2542 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2545 //reset attack power, damage and attack speed fields
2546 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2547 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2548 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2550 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2551 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2552 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2553 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2554 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2555 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2557 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2558 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2559 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2560 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2561 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2562 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2564 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2565 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2566 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2567 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2569 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2570 for (uint8 i = 0; i < 7; ++i)
2571 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2573 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2574 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2575 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2577 // Dodge percentage
2578 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2580 // set armor (resistance 0) to original value (create_agility*2)
2581 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2582 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2583 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2584 // set other resistance to original value (0)
2585 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2587 SetResistance(SpellSchools(i), 0);
2588 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2589 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2592 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2593 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2594 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2596 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2597 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2599 // Reset no reagent cost field
2600 for(int i = 0; i < 3; ++i)
2601 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2602 // Init data for form but skip reapply item mods for form
2603 InitDataForForm(reapplyMods);
2605 // save new stats
2606 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2607 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2609 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2611 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2612 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2614 // cleanup unit flags (will be re-applied if need at aura load).
2615 RemoveFlag( UNIT_FIELD_FLAGS,
2616 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2617 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2618 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2619 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2620 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2621 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2623 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2625 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2626 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2628 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2629 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2631 // restore if need some important flags
2632 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2634 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2635 _ApplyAllStatBonuses();
2637 // set current level health and mana/energy to maximum after applying all mods.
2638 SetHealth(GetMaxHealth());
2639 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2640 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2641 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2642 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2643 SetPower(POWER_FOCUS, 0);
2644 SetPower(POWER_HAPPINESS, 0);
2645 SetPower(POWER_RUNIC_POWER, 0);
2647 // update level to hunter/summon pet
2648 if (Pet* pet = GetPet())
2649 pet->SynchronizeLevelWithOwner();
2652 void Player::SendInitialSpells()
2654 time_t curTime = time(NULL);
2655 time_t infTime = curTime + infinityCooldownDelayCheck;
2657 uint16 spellCount = 0;
2659 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2660 data << uint8(0);
2662 size_t countPos = data.wpos();
2663 data << uint16(spellCount); // spell count placeholder
2665 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2667 if(itr->second->state == PLAYERSPELL_REMOVED)
2668 continue;
2670 if(!itr->second->active || itr->second->disabled)
2671 continue;
2673 data << uint32(itr->first);
2674 data << uint16(0); // it's not slot id
2676 spellCount +=1;
2679 data.put<uint16>(countPos,spellCount); // write real count value
2681 uint16 spellCooldowns = m_spellCooldowns.size();
2682 data << uint16(spellCooldowns);
2683 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2685 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2686 if(!sEntry)
2687 continue;
2689 data << uint32(itr->first);
2691 data << uint16(itr->second.itemid); // cast item id
2692 data << uint16(sEntry->Category); // spell category
2694 // send infinity cooldown in special format
2695 if(itr->second.end >= infTime)
2697 data << uint32(1); // cooldown
2698 data << uint32(0x80000000); // category cooldown
2699 continue;
2702 time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILISECONDS : 0;
2704 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2706 data << uint32(0); // cooldown
2707 data << uint32(cooldown); // category cooldown
2709 else
2711 data << uint32(cooldown); // cooldown
2712 data << uint32(0); // category cooldown
2716 GetSession()->SendPacket(&data);
2718 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2721 void Player::RemoveMail(uint32 id)
2723 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2725 if ((*itr)->messageID == id)
2727 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2728 m_mail.erase(itr);
2729 return;
2734 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2736 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2737 data << (uint32) mailId;
2738 data << (uint32) mailAction;
2739 data << (uint32) mailError;
2740 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2741 data << (uint32) equipError;
2742 else if( mailAction == MAIL_ITEM_TAKEN )
2744 data << (uint32) item_guid; // item guid low?
2745 data << (uint32) item_count; // item count?
2747 GetSession()->SendPacket(&data);
2750 void Player::SendNewMail()
2752 // deliver undelivered mail
2753 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2754 data << (uint32) 0;
2755 GetSession()->SendPacket(&data);
2758 void Player::UpdateNextMailTimeAndUnreads()
2760 // calculate next delivery time (min. from non-delivered mails
2761 // and recalculate unReadMail
2762 time_t cTime = time(NULL);
2763 m_nextMailDelivereTime = 0;
2764 unReadMails = 0;
2765 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2767 if((*itr)->deliver_time > cTime)
2769 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2770 m_nextMailDelivereTime = (*itr)->deliver_time;
2772 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2773 ++unReadMails;
2777 void Player::AddNewMailDeliverTime(time_t deliver_time)
2779 if(deliver_time <= time(NULL)) // ready now
2781 ++unReadMails;
2782 SendNewMail();
2784 else // not ready and no have ready mails
2786 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2787 m_nextMailDelivereTime = deliver_time;
2791 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2793 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2794 if (!spellInfo)
2796 // do character spell book cleanup (all characters)
2797 if(!IsInWorld() && !learning) // spell load case
2799 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2800 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2802 else
2803 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2805 return false;
2808 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2810 // do character spell book cleanup (all characters)
2811 if(!IsInWorld() && !learning) // spell load case
2813 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2814 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2816 else
2817 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2819 return false;
2822 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2824 bool dependent_set = false;
2825 bool disabled_case = false;
2826 bool superceded_old = false;
2828 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2829 if (itr != m_spells.end())
2831 uint32 next_active_spell_id = 0;
2832 // fix activate state for non-stackable low rank (and find next spell for !active case)
2833 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2835 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2836 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2838 if(HasSpell(next_itr->second))
2840 // high rank already known so this must !active
2841 active = false;
2842 next_active_spell_id = next_itr->second;
2843 break;
2848 // not do anything if already known in expected state
2849 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2850 itr->second->dependent == dependent && itr->second->disabled == disabled)
2852 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2853 itr->second->state = PLAYERSPELL_UNCHANGED;
2855 return false;
2858 // dependent spell known as not dependent, overwrite state
2859 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2861 itr->second->dependent = dependent;
2862 if (itr->second->state != PLAYERSPELL_NEW)
2863 itr->second->state = PLAYERSPELL_CHANGED;
2864 dependent_set = true;
2867 // update active state for known spell
2868 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2870 itr->second->active = active;
2872 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2873 itr->second->state = PLAYERSPELL_UNCHANGED;
2874 else if(itr->second->state != PLAYERSPELL_NEW)
2875 itr->second->state = PLAYERSPELL_CHANGED;
2877 if(active)
2879 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2880 CastSpell (this,spell_id,true);
2882 else if(IsInWorld())
2884 if(next_active_spell_id)
2886 // update spell ranks in spellbook and action bar
2887 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2888 data << uint32(spell_id);
2889 data << uint32(next_active_spell_id);
2890 GetSession()->SendPacket( &data );
2892 else
2894 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2895 data << uint32(spell_id);
2896 GetSession()->SendPacket(&data);
2900 return active; // learn (show in spell book if active now)
2903 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2905 if(itr->second->state != PLAYERSPELL_NEW)
2906 itr->second->state = PLAYERSPELL_CHANGED;
2907 itr->second->disabled = disabled;
2909 if(disabled)
2910 return false;
2912 disabled_case = true;
2914 else switch(itr->second->state)
2916 case PLAYERSPELL_UNCHANGED: // known saved spell
2917 return false;
2918 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2920 delete itr->second;
2921 m_spells.erase(itr);
2922 state = PLAYERSPELL_CHANGED;
2923 break; // need re-add
2925 default: // known not saved yet spell (new or modified)
2927 // can be in case spell loading but learned at some previous spell loading
2928 if(!IsInWorld() && !learning && !dependent_set)
2929 itr->second->state = PLAYERSPELL_UNCHANGED;
2931 return false;
2936 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2938 // talent: unlearn all other talent ranks (high and low)
2939 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2941 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2943 for(int i=0; i < MAX_TALENT_RANK; ++i)
2945 // skip learning spell and no rank spell case
2946 uint32 rankSpellId = talentInfo->RankID[i];
2947 if(!rankSpellId || rankSpellId==spell_id)
2948 continue;
2950 removeSpell(rankSpellId,false,false);
2954 // non talent spell: learn low ranks (recursive call)
2955 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2957 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2958 addSpell(prev_spell,active,true,true,disabled);
2959 else // at normal learning
2960 learnSpell(prev_spell,true);
2963 PlayerSpell *newspell = new PlayerSpell;
2964 newspell->state = state;
2965 newspell->active = active;
2966 newspell->dependent = dependent;
2967 newspell->disabled = disabled;
2969 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2970 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2972 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
2974 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
2975 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
2976 if(!i_spellInfo) continue;
2978 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
2980 if(itr2->second->active)
2982 if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
2984 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2986 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2987 data << uint32(itr2->first);
2988 data << uint32(spell_id);
2989 GetSession()->SendPacket( &data );
2992 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2993 itr2->second->active = false;
2994 if(itr2->second->state != PLAYERSPELL_NEW)
2995 itr2->second->state = PLAYERSPELL_CHANGED;
2996 superceded_old = true; // new spell replace old in action bars and spell book.
2998 else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
3000 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3002 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3003 data << uint32(spell_id);
3004 data << uint32(itr2->first);
3005 GetSession()->SendPacket( &data );
3008 // mark new spell as disable (not learned yet for client and will not learned)
3009 newspell->active = false;
3010 if(newspell->state != PLAYERSPELL_NEW)
3011 newspell->state = PLAYERSPELL_CHANGED;
3018 m_spells[spell_id] = newspell;
3020 // return false if spell disabled
3021 if (newspell->disabled)
3022 return false;
3025 uint32 talentCost = GetTalentSpellCost(spell_id);
3027 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3028 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3029 if (talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
3031 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3032 CastSpell(this, spell_id, true);
3034 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3035 else if (IsPassiveSpell(spell_id))
3037 if (IsNeedCastPassiveSpellAtLearn(spellInfo))
3038 CastSpell(this, spell_id, true);
3040 else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
3042 CastSpell(this, spell_id, true);
3043 return false;
3046 // update used talent points count
3047 m_usedTalentCount += talentCost;
3049 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3050 if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
3052 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3053 SetFreePrimaryProfessions(freeProfs-1);
3056 // add dependent skills
3057 uint16 maxskill = GetMaxSkillValueForLevel();
3059 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3061 SkillLineAbilityMapBounds skill_bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
3063 if (spellLearnSkill)
3065 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
3066 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
3068 if (skill_value < spellLearnSkill->value)
3069 skill_value = spellLearnSkill->value;
3071 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
3073 if (skill_max_value < new_skill_max_value)
3074 skill_max_value = new_skill_max_value;
3076 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
3078 else
3080 // not ranked skills
3081 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3083 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3084 if (!pSkill)
3085 continue;
3087 if (HasSkill(pSkill->id))
3088 continue;
3090 if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3091 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3092 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3094 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
3096 case SKILL_RANGE_LANGUAGE:
3097 SetSkill(pSkill->id, 300, 300 );
3098 break;
3099 case SKILL_RANGE_LEVEL:
3100 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
3101 break;
3102 case SKILL_RANGE_MONO:
3103 SetSkill(pSkill->id, 1, 1 );
3104 break;
3105 default:
3106 break;
3112 // learn dependent spells
3113 SpellLearnSpellMapBounds spell_bounds = spellmgr.GetSpellLearnSpellMapBounds(spell_id);
3115 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3117 if (!itr2->second.autoLearned)
3119 if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
3120 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
3121 else // at normal learning
3122 learnSpell(itr2->second.spell,true);
3126 if (!GetSession()->PlayerLoading())
3128 // not ranked skills
3129 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3131 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3132 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3135 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3138 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3139 return active && !disabled && !superceded_old;
3142 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3144 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3145 // talent dependent passives activated at form apply have proper stance data
3146 bool need_cast = (!spellInfo->Stances || (m_form != 0 && (spellInfo->Stances & (1<<(m_form-1)))));
3148 //Check CasterAuraStates
3149 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3152 void Player::learnSpell(uint32 spell_id, bool dependent)
3154 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3156 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3157 bool active = disabled ? itr->second->active : true;
3159 bool learning = addSpell(spell_id,active,true,dependent,false);
3161 // learn all disabled higher ranks (recursive)
3162 if(disabled)
3164 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3165 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3167 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3168 if (iter != m_spells.end() && iter->second->disabled)
3169 learnSpell(i->second,false);
3173 // prevent duplicated entires in spell book, also not send if not in world (loading)
3174 if(!learning || !IsInWorld ())
3175 return;
3177 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3178 data << uint32(spell_id);
3179 GetSession()->SendPacket(&data);
3182 void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank)
3184 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3185 if (itr == m_spells.end())
3186 return;
3188 if (itr->second->state == PLAYERSPELL_REMOVED || (disabled && itr->second->disabled))
3189 return;
3191 // unlearn non talent higher ranks (recursive)
3192 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3193 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3194 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3195 removeSpell(itr2->second,disabled,false);
3197 // re-search, it can be corrupted in prev loop
3198 itr = m_spells.find(spell_id);
3199 if (itr == m_spells.end())
3200 return; // already unleared
3202 bool cur_active = itr->second->active;
3203 bool cur_dependent = itr->second->dependent;
3205 if (disabled)
3207 itr->second->disabled = disabled;
3208 if(itr->second->state != PLAYERSPELL_NEW)
3209 itr->second->state = PLAYERSPELL_CHANGED;
3211 else
3213 if(itr->second->state == PLAYERSPELL_NEW)
3215 delete itr->second;
3216 m_spells.erase(itr);
3218 else
3219 itr->second->state = PLAYERSPELL_REMOVED;
3222 RemoveAurasDueToSpell(spell_id);
3224 // remove pet auras
3225 for(int i = 0; i < 3; ++i)
3226 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id, i))
3227 RemovePetAura(petSpell);
3229 // free talent points
3230 uint32 talentCosts = GetTalentSpellCost(spell_id);
3231 if(talentCosts > 0)
3233 if(talentCosts < m_usedTalentCount)
3234 m_usedTalentCount -= talentCosts;
3235 else
3236 m_usedTalentCount = 0;
3239 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3240 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3242 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3243 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3244 SetFreePrimaryProfessions(freeProfs);
3247 // remove dependent skill
3248 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3249 if(spellLearnSkill)
3251 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3252 if(!prev_spell) // first rank, remove skill
3253 SetSkill(spellLearnSkill->skill,0,0);
3254 else
3256 // search prev. skill setting by spell ranks chain
3257 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3258 while(!prevSkill && prev_spell)
3260 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3261 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3264 if (!prevSkill) // not found prev skill setting, remove skill
3265 SetSkill(spellLearnSkill->skill,0,0);
3266 else // set to prev. skill setting values
3268 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3269 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3271 if (skill_value > prevSkill->value)
3272 skill_value = prevSkill->value;
3274 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3276 if (skill_max_value > new_skill_max_value)
3277 skill_max_value = new_skill_max_value;
3279 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3284 else
3286 // not ranked skills
3287 SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
3289 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
3291 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3292 if (!pSkill)
3293 continue;
3295 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
3296 pSkill->categoryId != SKILL_CATEGORY_CLASS ||// not unlearn class skills (spellbook/talent pages)
3297 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3298 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3300 // not reset skills for professions and racial abilities
3301 if ((pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3302 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0))
3303 continue;
3305 SetSkill(pSkill->id, 0, 0 );
3310 // remove dependent spells
3311 SpellLearnSpellMapBounds spell_bounds = spellmgr.GetSpellLearnSpellMapBounds(spell_id);
3313 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3314 removeSpell(itr2->second.spell, disabled);
3316 // activate lesser rank in spellbook/action bar, and cast it if need
3317 bool prev_activate = false;
3319 if (uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3321 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3323 // if talent then lesser rank also talent and need learn
3324 if (talentCosts)
3326 if(learn_low_rank)
3327 learnSpell (prev_id,false);
3329 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3330 else if (cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3332 // need manually update dependence state (learn spell ignore like attempts)
3333 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3334 if (prev_itr != m_spells.end())
3336 if (prev_itr->second->dependent != cur_dependent)
3338 prev_itr->second->dependent = cur_dependent;
3339 if (prev_itr->second->state != PLAYERSPELL_NEW)
3340 prev_itr->second->state = PLAYERSPELL_CHANGED;
3343 // now re-learn if need re-activate
3344 if (cur_active && !prev_itr->second->active && learn_low_rank)
3346 if (addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3348 // downgrade spell ranks in spellbook and action bar
3349 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3350 data << uint32(spell_id);
3351 data << uint32(prev_id);
3352 GetSession()->SendPacket( &data );
3353 prev_activate = true;
3360 // remove from spell book if not replaced by lesser rank
3361 if(!prev_activate)
3363 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3364 data << uint32(spell_id);
3365 GetSession()->SendPacket(&data);
3369 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3371 m_spellCooldowns.erase(spell_id);
3373 if(update)
3374 SendClearCooldown(spell_id, this);
3377 void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
3379 SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
3380 if (ct == sSpellCategoryStore.end())
3381 return;
3383 const SpellCategorySet& ct_set = ct->second;
3384 for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
3386 if (ct_set.find(i->first) != ct_set.end())
3387 RemoveSpellCooldown((i++)->first, update);
3388 else
3389 ++i;
3393 void Player::RemoveArenaSpellCooldowns()
3395 // remove cooldowns on spells that has < 15 min CD
3396 SpellCooldowns::iterator itr, next;
3397 // iterate spell cooldowns
3398 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3400 next = itr;
3401 ++next;
3402 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3403 // check if spellentry is present and if the cooldown is less than 15 mins
3404 if( entry &&
3405 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3406 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3408 // remove & notify
3409 RemoveSpellCooldown(itr->first, true);
3414 void Player::RemoveAllSpellCooldown()
3416 if(!m_spellCooldowns.empty())
3418 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3419 SendClearCooldown(itr->first, this);
3421 m_spellCooldowns.clear();
3425 void Player::_LoadSpellCooldowns(QueryResult *result)
3427 // some cooldowns can be already set at aura loading...
3429 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3431 if(result)
3433 time_t curTime = time(NULL);
3437 Field *fields = result->Fetch();
3439 uint32 spell_id = fields[0].GetUInt32();
3440 uint32 item_id = fields[1].GetUInt32();
3441 time_t db_time = (time_t)fields[2].GetUInt64();
3443 if(!sSpellStore.LookupEntry(spell_id))
3445 sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3446 continue;
3449 // skip outdated cooldown
3450 if(db_time <= curTime)
3451 continue;
3453 AddSpellCooldown(spell_id, item_id, db_time);
3455 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3457 while( result->NextRow() );
3459 delete result;
3463 void Player::_SaveSpellCooldowns()
3465 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3467 time_t curTime = time(NULL);
3468 time_t infTime = curTime + infinityCooldownDelayCheck;
3470 // remove outdated and save active
3471 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3473 if(itr->second.end <= curTime)
3474 m_spellCooldowns.erase(itr++);
3475 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3477 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));
3478 ++itr;
3480 else
3481 ++itr;
3485 uint32 Player::resetTalentsCost() const
3487 // The first time reset costs 1 gold
3488 if(m_resetTalentsCost < 1*GOLD)
3489 return 1*GOLD;
3490 // then 5 gold
3491 else if(m_resetTalentsCost < 5*GOLD)
3492 return 5*GOLD;
3493 // After that it increases in increments of 5 gold
3494 else if(m_resetTalentsCost < 10*GOLD)
3495 return 10*GOLD;
3496 else
3498 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3499 if(months > 0)
3501 // This cost will be reduced by a rate of 5 gold per month
3502 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3503 // to a minimum of 10 gold.
3504 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3506 else
3508 // After that it increases in increments of 5 gold
3509 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3510 // until it hits a cap of 50 gold.
3511 if(new_cost > 50*GOLD)
3512 new_cost = 50*GOLD;
3513 return new_cost;
3518 bool Player::resetTalents(bool no_cost)
3520 // not need after this call
3521 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3522 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
3524 uint32 talentPointsForLevel = CalculateTalentsPoints();
3526 if (m_usedTalentCount == 0)
3528 SetFreeTalentPoints(talentPointsForLevel);
3529 return false;
3532 uint32 cost = 0;
3534 if(!no_cost)
3536 cost = resetTalentsCost();
3538 if (GetMoney() < cost)
3540 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3541 return false;
3545 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3547 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3549 if (!talentInfo) continue;
3551 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3553 if(!talentTabInfo)
3554 continue;
3556 // unlearn only talents for character class
3557 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3558 // to prevent unexpected lost normal learned spell skip another class talents
3559 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3560 continue;
3562 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3564 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3566 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3568 ++itr;
3569 continue;
3572 // remove learned spells (all ranks)
3573 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3575 // unlearn if first rank is talent or learned by talent
3576 if (itrFirstId == talentInfo->RankID[j])
3578 removeSpell(itr->first,!IsPassiveSpell(itr->first),false);
3579 itr = GetSpellMap().begin();
3580 continue;
3582 else if (spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3584 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3585 itr = GetSpellMap().begin();
3586 continue;
3588 else
3589 ++itr;
3594 SetFreeTalentPoints(talentPointsForLevel);
3596 if(!no_cost)
3598 ModifyMoney(-(int32)cost);
3599 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3600 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3602 m_resetTalentsCost = cost;
3603 m_resetTalentsTime = time(NULL);
3606 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3607 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3608 /* when prev line will dropped use next line
3609 if(Pet* pet = GetPet())
3611 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3612 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3617 if(m_canTitanGrip)
3619 m_canTitanGrip = false;
3620 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3621 AutoUnequipOffhandIfNeed();
3624 return true;
3627 Mail* Player::GetMail(uint32 id)
3629 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3631 if ((*itr)->messageID == id)
3633 return (*itr);
3636 return NULL;
3639 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3641 if(target == this)
3643 Object::_SetCreateBits(updateMask, target);
3645 else
3647 for(uint16 index = 0; index < m_valuesCount; index++)
3649 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3650 updateMask->SetBit(index);
3655 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3657 if(target == this)
3659 Object::_SetUpdateBits(updateMask, target);
3661 else
3663 Object::_SetUpdateBits(updateMask, target);
3664 *updateMask &= updateVisualBits;
3668 void Player::InitVisibleBits()
3670 updateVisualBits.SetCount(PLAYER_END);
3672 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3673 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3674 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3675 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3676 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3677 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3678 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3679 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3680 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3681 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3682 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3683 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3684 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3685 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3686 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3687 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3688 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3689 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3690 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3691 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3692 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3693 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3694 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3695 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3696 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3697 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3698 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3699 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3700 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3701 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3702 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3703 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3704 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3705 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3706 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3707 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3708 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3709 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3710 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3711 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3712 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3713 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3714 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3715 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3716 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3717 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3718 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3719 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3720 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3721 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3722 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3723 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3724 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3725 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3726 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3728 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3729 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3730 updateVisualBits.SetBit(PLAYER_FLAGS);
3731 updateVisualBits.SetBit(PLAYER_GUILDID);
3732 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3733 updateVisualBits.SetBit(PLAYER_BYTES);
3734 updateVisualBits.SetBit(PLAYER_BYTES_2);
3735 updateVisualBits.SetBit(PLAYER_BYTES_3);
3736 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3737 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3739 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3740 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3741 updateVisualBits.SetBit(i);
3743 // Players visible items are not inventory stuff
3744 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3746 uint32 offset = i * 2;
3748 // item entry
3749 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3750 // enchant
3751 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3754 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3757 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3759 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3761 if(m_items[i] == NULL)
3762 continue;
3764 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3767 if(target == this)
3769 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3771 if(m_items[i] == NULL)
3772 continue;
3774 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3776 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3778 if(m_items[i] == NULL)
3779 continue;
3781 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3785 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3788 void Player::DestroyForPlayer( Player *target, bool anim ) const
3790 Unit::DestroyForPlayer( target, anim );
3792 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3794 if(m_items[i] == NULL)
3795 continue;
3797 m_items[i]->DestroyForPlayer( target );
3800 if(target == this)
3802 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3804 if(m_items[i] == NULL)
3805 continue;
3807 m_items[i]->DestroyForPlayer( target );
3809 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3811 if(m_items[i] == NULL)
3812 continue;
3814 m_items[i]->DestroyForPlayer( target );
3819 bool Player::HasSpell(uint32 spell) const
3821 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3822 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3823 !itr->second->disabled);
3826 bool Player::HasActiveSpell(uint32 spell) const
3828 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3829 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3830 itr->second->active && !itr->second->disabled);
3833 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3835 if (!trainer_spell)
3836 return TRAINER_SPELL_RED;
3838 if (!trainer_spell->learnedSpell)
3839 return TRAINER_SPELL_RED;
3841 // known spell
3842 if(HasSpell(trainer_spell->learnedSpell))
3843 return TRAINER_SPELL_GRAY;
3845 // check race/class requirement
3846 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3847 return TRAINER_SPELL_RED;
3849 // check level requirement
3850 if(getLevel() < trainer_spell->reqLevel)
3851 return TRAINER_SPELL_RED;
3853 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3855 // check prev.rank requirement
3856 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3857 return TRAINER_SPELL_RED;
3859 // check additional spell requirement
3860 if(spell_chain->req && !HasSpell(spell_chain->req))
3861 return TRAINER_SPELL_RED;
3864 // check skill requirement
3865 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3866 return TRAINER_SPELL_RED;
3868 // exist, already checked at loading
3869 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3871 // secondary prof. or not prof. spell
3872 uint32 skill = spell->EffectMiscValue[1];
3874 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3875 return TRAINER_SPELL_GREEN;
3877 // check primary prof. limit
3878 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
3879 return TRAINER_SPELL_GREEN_DISABLED;
3881 return TRAINER_SPELL_GREEN;
3884 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3886 uint32 guid = GUID_LOPART(playerguid);
3888 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3889 // bones will be deleted by corpse/bones deleting thread shortly
3890 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3892 // remove from guild
3893 uint32 guildId = GetGuildIdFromDB(playerguid);
3894 if(guildId != 0)
3896 Guild* guild = objmgr.GetGuildById(guildId);
3897 if(guild)
3898 guild->DelMember(guid);
3901 // remove from arena teams
3902 LeaveAllArenaTeams(playerguid);
3904 // the player was uninvited already on logout so just remove from group
3905 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3906 if(resultGroup)
3908 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3909 delete resultGroup;
3910 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3911 if(group)
3913 RemoveFromGroup(group, playerguid);
3917 // remove signs from petitions (also remove petitions if owner);
3918 RemovePetitionsAndSigns(playerguid, 10);
3920 // return back all mails with COD and Item 0 1 2 3 4 5 6 7
3921 QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,messageType,mailTemplateId,sender,subject,itemTextId,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid);
3922 if(resultMail)
3926 Field *fields = resultMail->Fetch();
3928 uint32 mail_id = fields[0].GetUInt32();
3929 uint16 mailType = fields[1].GetUInt16();
3930 uint16 mailTemplateId= fields[2].GetUInt16();
3931 uint32 sender = fields[3].GetUInt32();
3932 std::string subject = fields[4].GetCppString();
3933 uint32 itemTextId = fields[5].GetUInt32();
3934 uint32 money = fields[6].GetUInt32();
3935 bool has_items = fields[7].GetBool();
3937 //we can return mail now
3938 //so firstly delete the old one
3939 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3941 // mail not from player
3942 if (mailType != MAIL_NORMAL)
3944 if(has_items)
3945 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3946 continue;
3949 MailDraft draft(subject, itemTextId);
3950 if (mailTemplateId)
3951 draft = MailDraft(mailTemplateId,false); // itesm already included
3953 if(has_items)
3955 // data needs to be at first place for Item::LoadFromDB
3956 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);
3957 if(resultItems)
3961 Field *fields2 = resultItems->Fetch();
3963 uint32 item_guidlow = fields2[1].GetUInt32();
3964 uint32 item_template = fields2[2].GetUInt32();
3966 ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_template);
3967 if(!itemProto)
3969 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3970 continue;
3973 Item *pItem = NewItemOrBag(itemProto);
3974 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3976 pItem->FSetState(ITEM_REMOVED);
3977 pItem->SaveToDB(); // it also deletes item object !
3978 continue;
3981 draft.AddItem(pItem);
3983 while (resultItems->NextRow());
3985 delete resultItems;
3989 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3991 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3993 draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender);
3995 while (resultMail->NextRow());
3997 delete resultMail;
4000 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
4001 // Get guids of character's pets, will deleted in transaction
4002 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
4004 // NOW we can finally clear other DB data related to character
4005 CharacterDatabase.BeginTransaction();
4006 if (resultPets)
4010 Field *fields3 = resultPets->Fetch();
4011 uint32 petguidlow = fields3[0].GetUInt32();
4012 Pet::DeleteFromDB(petguidlow);
4013 } while (resultPets->NextRow());
4014 delete resultPets;
4017 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
4018 CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid);
4019 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
4020 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
4021 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
4022 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
4023 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
4024 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
4025 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
4026 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
4027 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
4028 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
4029 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
4030 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
4031 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
4032 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
4033 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
4034 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
4035 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
4036 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
4037 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
4038 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
4039 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
4040 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
4041 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u'",guid);
4042 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid);
4043 CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid);
4044 CharacterDatabase.CommitTransaction();
4046 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4047 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
4050 void Player::SetMovement(PlayerMovementType pType)
4052 WorldPacket data;
4053 switch(pType)
4055 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
4056 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
4057 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
4058 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
4059 default:
4060 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
4061 return;
4063 data.append(GetPackGUID());
4064 data << uint32(0);
4065 GetSession()->SendPacket( &data );
4068 /* Preconditions:
4069 - a resurrectable corpse must not be loaded for the player (only bones)
4070 - the player must be in world
4072 void Player::BuildPlayerRepop()
4074 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
4075 data.append(GetPackGUID());
4076 GetSession()->SendPacket(&data);
4078 if(getRace() == RACE_NIGHTELF)
4079 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)
4080 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4082 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4083 // there must be SMSG.STOP_MIRROR_TIMER
4084 // there we must send 888 opcode
4086 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4087 if(GetCorpse())
4089 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4090 assert(false);
4093 // create a corpse and place it at the player's location
4094 CreateCorpse();
4095 Corpse *corpse = GetCorpse();
4096 if(!corpse)
4098 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4099 return;
4101 GetMap()->Add(corpse);
4103 // convert player body to ghost
4104 SetHealth( 1 );
4106 SetMovement(MOVE_WATER_WALK);
4107 if(!GetSession()->isLogingOut())
4108 SetMovement(MOVE_UNROOT);
4110 // BG - remove insignia related
4111 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
4113 SendCorpseReclaimDelay();
4115 // to prevent cheating
4116 corpse->ResetGhostTime();
4118 StopMirrorTimers(); //disable timers(bars)
4120 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
4122 // set and clear other
4123 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
4126 void Player::SendDelayResponse(const uint32 ml_seconds)
4128 //FIXME: is this delay time arg really need? 50msec by default in code
4129 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
4130 data << (uint32)time(NULL);
4131 data << (uint32)0;
4132 GetSession()->SendPacket( &data );
4135 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
4137 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
4138 data << uint32(-1);
4139 data << float(0);
4140 data << float(0);
4141 data << float(0);
4142 GetSession()->SendPacket(&data);
4144 // speed change, land walk
4146 // remove death flag + set aura
4147 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4148 if(getRace() == RACE_NIGHTELF)
4149 RemoveAurasDueToSpell(20584); // speed bonuses
4150 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4152 setDeathState(ALIVE);
4154 SetMovement(MOVE_LAND_WALK);
4155 SetMovement(MOVE_UNROOT);
4157 m_deathTimer = 0;
4159 // set health/powers (0- will be set in caller)
4160 if(restore_percent>0.0f)
4162 SetHealth(uint32(GetMaxHealth()*restore_percent));
4163 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4164 SetPower(POWER_RAGE, 0);
4165 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4168 // trigger update zone for alive state zone updates
4169 uint32 newzone, newarea;
4170 GetZoneAndAreaId(newzone,newarea);
4171 UpdateZone(newzone,newarea);
4173 // update visibility
4174 UpdateVisibilityForPlayer();
4176 if(!applySickness)
4177 return;
4179 //Characters from level 1-10 are not affected by resurrection sickness.
4180 //Characters from level 11-19 will suffer from one minute of sickness
4181 //for each level they are above 10.
4182 //Characters level 20 and up suffer from ten minutes of sickness.
4183 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
4185 if(int32(getLevel()) >= startLevel)
4187 // set resurrection sickness
4188 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4190 // not full duration
4191 if(int32(getLevel()) < startLevel+9)
4193 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4195 for(int i =0; i < 3; ++i)
4197 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4199 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4200 Aur->SendAuraUpdate(false);
4207 void Player::KillPlayer()
4209 SetMovement(MOVE_ROOT);
4211 StopMirrorTimers(); //disable timers(bars)
4213 setDeathState(CORPSE);
4214 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4216 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4217 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4219 // 6 minutes until repop at graveyard
4220 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4222 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4224 // don't create corpse at this moment, player might be falling
4226 // update visibility
4227 UpdateObjectVisibility();
4230 void Player::CreateCorpse()
4232 // prevent existence 2 corpse for player
4233 SpawnCorpseBones();
4235 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4237 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4238 SetPvPDeath(false);
4240 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4242 delete corpse;
4243 return;
4246 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4247 _pb = GetUInt32Value(PLAYER_BYTES);
4248 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4250 uint8 race = (uint8)(_uf);
4251 uint8 skin = (uint8)(_pb);
4252 uint8 face = (uint8)(_pb >> 8);
4253 uint8 hairstyle = (uint8)(_pb >> 16);
4254 uint8 haircolor = (uint8)(_pb >> 24);
4255 uint8 facialhair = (uint8)(_pb2);
4257 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4258 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4260 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4261 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4263 uint32 flags = CORPSE_FLAG_UNK2;
4264 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4265 flags |= CORPSE_FLAG_HIDE_HELM;
4266 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4267 flags |= CORPSE_FLAG_HIDE_CLOAK;
4268 if(InBattleGround() && !InArena())
4269 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4270 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4272 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4274 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4276 uint32 iDisplayID;
4277 uint32 iIventoryType;
4278 uint32 _cfi;
4279 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4281 if(m_items[i])
4283 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4284 iIventoryType = m_items[i]->GetProto()->InventoryType;
4286 _cfi = iDisplayID | (iIventoryType << 24);
4287 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi);
4291 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4292 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4293 assert(entry);
4294 if(entry->map_type != MAP_BATTLEGROUND)
4295 corpse->SaveToDB();
4297 // register for player, but not show
4298 ObjectAccessor::Instance().AddCorpse(corpse);
4301 void Player::SpawnCorpseBones()
4303 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4304 SaveToDB(); // prevent loading as ghost without corpse
4307 Corpse* Player::GetCorpse() const
4309 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4312 void Player::DurabilityLossAll(double percent, bool inventory)
4314 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4315 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4316 DurabilityLoss(pItem,percent);
4318 if(inventory)
4320 // bags not have durability
4321 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4323 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4324 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4325 DurabilityLoss(pItem,percent);
4327 // keys not have durability
4328 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4330 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4331 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4332 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4333 if(Item* pItem = GetItemByPos( i, j ))
4334 DurabilityLoss(pItem,percent);
4338 void Player::DurabilityLoss(Item* item, double percent)
4340 if(!item )
4341 return;
4343 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4345 if(!pMaxDurability)
4346 return;
4348 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4350 if(pDurabilityLoss < 1 )
4351 pDurabilityLoss = 1;
4353 DurabilityPointsLoss(item,pDurabilityLoss);
4356 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4358 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4359 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4360 DurabilityPointsLoss(pItem,points);
4362 if(inventory)
4364 // bags not have durability
4365 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4367 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4368 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4369 DurabilityPointsLoss(pItem,points);
4371 // keys not have durability
4372 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4374 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4375 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4376 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4377 if(Item* pItem = GetItemByPos( i, j ))
4378 DurabilityPointsLoss(pItem,points);
4382 void Player::DurabilityPointsLoss(Item* item, int32 points)
4384 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4385 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4386 int32 pNewDurability = pOldDurability - points;
4388 if (pNewDurability < 0)
4389 pNewDurability = 0;
4390 else if (pNewDurability > pMaxDurability)
4391 pNewDurability = pMaxDurability;
4393 if (pOldDurability != pNewDurability)
4395 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4396 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4397 _ApplyItemMods(item,item->GetSlot(), false);
4399 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4401 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4402 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4403 _ApplyItemMods(item,item->GetSlot(), true);
4405 item->SetState(ITEM_CHANGED, this);
4409 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4411 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4412 DurabilityPointsLoss(pItem,1);
4415 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4417 uint32 TotalCost = 0;
4418 // equipped, backpack, bags itself
4419 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4420 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4422 // bank, buyback and keys not repaired
4424 // items in inventory bags
4425 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4426 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4427 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4428 return TotalCost;
4431 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4433 Item* item = GetItemByPos(pos);
4435 uint32 TotalCost = 0;
4436 if(!item)
4437 return TotalCost;
4439 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4440 if(!maxDurability)
4441 return TotalCost;
4443 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4445 if(cost)
4447 uint32 LostDurability = maxDurability - curDurability;
4448 if(LostDurability>0)
4450 ItemPrototype const *ditemProto = item->GetProto();
4452 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4453 if(!dcost)
4455 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4456 return TotalCost;
4459 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4460 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4461 if(!dQualitymodEntry)
4463 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4464 return TotalCost;
4467 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4468 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4470 costs = uint32(costs * discountMod);
4472 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4473 costs = 1;
4475 if (guildBank)
4477 if (GetGuildId()==0)
4479 DEBUG_LOG("You are not member of a guild");
4480 return TotalCost;
4483 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4484 if (!pGuild)
4485 return TotalCost;
4487 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4489 DEBUG_LOG("You do not have rights to withdraw for repairs");
4490 return TotalCost;
4493 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4495 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4496 return TotalCost;
4499 if (pGuild->GetGuildBankMoney() < costs)
4501 DEBUG_LOG("There is not enough money in bank");
4502 return TotalCost;
4505 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4506 TotalCost = costs;
4508 else if (GetMoney() < costs)
4510 DEBUG_LOG("You do not have enough money");
4511 return TotalCost;
4513 else
4514 ModifyMoney( -int32(costs) );
4518 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4519 item->SetState(ITEM_CHANGED, this);
4521 // reapply mods for total broken and repaired item if equipped
4522 if(IsEquipmentPos(pos) && !curDurability)
4523 _ApplyItemMods(item,pos & 255, true);
4524 return TotalCost;
4527 void Player::RepopAtGraveyard()
4529 // note: this can be called also when the player is alive
4530 // for example from WorldSession::HandleMovementOpcodes
4532 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4534 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4535 if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport())
4537 ResurrectPlayer(0.5f);
4538 SpawnCorpseBones();
4541 WorldSafeLocsEntry const *ClosestGrave = NULL;
4543 // Special handle for battleground maps
4544 if( BattleGround *bg = GetBattleGround() )
4545 ClosestGrave = bg->GetClosestGraveYard(this);
4546 else
4547 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4549 // stop countdown until repop
4550 m_deathTimer = 0;
4552 // if no grave found, stay at the current location
4553 // and don't show spirit healer location
4554 if(ClosestGrave)
4556 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4557 if(isDead()) // not send if alive, because it used in TeleportTo()
4559 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4560 data << ClosestGrave->map_id;
4561 data << ClosestGrave->x;
4562 data << ClosestGrave->y;
4563 data << ClosestGrave->z;
4564 GetSession()->SendPacket(&data);
4569 void Player::JoinedChannel(Channel *c)
4571 m_channels.push_back(c);
4574 void Player::LeftChannel(Channel *c)
4576 m_channels.remove(c);
4579 void Player::CleanupChannels()
4581 while(!m_channels.empty())
4583 Channel* ch = *m_channels.begin();
4584 m_channels.erase(m_channels.begin()); // remove from player's channel list
4585 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4586 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4587 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4590 sLog.outDebug("Player: channels cleaned up!");
4593 void Player::UpdateLocalChannels(uint32 newZone )
4595 if(m_channels.empty())
4596 return;
4598 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4599 if(!current_zone)
4600 return;
4602 ChannelMgr* cMgr = channelMgr(GetTeam());
4603 if(!cMgr)
4604 return;
4606 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4608 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4610 next = i; ++next;
4612 // skip non built-in channels
4613 if(!(*i)->IsConstant())
4614 continue;
4616 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4617 if(!ch)
4618 continue;
4620 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4621 continue;
4623 // new channel
4624 char new_channel_name_buf[100];
4625 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4626 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4628 if((*i)!=new_channel)
4630 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4632 // leave old channel
4633 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4634 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4635 LeftChannel(*i); // remove from player's channel list
4636 cMgr->LeftChannel(name); // delete if empty
4639 sLog.outDebug("Player: channels cleaned up!");
4642 void Player::LeaveLFGChannel()
4644 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4646 if((*i)->IsLFG())
4648 (*i)->Leave(GetGUID());
4649 break;
4654 void Player::UpdateDefense()
4656 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4658 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4660 // update dependent from defense skill part
4661 UpdateDefenseBonusesMod();
4665 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4667 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4669 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4670 return;
4673 float val = 1.0f;
4675 switch(modType)
4677 case FLAT_MOD:
4678 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4679 break;
4680 case PCT_MOD:
4681 if(amount <= -100.0f)
4682 amount = -200.0f;
4684 val = (100.0f + amount) / 100.0f;
4685 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4686 break;
4689 if(!CanModifyStats())
4690 return;
4692 switch(modGroup)
4694 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4695 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4696 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4697 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4698 default: break;
4702 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4704 if(modGroup >= BASEMOD_END || modType > MOD_END)
4706 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4707 return 0.0f;
4710 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4711 return 0.0f;
4713 return m_auraBaseMod[modGroup][modType];
4716 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4718 if(modGroup >= BASEMOD_END)
4720 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4721 return 0.0f;
4724 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4725 return 0.0f;
4727 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4730 uint32 Player::GetShieldBlockValue() const
4732 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4734 value = (value < 0) ? 0 : value;
4736 return uint32(value);
4739 float Player::GetMeleeCritFromAgility()
4741 uint32 level = getLevel();
4742 uint32 pclass = getClass();
4744 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4746 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4747 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4748 if (critBase==NULL || critRatio==NULL)
4749 return 0.0f;
4751 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4752 return crit*100.0f;
4755 float Player::GetDodgeFromAgility()
4757 // Table for base dodge values
4758 float dodge_base[MAX_CLASSES] = {
4759 0.0075f, // Warrior
4760 0.00652f, // Paladin
4761 -0.0545f, // Hunter
4762 -0.0059f, // Rogue
4763 0.03183f, // Priest
4764 0.0114f, // DK
4765 0.0167f, // Shaman
4766 0.034575f, // Mage
4767 0.02011f, // Warlock
4768 0.0f, // ??
4769 -0.0187f // Druid
4771 // Crit/agility to dodge/agility coefficient multipliers
4772 float crit_to_dodge[MAX_CLASSES] = {
4773 1.1f, // Warrior
4774 1.0f, // Paladin
4775 1.6f, // Hunter
4776 2.0f, // Rogue
4777 1.0f, // Priest
4778 1.0f, // DK?
4779 1.0f, // Shaman
4780 1.0f, // Mage
4781 1.0f, // Warlock
4782 0.0f, // ??
4783 1.7f // Druid
4786 uint32 level = getLevel();
4787 uint32 pclass = getClass();
4789 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4791 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4792 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4793 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4794 return 0.0f;
4796 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4797 return dodge*100.0f;
4800 float Player::GetSpellCritFromIntellect()
4802 uint32 level = getLevel();
4803 uint32 pclass = getClass();
4805 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4807 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4808 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4809 if (critBase==NULL || critRatio==NULL)
4810 return 0.0f;
4812 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4813 return crit*100.0f;
4816 float Player::GetRatingCoefficient(CombatRating cr) const
4818 uint32 level = getLevel();
4820 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4822 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4823 if (Rating == NULL)
4824 return 1.0f; // By default use minimum coefficient (not must be called)
4826 return Rating->ratio;
4829 float Player::GetRatingBonusValue(CombatRating cr) const
4831 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4834 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4836 switch (attType)
4838 case BASE_ATTACK:
4839 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4840 case OFF_ATTACK:
4841 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4842 default:
4843 break;
4845 return 0.0f;
4848 float Player::OCTRegenHPPerSpirit()
4850 uint32 level = getLevel();
4851 uint32 pclass = getClass();
4853 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4855 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4856 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4857 if (baseRatio==NULL || moreRatio==NULL)
4858 return 0.0f;
4860 // Formula from PaperDollFrame script
4861 float spirit = GetStat(STAT_SPIRIT);
4862 float baseSpirit = spirit;
4863 if (baseSpirit>50) baseSpirit = 50;
4864 float moreSpirit = spirit - baseSpirit;
4865 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4866 return regen;
4869 float Player::OCTRegenMPPerSpirit()
4871 uint32 level = getLevel();
4872 uint32 pclass = getClass();
4874 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4876 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4877 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4878 if (moreRatio==NULL)
4879 return 0.0f;
4881 // Formula get from PaperDollFrame script
4882 float spirit = GetStat(STAT_SPIRIT);
4883 float regen = spirit * moreRatio->ratio;
4884 return regen;
4887 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4889 m_baseRatingValue[cr]+=(apply ? value : -value);
4891 int32 amount = uint32(m_baseRatingValue[cr]);
4892 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4893 // stat used stored in miscValueB for this aura
4894 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4895 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4896 if ((*i)->GetMiscValue() & (1<<cr))
4897 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4898 if (amount < 0)
4899 amount = 0;
4900 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4902 float RatingCoeffecient = GetRatingCoefficient(cr);
4903 float RatingChange = 0.0f;
4905 bool affectStats = CanModifyStats();
4907 switch (cr)
4909 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4910 case CR_DEFENSE_SKILL:
4911 UpdateDefenseBonusesMod();
4912 break;
4913 case CR_DODGE:
4914 UpdateDodgePercentage();
4915 break;
4916 case CR_PARRY:
4917 UpdateParryPercentage();
4918 break;
4919 case CR_BLOCK:
4920 UpdateBlockPercentage();
4921 break;
4922 case CR_HIT_MELEE:
4923 UpdateMeleeHitChances();
4924 break;
4925 case CR_HIT_RANGED:
4926 UpdateRangedHitChances();
4927 break;
4928 case CR_HIT_SPELL:
4929 UpdateSpellHitChances();
4930 break;
4931 case CR_CRIT_MELEE:
4932 if(affectStats)
4934 UpdateCritPercentage(BASE_ATTACK);
4935 UpdateCritPercentage(OFF_ATTACK);
4937 break;
4938 case CR_CRIT_RANGED:
4939 if(affectStats)
4940 UpdateCritPercentage(RANGED_ATTACK);
4941 break;
4942 case CR_CRIT_SPELL:
4943 if(affectStats)
4944 UpdateAllSpellCritChances();
4945 break;
4946 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4947 case CR_HIT_TAKEN_RANGED:
4948 break;
4949 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4950 break;
4951 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4952 case CR_CRIT_TAKEN_RANGED:
4953 break;
4954 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4955 break;
4956 case CR_HASTE_MELEE:
4957 RatingChange = value / RatingCoeffecient;
4958 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4959 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4960 break;
4961 case CR_HASTE_RANGED:
4962 RatingChange = value / RatingCoeffecient;
4963 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4964 break;
4965 case CR_HASTE_SPELL:
4966 RatingChange = value / RatingCoeffecient;
4967 ApplyCastTimePercentMod(RatingChange,apply);
4968 break;
4969 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4970 case CR_WEAPON_SKILL_OFFHAND:
4971 case CR_WEAPON_SKILL_RANGED:
4972 break;
4973 case CR_EXPERTISE:
4974 if(affectStats)
4976 UpdateExpertise(BASE_ATTACK);
4977 UpdateExpertise(OFF_ATTACK);
4979 break;
4980 case CR_ARMOR_PENETRATION:
4981 if(affectStats)
4982 UpdateArmorPenetration();
4983 break;
4987 void Player::SetRegularAttackTime()
4989 for(int i = 0; i < MAX_ATTACK; ++i)
4991 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4992 if(tmpitem && !tmpitem->IsBroken())
4994 ItemPrototype const *proto = tmpitem->GetProto();
4995 if(proto->Delay)
4996 SetAttackTime(WeaponAttackType(i), proto->Delay);
4997 else
4998 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
5003 //skill+step, checking for max value
5004 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
5006 if(!skill_id)
5007 return false;
5009 uint16 i=0;
5010 for (; i < PLAYER_MAX_SKILLS; ++i)
5011 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
5012 break;
5014 if(i>=PLAYER_MAX_SKILLS)
5015 return false;
5017 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5018 uint32 value = SKILL_VALUE(data);
5019 uint32 max = SKILL_MAX(data);
5021 if ((!max) || (!value) || (value >= max))
5022 return false;
5024 if (value*512 < max*urand(0,512))
5026 uint32 new_value = value+step;
5027 if(new_value > max)
5028 new_value = max;
5030 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
5031 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
5032 return true;
5035 return false;
5038 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
5040 if ( SkillValue >= GrayLevel )
5041 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
5042 if ( SkillValue >= GreenLevel )
5043 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
5044 if ( SkillValue >= YellowLevel )
5045 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
5046 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
5049 bool Player::UpdateCraftSkill(uint32 spellid)
5051 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
5053 SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spellid);
5055 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
5057 if (_spell_idx->second->skillId)
5059 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
5061 // Alchemy Discoveries here
5062 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
5063 if (spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
5065 if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
5066 learnSpell(discoveredSpell,false);
5069 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
5071 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
5072 _spell_idx->second->max_value,
5073 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
5074 _spell_idx->second->min_value),
5075 craft_skill_gain);
5078 return false;
5081 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
5083 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
5085 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5087 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5088 switch (SkillId)
5090 case SKILL_HERBALISM:
5091 case SKILL_LOCKPICKING:
5092 case SKILL_JEWELCRAFTING:
5093 case SKILL_INSCRIPTION:
5094 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5095 case SKILL_SKINNING:
5096 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
5097 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5098 else
5099 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
5100 case SKILL_MINING:
5101 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
5102 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5103 else
5104 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
5106 return false;
5109 bool Player::UpdateFishingSkill()
5111 sLog.outDebug("UpdateFishingSkill");
5113 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5115 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5117 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5119 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5122 // levels sync. with spell requirement for skill levels to learn
5123 // bonus abilities in sSkillLineAbilityStore
5124 // Used only to avoid scan DBC at each skill grow
5125 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5127 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5129 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5130 if ( !SkillId )
5131 return false;
5133 if(Chance <= 0) // speedup in 0 chance case
5135 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5136 return false;
5139 uint16 i=0;
5140 for (; i < PLAYER_MAX_SKILLS; ++i)
5141 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
5142 if ( i >= PLAYER_MAX_SKILLS )
5143 return false;
5145 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5146 uint16 SkillValue = SKILL_VALUE(data);
5147 uint16 MaxValue = SKILL_MAX(data);
5149 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5150 return false;
5152 int32 Roll = irand(1,1000);
5154 if ( Roll <= Chance )
5156 uint32 new_value = SkillValue+step;
5157 if(new_value > MaxValue)
5158 new_value = MaxValue;
5160 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
5161 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5163 if((SkillValue < *bsl && new_value >= *bsl))
5165 learnSkillRewardedSpells( SkillId, new_value);
5166 break;
5169 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5170 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5171 return true;
5174 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5175 return false;
5178 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5180 // no skill gain in pvp
5181 Unit *pVictim = getVictim();
5182 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5183 return;
5185 if(IsInFeralForm())
5186 return; // always maximized SKILL_FERAL_COMBAT in fact
5188 if(m_form == FORM_TREE)
5189 return; // use weapon but not skill up
5191 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5193 switch(attType)
5195 case BASE_ATTACK:
5197 Item *tmpitem = GetWeaponForAttack(attType,true);
5199 if (!tmpitem)
5200 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5201 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5202 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5203 break;
5205 case OFF_ATTACK:
5206 case RANGED_ATTACK:
5208 Item *tmpitem = GetWeaponForAttack(attType,true);
5209 if (tmpitem)
5210 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5211 break;
5214 UpdateAllCritPercentages();
5217 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5219 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5220 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5221 uint32 moblevel = pVictim->getLevelForTarget(this);
5222 if(moblevel < greylevel)
5223 return;
5225 if (moblevel > plevel + 5)
5226 moblevel = plevel + 5;
5228 uint32 lvldif = moblevel - greylevel;
5229 if(lvldif < 3)
5230 lvldif = 3;
5232 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5233 if(skilldif <= 0)
5234 return;
5236 float chance = float(3 * lvldif * skilldif) / plevel;
5237 if(!defence)
5239 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5240 chance *= 0.1f * GetStat(STAT_INTELLECT);
5243 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5245 if(roll_chance_f(chance))
5247 if(defence)
5248 UpdateDefense();
5249 else
5250 UpdateWeaponSkill(attType);
5252 else
5253 return;
5256 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5258 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5259 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5261 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5262 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5263 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5265 if(talent) // permanent bonus stored in high part
5266 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5267 else // temporary/item bonus stored in low part
5268 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5269 return;
5273 void Player::UpdateSkillsForLevel()
5275 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5276 uint32 maxSkill = GetMaxSkillValueForLevel();
5278 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5280 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5281 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5283 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5285 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5286 if(!pSkill)
5287 continue;
5289 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5290 continue;
5292 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5293 uint32 max = SKILL_MAX(data);
5294 uint32 val = SKILL_VALUE(data);
5296 /// update only level dependent max skill values
5297 if(max!=1)
5299 /// miximize skill always
5300 if(alwaysMaxSkill)
5301 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5302 /// update max skill value if current max skill not maximized
5303 else if(max != maxconfskill)
5304 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5309 void Player::UpdateSkillsToMaxSkillsForLevel()
5311 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5312 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5314 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5315 if( IsProfessionOrRidingSkill(pskill))
5316 continue;
5317 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5319 uint32 max = SKILL_MAX(data);
5321 if(max > 1)
5322 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5324 if(pskill == SKILL_DEFENSE)
5325 UpdateDefenseBonusesMod();
5329 // This functions sets a skill line value (and adds if doesn't exist yet)
5330 // To "remove" a skill line, set it's values to zero
5331 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5333 if(!id)
5334 return;
5336 uint16 i=0;
5337 for (; i < PLAYER_MAX_SKILLS; ++i)
5338 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5340 if(i<PLAYER_MAX_SKILLS) //has skill
5342 if(currVal)
5344 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5345 learnSkillRewardedSpells(id, currVal);
5346 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5347 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5349 else //remove
5351 // clear skill fields
5352 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5353 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5354 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5356 // remove all spells that related to this skill
5357 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5358 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5359 if (pAbility->skillId==id)
5360 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5363 else if(currVal) //add
5365 for (i=0; i < PLAYER_MAX_SKILLS; ++i)
5366 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5368 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5369 if(!pSkill)
5371 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5372 return;
5374 // enable unlearn button for primary professions only
5375 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5376 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5377 else
5378 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5379 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5380 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5381 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5383 // apply skill bonuses
5384 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5386 // temporary bonuses
5387 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5388 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5389 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5390 (*j)->ApplyModifier(true);
5392 // permanent bonuses
5393 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5394 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5395 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5396 (*j)->ApplyModifier(true);
5398 // Learn all spells for skill
5399 learnSkillRewardedSpells(id, currVal);
5400 return;
5405 bool Player::HasSkill(uint32 skill) const
5407 if(!skill)return false;
5408 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5410 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5412 return true;
5415 return false;
5418 uint16 Player::GetSkillValue(uint32 skill) const
5420 if(!skill)
5421 return 0;
5423 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5425 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5427 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5429 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5430 result += SKILL_TEMP_BONUS(bonus);
5431 result += SKILL_PERM_BONUS(bonus);
5432 return result < 0 ? 0 : result;
5435 return 0;
5438 uint16 Player::GetMaxSkillValue(uint32 skill) const
5440 if(!skill)return 0;
5441 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5443 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5445 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5447 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5448 result += SKILL_TEMP_BONUS(bonus);
5449 result += SKILL_PERM_BONUS(bonus);
5450 return result < 0 ? 0 : result;
5453 return 0;
5456 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5458 if(!skill)return 0;
5459 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5461 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5463 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5466 return 0;
5469 uint16 Player::GetBaseSkillValue(uint32 skill) const
5471 if(!skill)return 0;
5472 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5474 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5476 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5477 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5478 return result < 0 ? 0 : result;
5481 return 0;
5484 uint16 Player::GetPureSkillValue(uint32 skill) const
5486 if(!skill)return 0;
5487 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5489 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5491 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5494 return 0;
5497 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5499 if(!skill)
5500 return 0;
5502 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5504 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5506 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5510 return 0;
5513 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5515 if(!skill)
5516 return 0;
5518 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5520 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5522 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5526 return 0;
5529 void Player::SendInitialActionButtons() const
5531 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5533 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5534 data << uint8(0); // can be 0, 1, 2 (talent spec)
5535 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5537 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5538 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5539 data << uint32(itr->second.packedData);
5540 else
5541 data << uint32(0);
5544 GetSession()->SendPacket( &data );
5545 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5548 ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type)
5550 if(button >= MAX_ACTION_BUTTONS)
5552 sLog.outError( "Action %u not added into button %u for player %s: button must be < 144", action, button, GetName() );
5553 return NULL;
5556 if(action >= MAX_ACTION_BUTTON_ACTION_VALUE)
5558 sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, GetName(), MAX_ACTION_BUTTON_ACTION_VALUE );
5559 return NULL;
5562 switch(type)
5564 case ACTION_BUTTON_SPELL:
5565 if(!sSpellStore.LookupEntry(action))
5567 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5568 return NULL;
5571 if(!HasSpell(action))
5573 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5574 return NULL;
5576 break;
5577 case ACTION_BUTTON_ITEM:
5578 if(!ObjectMgr::GetItemPrototype(action))
5580 sLog.outError( "Action %u not added into button %u for player %s: item not exist", action, button, GetName() );
5581 return NULL;
5583 break;
5584 default:
5585 break; // pther cases not checked at this moment
5589 // it create new button (NEW state) if need or return existed
5590 ActionButton& ab = m_actionButtons[button];
5592 // set data and update to CHANGED if not NEW
5593 ab.SetActionAndType(action,ActionButtonType(type));
5595 sLog.outDetail( "Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUIDLow(), action, uint32(type), button );
5596 return &ab;
5599 void Player::removeActionButton(uint8 button)
5601 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5602 if (buttonItr==m_actionButtons.end())
5603 return;
5605 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5606 m_actionButtons.erase(buttonItr); // new and not saved
5607 else
5608 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5610 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5613 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5615 // prevent crash when a bad coord is sent by the client
5616 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5618 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5619 return false;
5622 Map *m = GetMap();
5624 const float old_x = GetPositionX();
5625 const float old_y = GetPositionY();
5626 const float old_z = GetPositionZ();
5627 const float old_r = GetOrientation();
5629 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5631 if (teleport || old_x != x || old_y != y || old_z != z)
5632 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5633 else
5634 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5636 // move and update visible state if need
5637 m->PlayerRelocation(this, x, y, z, orientation);
5639 // reread after Map::Relocation
5640 m = GetMap();
5641 x = GetPositionX();
5642 y = GetPositionY();
5643 z = GetPositionZ();
5645 // group update
5646 if(GetGroup() && (old_x != x || old_y != y))
5647 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5650 // code block for underwater state update
5651 UpdateUnderwaterState(m, x, y, z);
5653 CheckExploreSystem();
5655 return true;
5658 void Player::SaveRecallPosition()
5660 m_recallMap = GetMapId();
5661 m_recallX = GetPositionX();
5662 m_recallY = GetPositionY();
5663 m_recallZ = GetPositionZ();
5664 m_recallO = GetOrientation();
5667 void Player::SendMessageToSet(WorldPacket *data, bool self)
5669 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5670 if(_map)
5672 _map->MessageBroadcast(this, data, self);
5673 return;
5676 //if player is not in world and map in not created/already destroyed
5677 //no need to create one, just send packet for itself!
5678 if(self)
5679 GetSession()->SendPacket(data);
5682 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5684 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5685 if(_map)
5687 _map->MessageDistBroadcast(this, data, dist, self);
5688 return;
5691 if(self)
5692 GetSession()->SendPacket(data);
5695 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5697 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5698 if(_map)
5700 _map->MessageDistBroadcast(this, data, dist, self, own_team_only);
5701 return;
5704 if(self)
5705 GetSession()->SendPacket(data);
5708 void Player::SendDirectMessage(WorldPacket *data)
5710 GetSession()->SendPacket(data);
5713 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5715 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5716 data << uint32(CinematicSequenceId);
5717 SendDirectMessage(&data);
5720 void Player::SendMovieStart(uint32 MovieId)
5722 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5723 data << uint32(MovieId);
5724 SendDirectMessage(&data);
5727 void Player::CheckExploreSystem()
5729 if (!isAlive())
5730 return;
5732 if (isInFlight())
5733 return;
5735 uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5736 if(areaFlag==0xffff)
5737 return;
5738 int offset = areaFlag / 32;
5740 if(offset >= 128)
5742 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);
5743 return;
5746 uint32 val = (uint32)(1 << (areaFlag % 32));
5747 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5749 if( !(currFields & val) )
5751 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5753 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5755 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5756 if(!p)
5758 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5760 else if(p->area_level > 0)
5762 uint32 area = p->ID;
5763 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5765 SendExplorationExperience(area,0);
5767 else
5769 int32 diff = int32(getLevel()) - p->area_level;
5770 uint32 XP = 0;
5771 if (diff < -5)
5773 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5775 else if (diff > 5)
5777 int32 exploration_percent = (100-((diff-5)*5));
5778 if (exploration_percent > 100)
5779 exploration_percent = 100;
5780 else if (exploration_percent < 0)
5781 exploration_percent = 0;
5783 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5785 else
5787 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5790 GiveXP( XP, NULL );
5791 SendExplorationExperience(area,XP);
5793 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5798 uint32 Player::TeamForRace(uint8 race)
5800 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5801 if(!rEntry)
5803 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5804 return ALLIANCE;
5807 switch(rEntry->TeamID)
5809 case 7: return ALLIANCE;
5810 case 1: return HORDE;
5813 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5814 return ALLIANCE;
5817 uint32 Player::getFactionForRace(uint8 race)
5819 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5820 if(!rEntry)
5822 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5823 return 0;
5826 return rEntry->FactionID;
5829 void Player::setFactionForRace(uint8 race)
5831 m_team = TeamForRace(race);
5832 setFaction( getFactionForRace(race) );
5835 ReputationRank Player::GetReputationRank(uint32 faction) const
5837 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5838 return GetReputationMgr().GetRank(factionEntry);
5841 //Calculate total reputation percent player gain with quest/creature level
5842 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5844 float percent = 100.0f;
5846 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5848 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5849 percent *= rate;
5851 float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5853 if (!for_quest)
5854 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
5856 percent += rep > 0 ? repMod : -repMod;
5858 if (percent <= 0.0f)
5859 return 0;
5861 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100.0f);
5864 //Calculates how many reputation points player gains in victim's enemy factions
5865 void Player::RewardReputation(Unit *pVictim, float rate)
5867 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5868 return;
5870 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5872 if(!Rep)
5873 return;
5875 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5877 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
5878 donerep1 = int32(donerep1*rate);
5879 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5880 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5881 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5882 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5884 // Wiki: Team factions value divided by 2
5885 if (factionEntry1 && Rep->is_teamaward1)
5887 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5888 if(team1_factionEntry)
5889 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5893 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5895 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
5896 donerep2 = int32(donerep2*rate);
5897 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5898 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5899 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5900 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5902 // Wiki: Team factions value divided by 2
5903 if (factionEntry2 && Rep->is_teamaward2)
5905 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5906 if(team2_factionEntry)
5907 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5912 //Calculate how many reputation points player gain with the quest
5913 void Player::RewardReputation(Quest const *pQuest)
5915 // quest reputation reward/loss
5916 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5918 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5920 int32 rep = CalculateReputationGain(GetQuestLevelForPlayer(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
5921 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5922 if(factionEntry)
5923 GetReputationMgr().ModifyReputation(factionEntry, rep);
5927 // TODO: implement reputation spillover
5930 void Player::UpdateArenaFields(void)
5932 /* arena calcs go here */
5935 void Player::UpdateHonorFields()
5937 /// called when rewarding honor and at each save
5938 uint64 now = time(NULL);
5939 uint64 today = uint64(time(NULL) / DAY) * DAY;
5941 if(m_lastHonorUpdateTime < today)
5943 uint64 yesterday = today - DAY;
5945 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5947 // update yesterday's contribution
5948 if(m_lastHonorUpdateTime >= yesterday )
5950 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5952 // this is the first update today, reset today's contribution
5953 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5954 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5956 else
5958 // no honor/kills yesterday or today, reset
5959 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5960 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5964 m_lastHonorUpdateTime = now;
5967 ///Calculate the amount of honor gained based on the victim
5968 ///and the size of the group for which the honor is divided
5969 ///An exact honor value can also be given (overriding the calcs)
5970 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5972 // do not reward honor in arenas, but enable onkill spellproc
5973 if(InArena())
5975 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5976 return false;
5978 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5979 return false;
5981 return true;
5984 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5985 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5986 return false;
5988 uint64 victim_guid = 0;
5989 uint32 victim_rank = 0;
5991 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5992 UpdateHonorFields();
5994 if(honor <= 0)
5996 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5997 return false;
5999 victim_guid = uVictim->GetGUID();
6001 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6003 Player *pVictim = (Player *)uVictim;
6005 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6006 return false;
6008 float f = 1; //need for total kills (?? need more info)
6009 uint32 k_grey = 0;
6010 uint32 k_level = getLevel();
6011 uint32 v_level = pVictim->getLevel();
6014 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6015 // [0] Just name
6016 // [1..14] Alliance honor titles and player name
6017 // [15..28] Horde honor titles and player name
6018 // [29..38] Other title and player name
6019 // [39+] Nothing
6020 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6021 // Get Killer titles, CharTitlesEntry::bit_index
6022 // Ranks:
6023 // title[1..14] -> rank[5..18]
6024 // title[15..28] -> rank[5..18]
6025 // title[other] -> 0
6026 if (victim_title == 0)
6027 victim_guid = 0; // Don't show HK: <rank> message, only log.
6028 else if (victim_title < 15)
6029 victim_rank = victim_title + 4;
6030 else if (victim_title < 29)
6031 victim_rank = victim_title - 14 + 4;
6032 else
6033 victim_guid = 0; // Don't show HK: <rank> message, only log.
6036 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6038 if(v_level<=k_grey)
6039 return false;
6041 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6043 int32 v_rank =1; //need more info
6045 honor = ((f * diff_level * (190 + v_rank*10))/6);
6046 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6048 // count the number of playerkills in one day
6049 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6050 // and those in a lifetime
6051 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6052 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
6053 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
6054 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
6056 else
6058 Creature *cVictim = (Creature *)uVictim;
6060 if (!cVictim->isRacialLeader())
6061 return false;
6063 honor = 100; // ??? need more info
6064 victim_rank = 19; // HK: Leader
6068 if (uVictim != NULL)
6070 honor *= sWorld.getRate(RATE_HONOR);
6071 honor *= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN) + 100.0f)/100.0f;
6073 if(groupsize > 1)
6074 honor /= groupsize;
6076 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6079 // honor - for show honor points in log
6080 // victim_guid - for show victim name in log
6081 // victim_rank [1..4] HK: <dishonored rank>
6082 // victim_rank [5..19] HK: <alliance\horde rank>
6083 // victim_rank [0,20+] HK: <>
6084 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6085 data << (uint32) honor;
6086 data << (uint64) victim_guid;
6087 data << (uint32) victim_rank;
6089 GetSession()->SendPacket(&data);
6091 // add honor points
6092 ModifyHonorPoints(int32(honor));
6094 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6095 return true;
6098 void Player::ModifyHonorPoints( int32 value )
6100 if(value < 0)
6102 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6103 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6104 else
6105 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6107 else
6108 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6111 void Player::ModifyArenaPoints( int32 value )
6113 if(value < 0)
6115 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6116 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6117 else
6118 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6120 else
6121 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6124 uint32 Player::GetGuildIdFromDB(uint64 guid)
6126 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6127 if(!result)
6128 return 0;
6130 uint32 id = result->Fetch()[0].GetUInt32();
6131 delete result;
6132 return id;
6135 uint32 Player::GetRankFromDB(uint64 guid)
6137 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6138 if( result )
6140 uint32 v = result->Fetch()[0].GetUInt32();
6141 delete result;
6142 return v;
6144 else
6145 return 0;
6148 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6150 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);
6151 if(!result)
6152 return 0;
6154 uint32 id = (*result)[0].GetUInt32();
6155 delete result;
6156 return id;
6159 uint32 Player::GetZoneIdFromDB(uint64 guid)
6161 uint32 guidLow = GUID_LOPART(guid);
6162 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6163 if (!result)
6164 return 0;
6165 Field* fields = result->Fetch();
6166 uint32 zone = fields[0].GetUInt32();
6167 delete result;
6169 if (!zone)
6171 // stored zone is zero, use generic and slow zone detection
6172 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6173 if( !result )
6174 return 0;
6175 fields = result->Fetch();
6176 uint32 map = fields[0].GetUInt32();
6177 float posx = fields[1].GetFloat();
6178 float posy = fields[2].GetFloat();
6179 float posz = fields[3].GetFloat();
6180 delete result;
6182 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6184 if (zone > 0)
6185 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6188 return zone;
6191 uint32 Player::GetLevelFromDB(uint64 guid)
6193 QueryResult *result = CharacterDatabase.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid) );
6194 if (!result)
6195 return 0;
6197 Field* fields = result->Fetch();
6198 uint32 level = fields[0].GetUInt32();
6199 delete result;
6201 return level;
6204 void Player::UpdateArea(uint32 newArea)
6206 // FFA_PVP flags are area and not zone id dependent
6207 // so apply them accordingly
6208 m_areaUpdateId = newArea;
6210 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6212 if(area && (area->flags & AREA_FLAG_ARENA))
6214 if(!isGameMaster())
6215 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6217 else
6219 // remove ffa flag only if not ffapvp realm
6220 // removal in sanctuaries and capitals is handled in zone update
6221 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6222 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6225 UpdateAreaDependentAuras(newArea);
6228 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6230 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6231 if(!zone)
6232 return;
6234 if(m_zoneUpdateId != newZone)
6236 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6238 if (sWorld.getConfig(CONFIG_WEATHER))
6240 if(Weather *wth = sWorld.FindWeather(zone->ID))
6241 wth->SendWeatherUpdateToPlayer(this);
6242 else if(!sWorld.AddWeather(zone->ID))
6244 // send fine weather packet to remove old zone's weather
6245 Weather::SendFineWeatherUpdateToPlayer(this);
6250 m_zoneUpdateId = newZone;
6251 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6253 // zone changed, so area changed as well, update it
6254 UpdateArea(newArea);
6256 // in PvP, any not controlled zone (except zone->team == 6, default case)
6257 // in PvE, only opposition team capital
6258 switch(zone->team)
6260 case AREATEAM_ALLY:
6261 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6262 break;
6263 case AREATEAM_HORDE:
6264 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6265 break;
6266 case AREATEAM_NONE:
6267 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6268 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6269 break;
6270 default: // 6 in fact
6271 pvpInfo.inHostileArea = false;
6272 break;
6275 if(pvpInfo.inHostileArea) // in hostile area
6277 if(!IsPvP() || pvpInfo.endTimer != 0)
6278 UpdatePvP(true, true);
6280 else // in friendly area
6282 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6283 pvpInfo.endTimer = time(0); // start toggle-off
6286 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6288 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6289 if(sWorld.IsFFAPvPRealm())
6290 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6292 else
6294 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6297 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6299 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6300 SetRestType(REST_TYPE_IN_CITY);
6301 InnEnter(time(0),GetMapId(),0,0,0);
6303 if(sWorld.IsFFAPvPRealm())
6304 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6306 else // anywhere else
6308 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6310 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6312 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6314 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6315 SetRestType(REST_TYPE_NO);
6317 if(sWorld.IsFFAPvPRealm())
6318 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6321 else // not in tavern (leave city then)
6323 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6324 SetRestType(REST_TYPE_NO);
6326 // Set player to FFA PVP when not in rested environment.
6327 if(sWorld.IsFFAPvPRealm())
6328 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6333 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6334 // if player resurrected at teleport this will be applied in resurrect code
6335 if(isAlive())
6336 DestroyZoneLimitedItem( true, newZone );
6338 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6339 AutoUnequipOffhandIfNeed();
6341 // recent client version not send leave/join channel packets for built-in local channels
6342 UpdateLocalChannels( newZone );
6344 // group update
6345 if(GetGroup())
6346 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6348 UpdateZoneDependentAuras(newZone);
6351 //If players are too far way of duel flag... then player loose the duel
6352 void Player::CheckDuelDistance(time_t currTime)
6354 if(!duel)
6355 return;
6357 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6358 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6359 if(!obj)
6360 return;
6362 if(duel->outOfBound == 0)
6364 if(!IsWithinDistInMap(obj, 50))
6366 duel->outOfBound = currTime;
6368 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6369 GetSession()->SendPacket(&data);
6372 else
6374 if(IsWithinDistInMap(obj, 40))
6376 duel->outOfBound = 0;
6378 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6379 GetSession()->SendPacket(&data);
6381 else if(currTime >= (duel->outOfBound+10))
6383 DuelComplete(DUEL_FLED);
6388 void Player::DuelComplete(DuelCompleteType type)
6390 // duel not requested
6391 if(!duel)
6392 return;
6394 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6395 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6396 GetSession()->SendPacket(&data);
6397 duel->opponent->GetSession()->SendPacket(&data);
6399 if(type != DUEL_INTERUPTED)
6401 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6402 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6403 data << duel->opponent->GetName();
6404 data << GetName();
6405 SendMessageToSet(&data,true);
6408 if (type == DUEL_WON)
6410 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6411 if (duel->opponent)
6412 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6415 //Remove Duel Flag object
6416 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6417 if(obj)
6418 duel->initiator->RemoveGameObject(obj,true);
6420 /* remove auras */
6421 std::vector<uint32> auras2remove;
6422 AuraMap const& vAuras = duel->opponent->GetAuras();
6423 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6425 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6426 auras2remove.push_back(i->second->GetId());
6429 for(size_t i=0; i<auras2remove.size(); ++i)
6430 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6432 auras2remove.clear();
6433 AuraMap const& auras = GetAuras();
6434 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6436 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6437 auras2remove.push_back(i->second->GetId());
6439 for(size_t i=0; i<auras2remove.size(); ++i)
6440 RemoveAurasDueToSpell(auras2remove[i]);
6442 // cleanup combo points
6443 if(GetComboTarget()==duel->opponent->GetGUID())
6444 ClearComboPoints();
6445 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6446 ClearComboPoints();
6448 if(duel->opponent->GetComboTarget()==GetGUID())
6449 duel->opponent->ClearComboPoints();
6450 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6451 duel->opponent->ClearComboPoints();
6453 //cleanups
6454 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6455 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6456 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6457 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6459 delete duel->opponent->duel;
6460 duel->opponent->duel = NULL;
6461 delete duel;
6462 duel = NULL;
6465 //---------------------------------------------------------//
6467 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6469 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6470 return;
6472 // not apply/remove mods for broken item
6473 if(item->IsBroken())
6474 return;
6476 ItemPrototype const *proto = item->GetProto();
6478 if(!proto)
6479 return;
6481 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6483 uint32 attacktype = Player::GetAttackBySlot(slot);
6484 if(attacktype < MAX_ATTACK)
6485 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6487 _ApplyItemBonuses(proto,slot,apply);
6489 if( slot==EQUIPMENT_SLOT_RANGED )
6490 _ApplyAmmoBonuses();
6492 ApplyItemEquipSpell(item,apply);
6493 ApplyEnchantment(item, apply);
6495 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6496 CorrectMetaGemEnchants(slot, apply);
6498 sLog.outDebug("_ApplyItemMods complete.");
6501 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
6503 if (slot >= INVENTORY_SLOT_BAG_END || !proto)
6504 return;
6506 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
6507 if (only_level_scale && !ssd)
6508 return;
6510 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6511 uint32 ssd_level = getLevel();
6512 if (ssd && ssd_level > ssd->MaxLevel)
6513 ssd_level = ssd->MaxLevel;
6515 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
6516 if (only_level_scale && !ssv)
6517 return;
6519 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6521 uint32 statType = 0;
6522 int32 val = 0;
6523 // If set ScalingStatDistribution need get stats and values from it
6524 if (ssd && ssv)
6526 if (ssd->StatMod[i] < 0)
6527 continue;
6528 statType = ssd->StatMod[i];
6529 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6531 else
6533 if (i >= proto->StatsCount)
6534 continue;
6535 statType = proto->ItemStat[i].ItemStatType;
6536 val = proto->ItemStat[i].ItemStatValue;
6539 if(val == 0)
6540 continue;
6542 switch (statType)
6544 case ITEM_MOD_MANA:
6545 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6546 break;
6547 case ITEM_MOD_HEALTH: // modify HP
6548 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6549 break;
6550 case ITEM_MOD_AGILITY: // modify agility
6551 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6552 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6553 break;
6554 case ITEM_MOD_STRENGTH: //modify strength
6555 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6556 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6557 break;
6558 case ITEM_MOD_INTELLECT: //modify intellect
6559 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6560 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6561 break;
6562 case ITEM_MOD_SPIRIT: //modify spirit
6563 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6564 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6565 break;
6566 case ITEM_MOD_STAMINA: //modify stamina
6567 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6568 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6569 break;
6570 case ITEM_MOD_DEFENSE_SKILL_RATING:
6571 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6572 break;
6573 case ITEM_MOD_DODGE_RATING:
6574 ApplyRatingMod(CR_DODGE, int32(val), apply);
6575 break;
6576 case ITEM_MOD_PARRY_RATING:
6577 ApplyRatingMod(CR_PARRY, int32(val), apply);
6578 break;
6579 case ITEM_MOD_BLOCK_RATING:
6580 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6581 break;
6582 case ITEM_MOD_HIT_MELEE_RATING:
6583 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6584 break;
6585 case ITEM_MOD_HIT_RANGED_RATING:
6586 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6587 break;
6588 case ITEM_MOD_HIT_SPELL_RATING:
6589 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6590 break;
6591 case ITEM_MOD_CRIT_MELEE_RATING:
6592 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6593 break;
6594 case ITEM_MOD_CRIT_RANGED_RATING:
6595 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6596 break;
6597 case ITEM_MOD_CRIT_SPELL_RATING:
6598 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6599 break;
6600 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6601 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6602 break;
6603 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6604 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6605 break;
6606 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6607 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6608 break;
6609 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6610 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6611 break;
6612 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6613 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6614 break;
6615 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6616 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6617 break;
6618 case ITEM_MOD_HASTE_MELEE_RATING:
6619 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6620 break;
6621 case ITEM_MOD_HASTE_RANGED_RATING:
6622 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6623 break;
6624 case ITEM_MOD_HASTE_SPELL_RATING:
6625 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6626 break;
6627 case ITEM_MOD_HIT_RATING:
6628 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6629 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6630 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6631 break;
6632 case ITEM_MOD_CRIT_RATING:
6633 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6634 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6635 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6636 break;
6637 case ITEM_MOD_HIT_TAKEN_RATING:
6638 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6639 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6640 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6641 break;
6642 case ITEM_MOD_CRIT_TAKEN_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_RESILIENCE_RATING:
6648 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6649 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6650 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6651 break;
6652 case ITEM_MOD_HASTE_RATING:
6653 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6654 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6655 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6656 break;
6657 case ITEM_MOD_EXPERTISE_RATING:
6658 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6659 break;
6660 case ITEM_MOD_ATTACK_POWER:
6661 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6662 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6663 break;
6664 case ITEM_MOD_RANGED_ATTACK_POWER:
6665 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6666 break;
6667 case ITEM_MOD_FERAL_ATTACK_POWER:
6668 ApplyFeralAPBonus(int32(val), apply);
6669 break;
6670 case ITEM_MOD_MANA_REGENERATION:
6671 ApplyManaRegenBonus(int32(val), apply);
6672 break;
6673 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6674 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6675 break;
6676 case ITEM_MOD_SPELL_POWER:
6677 ApplySpellPowerBonus(int32(val), apply);
6678 break;
6679 // depricated item mods
6680 case ITEM_MOD_SPELL_HEALING_DONE:
6681 case ITEM_MOD_SPELL_DAMAGE_DONE:
6682 break;
6686 // Apply Spell Power from ScalingStatValue if set
6687 if(ssv)
6689 if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
6690 ApplySpellPowerBonus(spellbonus, apply);
6693 // If set ScalingStatValue armor get it or use item armor
6694 uint32 armor = proto->Armor;
6695 if (ssv)
6697 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6698 armor = ssvarmor;
6700 // Add armor bonus from ArmorDamageModifier if > 0
6701 if (proto->ArmorDamageModifier > 0)
6702 armor += uint32(proto->ArmorDamageModifier);
6704 if (armor)
6705 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6707 if (proto->Block)
6708 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6710 if (proto->HolyRes)
6711 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6713 if (proto->FireRes)
6714 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6716 if (proto->NatureRes)
6717 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6719 if (proto->FrostRes)
6720 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6722 if (proto->ShadowRes)
6723 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6725 if (proto->ArcaneRes)
6726 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6728 WeaponAttackType attType = BASE_ATTACK;
6729 float damage = 0.0f;
6731 if( slot == EQUIPMENT_SLOT_RANGED && (
6732 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6733 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6735 attType = RANGED_ATTACK;
6737 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6739 attType = OFF_ATTACK;
6742 float minDamage = proto->Damage[0].DamageMin;
6743 float maxDamage = proto->Damage[0].DamageMax;
6744 int32 extraDPS = 0;
6745 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6746 if (ssv)
6748 if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue)))
6750 float average = extraDPS * proto->Delay / 1000.0f;
6751 minDamage = 0.7f * average;
6752 maxDamage = 1.3f * average;
6755 if (minDamage > 0 )
6757 damage = apply ? minDamage : BASE_MINDAMAGE;
6758 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6759 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6762 if (maxDamage > 0 )
6764 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6765 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6768 // Apply feral bonus from ScalingStatValue if set
6769 if (ssv)
6771 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6772 ApplyFeralAPBonus(feral_bonus, apply);
6774 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6775 if(getClass() == CLASS_DRUID)
6777 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6778 if (feral_bonus > 0)
6779 ApplyFeralAPBonus(feral_bonus, apply);
6782 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6783 return;
6785 if (proto->Delay)
6787 if(slot == EQUIPMENT_SLOT_RANGED)
6788 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6789 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6790 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6791 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6792 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6795 if(CanModifyStats() && (damage || proto->Delay))
6796 UpdateDamagePhysical(attType);
6799 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6801 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6802 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6803 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6805 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6806 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6807 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6809 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6810 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6811 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6814 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6816 // generic not weapon specific case processes in aura code
6817 if(aura->GetSpellProto()->EquippedItemClass == -1)
6818 return;
6820 BaseModGroup mod = BASEMOD_END;
6821 switch(attackType)
6823 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6824 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6825 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6826 default: return;
6829 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6831 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6835 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6837 // ignore spell mods for not wands
6838 Modifier const* modifier = aura->GetModifier();
6839 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6840 return;
6842 // generic not weapon specific case processes in aura code
6843 if(aura->GetSpellProto()->EquippedItemClass == -1)
6844 return;
6846 UnitMods unitMod = UNIT_MOD_END;
6847 switch(attackType)
6849 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6850 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6851 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6852 default: return;
6855 UnitModifierType unitModType = TOTAL_VALUE;
6856 switch(modifier->m_auraname)
6858 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6859 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6860 default: return;
6863 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6865 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6869 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6871 if(!item)
6872 return;
6874 ItemPrototype const *proto = item->GetProto();
6875 if(!proto)
6876 return;
6878 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6880 _Spell const& spellData = proto->Spells[i];
6882 // no spell
6883 if(!spellData.SpellId )
6884 continue;
6886 // wrong triggering type
6887 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6888 continue;
6890 // check if it is valid spell
6891 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6892 if(!spellproto)
6893 continue;
6895 ApplyEquipSpell(spellproto,item,apply,form_change);
6899 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6901 if(apply)
6903 // Cannot be used in this stance/form
6904 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6905 return;
6907 if(form_change) // check aura active state from other form
6909 bool found = false;
6910 for (int k=0; k < 3; ++k)
6912 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6913 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6915 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6917 found = true;
6918 break;
6921 if(found)
6922 break;
6925 if(found) // and skip re-cast already active aura at form change
6926 return;
6929 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6931 CastSpell(this,spellInfo,true,item);
6933 else
6935 if(form_change) // check aura compatibility
6937 // Cannot be used in this stance/form
6938 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6939 return; // and remove only not compatible at form change
6942 if(item)
6943 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6944 else
6945 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6949 void Player::UpdateEquipSpellsAtFormChange()
6951 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6953 if(m_items[i] && !m_items[i]->IsBroken())
6955 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6956 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6960 // item set bonuses not dependent from item broken state
6961 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6963 ItemSetEffect* eff = ItemSetEff[setindex];
6964 if(!eff)
6965 continue;
6967 for(uint32 y=0;y<8; ++y)
6969 SpellEntry const* spellInfo = eff->spells[y];
6970 if(!spellInfo)
6971 continue;
6973 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6974 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6979 void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
6981 Item *item = GetWeaponForAttack(attType, false);
6982 if(!item || item->IsBroken())
6983 return;
6985 ItemPrototype const *proto = item->GetProto();
6986 if(!proto)
6987 return;
6989 if (!Target || Target == this )
6990 return;
6992 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6994 _Spell const& spellData = proto->Spells[i];
6996 // no spell
6997 if(!spellData.SpellId )
6998 continue;
7000 // wrong triggering type
7001 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7002 continue;
7004 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7005 if(!spellInfo)
7007 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7008 continue;
7011 // not allow proc extra attack spell at extra attack
7012 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7013 return;
7015 float chance = spellInfo->procChance;
7017 if(spellData.SpellPPMRate)
7019 uint32 WeaponSpeed = proto->Delay;
7020 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7022 else if(chance > 100.0f)
7024 chance = GetWeaponProcChance();
7027 if (roll_chance_f(chance))
7028 CastSpell(Target, spellInfo->Id, true, item);
7031 // item combat enchantments
7032 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7034 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7035 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7036 if(!pEnchant) continue;
7037 for (int s=0;s<3;s++)
7039 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7040 continue;
7042 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7043 if (!spellInfo)
7045 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7046 continue;
7049 // Use first rank to access spell item enchant procs
7050 float ppmRate = spellmgr.GetItemEnchantProcChance(spellInfo->Id);
7052 float chance = ppmRate
7053 ? GetPPMProcChance(proto->Delay, ppmRate)
7054 : pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7057 ApplySpellMod(spellInfo->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
7058 ApplySpellMod(spellInfo->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
7060 if (roll_chance_f(chance))
7062 if(IsPositiveSpell(pEnchant->spellid[s]))
7063 CastSpell(this, pEnchant->spellid[s], true, item);
7064 else
7065 CastSpell(Target, pEnchant->spellid[s], true, item);
7071 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7073 ItemPrototype const* proto = item->GetProto();
7074 // special learning case
7075 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7077 uint32 learn_spell_id = proto->Spells[0].SpellId;
7078 uint32 learning_spell_id = proto->Spells[1].SpellId;
7080 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7081 if(!spellInfo)
7083 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7084 SendEquipError(EQUIP_ERR_NONE,item,NULL);
7085 return;
7088 Spell *spell = new Spell(this, spellInfo, false);
7089 spell->m_CastItem = item;
7090 spell->m_cast_count = cast_count; //set count of casts
7091 spell->m_currentBasePoints[0] = learning_spell_id;
7092 spell->prepare(&targets);
7093 return;
7096 // use triggered flag only for items with many spell casts and for not first cast
7097 int count = 0;
7099 // item spells casted at use
7100 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7102 _Spell const& spellData = proto->Spells[i];
7104 // no spell
7105 if(!spellData.SpellId)
7106 continue;
7108 // wrong triggering type
7109 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7110 continue;
7112 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7113 if(!spellInfo)
7115 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7116 continue;
7119 Spell *spell = new Spell(this, spellInfo, (count > 0));
7120 spell->m_CastItem = item;
7121 spell->m_cast_count = cast_count; // set count of casts
7122 spell->m_glyphIndex = glyphIndex; // glyph index
7123 spell->prepare(&targets);
7125 ++count;
7128 // Item enchantments spells casted at use
7129 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7131 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7132 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7133 if(!pEnchant) continue;
7134 for (int s=0;s<3;s++)
7136 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7137 continue;
7139 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7140 if (!spellInfo)
7142 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7143 continue;
7146 Spell *spell = new Spell(this, spellInfo, (count > 0));
7147 spell->m_CastItem = item;
7148 spell->m_cast_count = cast_count; // set count of casts
7149 spell->m_glyphIndex = glyphIndex; // glyph index
7150 spell->prepare(&targets);
7152 ++count;
7157 void Player::_RemoveAllItemMods()
7159 sLog.outDebug("_RemoveAllItemMods start.");
7161 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7163 if(m_items[i])
7165 ItemPrototype const *proto = m_items[i]->GetProto();
7166 if(!proto)
7167 continue;
7169 // item set bonuses not dependent from item broken state
7170 if(proto->ItemSet)
7171 RemoveItemsSetItem(this,proto);
7173 if(m_items[i]->IsBroken())
7174 continue;
7176 ApplyItemEquipSpell(m_items[i],false);
7177 ApplyEnchantment(m_items[i], false);
7181 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7183 if(m_items[i])
7185 if(m_items[i]->IsBroken())
7186 continue;
7187 ItemPrototype const *proto = m_items[i]->GetProto();
7188 if(!proto)
7189 continue;
7191 uint32 attacktype = Player::GetAttackBySlot(i);
7192 if(attacktype < MAX_ATTACK)
7193 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7195 _ApplyItemBonuses(proto,i, false);
7197 if( i == EQUIPMENT_SLOT_RANGED )
7198 _ApplyAmmoBonuses();
7202 sLog.outDebug("_RemoveAllItemMods complete.");
7205 void Player::_ApplyAllItemMods()
7207 sLog.outDebug("_ApplyAllItemMods start.");
7209 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7211 if(m_items[i])
7213 if(m_items[i]->IsBroken())
7214 continue;
7216 ItemPrototype const *proto = m_items[i]->GetProto();
7217 if(!proto)
7218 continue;
7220 uint32 attacktype = Player::GetAttackBySlot(i);
7221 if(attacktype < MAX_ATTACK)
7222 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7224 _ApplyItemBonuses(proto,i, true);
7226 if( i == EQUIPMENT_SLOT_RANGED )
7227 _ApplyAmmoBonuses();
7231 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7233 if(m_items[i])
7235 ItemPrototype const *proto = m_items[i]->GetProto();
7236 if(!proto)
7237 continue;
7239 // item set bonuses not dependent from item broken state
7240 if(proto->ItemSet)
7241 AddItemsSetItem(this,m_items[i]);
7243 if(m_items[i]->IsBroken())
7244 continue;
7246 ApplyItemEquipSpell(m_items[i],true);
7247 ApplyEnchantment(m_items[i], true);
7251 sLog.outDebug("_ApplyAllItemMods complete.");
7254 void Player::_ApplyAllLevelScaleItemMods(bool apply)
7256 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7258 if(m_items[i])
7260 if(m_items[i]->IsBroken())
7261 continue;
7263 ItemPrototype const *proto = m_items[i]->GetProto();
7264 if(!proto)
7265 continue;
7267 _ApplyItemBonuses(proto,i, apply, true);
7272 void Player::_ApplyAmmoBonuses()
7274 // check ammo
7275 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7276 if(!ammo_id)
7277 return;
7279 float currentAmmoDPS;
7281 ItemPrototype const *ammo_proto = ObjectMgr::GetItemPrototype( ammo_id );
7282 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7283 currentAmmoDPS = 0.0f;
7284 else
7285 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7287 if(currentAmmoDPS == GetAmmoDPS())
7288 return;
7290 m_ammoDPS = currentAmmoDPS;
7292 if(CanModifyStats())
7293 UpdateDamagePhysical(RANGED_ATTACK);
7296 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7298 if(!ammo_proto)
7299 return false;
7301 // check ranged weapon
7302 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7303 if(!weapon || weapon->IsBroken() )
7304 return false;
7306 ItemPrototype const* weapon_proto = weapon->GetProto();
7307 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7308 return false;
7310 // check ammo ws. weapon compatibility
7311 switch(weapon_proto->SubClass)
7313 case ITEM_SUBCLASS_WEAPON_BOW:
7314 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7315 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7316 return false;
7317 break;
7318 case ITEM_SUBCLASS_WEAPON_GUN:
7319 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7320 return false;
7321 break;
7322 default:
7323 return false;
7326 return true;
7329 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7330 Called by remove insignia spell effect */
7331 void Player::RemovedInsignia(Player* looterPlr)
7333 if (!GetBattleGroundId())
7334 return;
7336 // If not released spirit, do it !
7337 if(m_deathTimer > 0)
7339 m_deathTimer = 0;
7340 BuildPlayerRepop();
7341 RepopAtGraveyard();
7344 Corpse *corpse = GetCorpse();
7345 if (!corpse)
7346 return;
7348 // We have to convert player corpse to bones, not to be able to resurrect there
7349 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7350 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7351 if (!bones)
7352 return;
7354 // Now we must make bones lootable, and send player loot
7355 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7357 // We store the level of our player in the gold field
7358 // We retrieve this information at Player::SendLoot()
7359 bones->loot.gold = getLevel();
7360 bones->lootRecipient = looterPlr;
7361 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7364 void Player::SendLootRelease( uint64 guid )
7366 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7367 data << uint64(guid) << uint8(1);
7368 SendDirectMessage( &data );
7371 void Player::SendLoot(uint64 guid, LootType loot_type)
7373 if (uint64 lguid = GetLootGUID())
7374 m_session->DoLootRelease(lguid);
7376 Loot *loot = 0;
7377 PermissionTypes permission = ALL_PERMISSION;
7379 sLog.outDebug("Player::SendLoot");
7380 if (IS_GAMEOBJECT_GUID(guid))
7382 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7383 GameObject *go = GetMap()->GetGameObject(guid);
7385 // not check distance for GO in case owned GO (fishing bobber case, for example)
7386 // And permit out of range GO with no owner in case fishing hole
7387 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7389 SendLootRelease(guid);
7390 return;
7393 loot = &go->loot;
7395 if (go->getLootState() == GO_READY)
7397 uint32 lootid = go->GetGOInfo()->GetLootId();
7398 if ((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S))
7399 if (BattleGround *bg = GetBattleGround())
7400 if (bg->GetTypeID() == BATTLEGROUND_AV)
7401 if (!(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(go->GetEntry(), GetTeam())))
7403 SendLootRelease(guid);
7404 return;
7407 if (lootid)
7409 sLog.outDebug(" if(lootid)");
7410 loot->clear();
7411 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7414 if (loot_type == LOOT_FISHING)
7415 go->getFishLoot(loot,this);
7417 go->SetLootState(GO_ACTIVATED);
7420 else if (IS_ITEM_GUID(guid))
7422 Item *item = GetItemByGuid( guid );
7424 if (!item)
7426 SendLootRelease(guid);
7427 return;
7430 loot = &item->loot;
7432 if (!item->m_lootGenerated)
7434 item->m_lootGenerated = true;
7435 loot->clear();
7437 switch(loot_type)
7439 case LOOT_DISENCHANTING:
7440 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7441 break;
7442 case LOOT_PROSPECTING:
7443 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7444 break;
7445 case LOOT_MILLING:
7446 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7447 break;
7448 default:
7449 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7450 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7451 break;
7455 else if (IS_CORPSE_GUID(guid)) // remove insignia
7457 Corpse *bones = GetMap()->GetCorpse(guid);
7459 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7461 SendLootRelease(guid);
7462 return;
7465 loot = &bones->loot;
7467 if (!bones->lootForBody)
7469 bones->lootForBody = true;
7470 uint32 pLevel = bones->loot.gold;
7471 bones->loot.clear();
7472 if (GetBattleGround()->GetTypeID() == BATTLEGROUND_AV)
7473 loot->FillLoot(0, LootTemplates_Creature, this, false);
7474 // It may need a better formula
7475 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7476 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7479 if (bones->lootRecipient != this)
7480 permission = NONE_PERMISSION;
7482 else
7484 Creature *creature = GetMap()->GetCreature(guid);
7486 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7487 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7489 SendLootRelease(guid);
7490 return;
7493 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7495 SendLootRelease(guid);
7496 return;
7499 loot = &creature->loot;
7501 if (loot_type == LOOT_PICKPOCKETING)
7503 if (!creature->lootForPickPocketed)
7505 creature->lootForPickPocketed = true;
7506 loot->clear();
7508 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7509 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7511 // Generate extra money for pick pocket loot
7512 const uint32 a = urand(0, creature->getLevel()/2);
7513 const uint32 b = urand(0, getLevel()/2);
7514 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7517 else
7519 // the player whose group may loot the corpse
7520 Player *recipient = creature->GetLootRecipient();
7521 if (!recipient)
7523 creature->SetLootRecipient(this);
7524 recipient = this;
7527 if (creature->lootForPickPocketed)
7529 creature->lootForPickPocketed = false;
7530 loot->clear();
7533 if (!creature->lootForBody)
7535 creature->lootForBody = true;
7536 loot->clear();
7538 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7539 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7541 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7543 if (Group* group = recipient->GetGroup())
7545 group->UpdateLooterGuid(creature,true);
7547 switch (group->GetLootMethod())
7549 case GROUP_LOOT:
7550 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7551 group->GroupLoot(recipient->GetGUID(), loot, creature);
7552 break;
7553 case NEED_BEFORE_GREED:
7554 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7555 break;
7556 case MASTER_LOOT:
7557 group->MasterLoot(recipient->GetGUID(), loot, creature);
7558 break;
7559 default:
7560 break;
7565 // possible only if creature->lootForBody && loot->empty() at spell cast check
7566 if (loot_type == LOOT_SKINNING)
7568 loot->clear();
7569 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7571 // set group rights only for loot_type != LOOT_SKINNING
7572 else
7574 if(Group* group = GetGroup())
7576 if (group == recipient->GetGroup())
7578 if (group->GetLootMethod() == FREE_FOR_ALL)
7579 permission = ALL_PERMISSION;
7580 else if (group->GetLooterGuid() == GetGUID())
7582 if (group->GetLootMethod() == MASTER_LOOT)
7583 permission = MASTER_PERMISSION;
7584 else
7585 permission = ALL_PERMISSION;
7587 else
7588 permission = GROUP_PERMISSION;
7590 else
7591 permission = NONE_PERMISSION;
7593 else if (recipient == this)
7594 permission = ALL_PERMISSION;
7595 else
7596 permission = NONE_PERMISSION;
7601 SetLootGUID(guid);
7603 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7604 switch(loot_type)
7606 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7607 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7608 default: break;
7611 // need know merged fishing/corpse loot type for achievements
7612 loot->loot_type = loot_type;
7614 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7616 data << uint64(guid);
7617 data << uint8(loot_type);
7618 data << LootView(*loot, this, permission);
7620 SendDirectMessage(&data);
7622 // add 'this' player as one of the players that are looting 'loot'
7623 if (permission != NONE_PERMISSION)
7624 loot->AddLooter(GetGUID());
7626 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7627 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7630 void Player::SendNotifyLootMoneyRemoved()
7632 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7633 GetSession()->SendPacket( &data );
7636 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7638 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7639 data << uint8(lootSlot);
7640 GetSession()->SendPacket( &data );
7643 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7645 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7646 data << Field;
7647 data << Value;
7648 GetSession()->SendPacket(&data);
7651 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7653 // data depends on zoneid/mapid...
7654 BattleGround* bg = GetBattleGround();
7655 uint16 NumberOfFields = 0;
7656 uint32 mapid = GetMapId();
7658 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7660 // may be exist better way to do this...
7661 switch(zoneid)
7663 case 0:
7664 case 1:
7665 case 4:
7666 case 8:
7667 case 10:
7668 case 11:
7669 case 12:
7670 case 36:
7671 case 38:
7672 case 40:
7673 case 41:
7674 case 51:
7675 case 267:
7676 case 1519:
7677 case 1537:
7678 case 2257:
7679 case 2918:
7680 NumberOfFields = 8;
7681 break;
7682 case 139:
7683 NumberOfFields = 41;
7684 break;
7685 case 1377:
7686 NumberOfFields = 15;
7687 break;
7688 case 2597:
7689 NumberOfFields = 83;
7690 break;
7691 case 3277:
7692 NumberOfFields = 16;
7693 break;
7694 case 3358:
7695 case 3820:
7696 NumberOfFields = 40;
7697 break;
7698 case 3483:
7699 NumberOfFields = 27;
7700 break;
7701 case 3518:
7702 NumberOfFields = 39;
7703 break;
7704 case 3519:
7705 NumberOfFields = 38;
7706 break;
7707 case 3521:
7708 NumberOfFields = 37;
7709 break;
7710 case 3698:
7711 case 3702:
7712 case 3968:
7713 NumberOfFields = 11;
7714 break;
7715 case 3703:
7716 NumberOfFields = 11;
7717 break;
7718 default:
7719 NumberOfFields = 12;
7720 break;
7723 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7724 data << uint32(mapid); // mapid
7725 data << uint32(zoneid); // zone id
7726 data << uint32(areaid); // area id, new 2.1.0
7727 data << uint16(NumberOfFields); // count of uint64 blocks
7728 data << uint32(0x8d8) << uint32(0x0); // 1
7729 data << uint32(0x8d7) << uint32(0x0); // 2
7730 data << uint32(0x8d6) << uint32(0x0); // 3
7731 data << uint32(0x8d5) << uint32(0x0); // 4
7732 data << uint32(0x8d4) << uint32(0x0); // 5
7733 data << uint32(0x8d3) << uint32(0x0); // 6
7734 // 7 1 - Arena season in progress, 0 - end of season
7735 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7736 // 8 Arena season id
7737 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7738 if(mapid == 530) // Outland
7740 data << uint32(0x9bf) << uint32(0x0); // 7
7741 data << uint32(0x9bd) << uint32(0xF); // 8
7742 data << uint32(0x9bb) << uint32(0xF); // 9
7744 switch(zoneid)
7746 case 1:
7747 case 11:
7748 case 12:
7749 case 38:
7750 case 40:
7751 case 51:
7752 case 1519:
7753 case 1537:
7754 case 2257:
7755 break;
7756 case 2597: // AV
7757 if (bg && bg->GetTypeID() == BATTLEGROUND_AV)
7758 bg->FillInitialWorldStates(data);
7759 else
7761 data << uint32(0x7ae) << uint32(0x1); // 7 snowfall n
7762 data << uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
7763 data << uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
7764 data << uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
7765 data << uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
7766 data << uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
7767 data << uint32(0x567) << uint32(0x1); // 13 frostwolfe c
7768 data << uint32(0x566) << uint32(0x1); // 14 frostwolfw c
7769 data << uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
7770 data << uint32(0x544) << uint32(0x0); // 16 ice grave a_a
7771 data << uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
7772 data << uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
7773 data << uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
7774 data << uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
7775 data << uint32(0x574) << uint32(0x0); // 21 1396 unk
7776 data << uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
7777 data << uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
7778 data << uint32(0x56f) << uint32(0x0); // 24 1391 unk
7779 data << uint32(0x56e) << uint32(0x0); // 25 iceblood a
7780 data << uint32(0x56d) << uint32(0x0); // 26 towerp a
7781 data << uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
7782 data << uint32(0x56b) << uint32(0x0); // 28 froswolfw a
7783 data << uint32(0x56a) << uint32(0x1); // 29 1386 unk
7784 data << uint32(0x569) << uint32(0x1); // 30 iceblood c
7785 data << uint32(0x568) << uint32(0x1); // 31 towerp c
7786 data << uint32(0x565) << uint32(0x0); // 32 stoneh tower a
7787 data << uint32(0x564) << uint32(0x0); // 33 icewing tower a
7788 data << uint32(0x563) << uint32(0x0); // 34 dunn a
7789 data << uint32(0x562) << uint32(0x0); // 35 duns a
7790 data << uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
7791 data << uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
7792 data << uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
7793 data << uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
7794 data << uint32(0x55d) << uint32(0x0); // 40 stone tower d
7795 data << uint32(0x3c6) << uint32(0x0); // 41 966 unk
7796 data << uint32(0x3c4) << uint32(0x0); // 42 964 unk
7797 data << uint32(0x3c2) << uint32(0x0); // 43 962 unk
7798 data << uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
7799 data << uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
7800 data << uint32(0x3b6) << uint32(0x0); // 46 950 unk
7801 data << uint32(0x55c) << uint32(0x0); // 47 icewing tower d
7802 data << uint32(0x55b) << uint32(0x0); // 48 dunn d
7803 data << uint32(0x55a) << uint32(0x0); // 49 duns d
7804 data << uint32(0x559) << uint32(0x0); // 50 1369 unk
7805 data << uint32(0x558) << uint32(0x0); // 51 iceblood d
7806 data << uint32(0x557) << uint32(0x0); // 52 towerp d
7807 data << uint32(0x556) << uint32(0x0); // 53 frostwolfe d
7808 data << uint32(0x555) << uint32(0x0); // 54 frostwolfw d
7809 data << uint32(0x554) << uint32(0x1); // 55 stoneh tower c
7810 data << uint32(0x553) << uint32(0x1); // 56 icewing tower c
7811 data << uint32(0x552) << uint32(0x1); // 57 dunn c
7812 data << uint32(0x551) << uint32(0x1); // 58 duns c
7813 data << uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
7814 data << uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
7815 data << uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
7816 data << uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
7817 data << uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
7818 data << uint32(0x545) << uint32(0x0); // 64 iceblood h_a
7819 data << uint32(0x543) << uint32(0x1); // 65 iceblod h_c
7820 data << uint32(0x542) << uint32(0x0); // 66 iceblood a_c
7821 data << uint32(0x540) << uint32(0x0); // 67 snowfall h_a
7822 data << uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
7823 data << uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
7824 data << uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
7825 data << uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
7826 data << uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
7827 data << uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
7828 data << uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
7829 data << uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
7830 data << uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
7831 data << uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
7832 data << uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
7833 data << uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
7834 data << uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
7835 data << uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
7837 break;
7838 case 3277: // WS
7839 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7840 bg->FillInitialWorldStates(data);
7841 else
7843 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7844 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7845 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7846 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7847 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7848 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7849 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7850 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7852 break;
7853 case 3358: // AB
7854 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7855 bg->FillInitialWorldStates(data);
7856 else
7858 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7859 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7860 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7861 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7862 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7863 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7864 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7865 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7866 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7867 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7868 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7869 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7870 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7871 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7872 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7873 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7874 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7875 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7876 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7877 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7878 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7879 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7880 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7881 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7882 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7883 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7884 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7885 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7886 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7887 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7888 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7889 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7891 break;
7892 case 3820: // EY
7893 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7894 bg->FillInitialWorldStates(data);
7895 else
7897 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7898 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7899 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7900 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7901 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7902 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7903 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7904 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7905 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7906 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7907 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7908 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7909 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7910 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7911 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7912 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7913 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7914 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7915 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7916 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7917 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7918 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7919 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7920 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7921 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7922 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7923 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7924 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7925 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7926 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7927 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7928 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7929 // and some more ... unknown
7931 break;
7932 case 3483: // Hellfire Peninsula
7933 data << uint32(0x9ba) << uint32(0x1); // 10
7934 data << uint32(0x9b9) << uint32(0x1); // 11
7935 data << uint32(0x9b5) << uint32(0x0); // 12
7936 data << uint32(0x9b4) << uint32(0x1); // 13
7937 data << uint32(0x9b3) << uint32(0x0); // 14
7938 data << uint32(0x9b2) << uint32(0x0); // 15
7939 data << uint32(0x9b1) << uint32(0x1); // 16
7940 data << uint32(0x9b0) << uint32(0x0); // 17
7941 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7942 data << uint32(0x9ac) << uint32(0x0); // 19
7943 data << uint32(0x9a8) << uint32(0x0); // 20
7944 data << uint32(0x9a7) << uint32(0x0); // 21
7945 data << uint32(0x9a6) << uint32(0x1); // 22
7946 break;
7947 case 3519: // Terokkar Forest
7948 data << uint32(0xa41) << uint32(0x0); // 10
7949 data << uint32(0xa40) << uint32(0x14); // 11
7950 data << uint32(0xa3f) << uint32(0x0); // 12
7951 data << uint32(0xa3e) << uint32(0x0); // 13
7952 data << uint32(0xa3d) << uint32(0x5); // 14
7953 data << uint32(0xa3c) << uint32(0x0); // 15
7954 data << uint32(0xa87) << uint32(0x0); // 16
7955 data << uint32(0xa86) << uint32(0x0); // 17
7956 data << uint32(0xa85) << uint32(0x0); // 18
7957 data << uint32(0xa84) << uint32(0x0); // 19
7958 data << uint32(0xa83) << uint32(0x0); // 20
7959 data << uint32(0xa82) << uint32(0x0); // 21
7960 data << uint32(0xa81) << uint32(0x0); // 22
7961 data << uint32(0xa80) << uint32(0x0); // 23
7962 data << uint32(0xa7e) << uint32(0x0); // 24
7963 data << uint32(0xa7d) << uint32(0x0); // 25
7964 data << uint32(0xa7c) << uint32(0x0); // 26
7965 data << uint32(0xa7b) << uint32(0x0); // 27
7966 data << uint32(0xa7a) << uint32(0x0); // 28
7967 data << uint32(0xa79) << uint32(0x0); // 29
7968 data << uint32(0x9d0) << uint32(0x5); // 30
7969 data << uint32(0x9ce) << uint32(0x0); // 31
7970 data << uint32(0x9cd) << uint32(0x0); // 32
7971 data << uint32(0x9cc) << uint32(0x0); // 33
7972 data << uint32(0xa88) << uint32(0x0); // 34
7973 data << uint32(0xad0) << uint32(0x0); // 35
7974 data << uint32(0xacf) << uint32(0x1); // 36
7975 break;
7976 case 3521: // Zangarmarsh
7977 data << uint32(0x9e1) << uint32(0x0); // 10
7978 data << uint32(0x9e0) << uint32(0x0); // 11
7979 data << uint32(0x9df) << uint32(0x0); // 12
7980 data << uint32(0xa5d) << uint32(0x1); // 13
7981 data << uint32(0xa5c) << uint32(0x0); // 14
7982 data << uint32(0xa5b) << uint32(0x1); // 15
7983 data << uint32(0xa5a) << uint32(0x0); // 16
7984 data << uint32(0xa59) << uint32(0x1); // 17
7985 data << uint32(0xa58) << uint32(0x0); // 18
7986 data << uint32(0xa57) << uint32(0x0); // 19
7987 data << uint32(0xa56) << uint32(0x0); // 20
7988 data << uint32(0xa55) << uint32(0x1); // 21
7989 data << uint32(0xa54) << uint32(0x0); // 22
7990 data << uint32(0x9e7) << uint32(0x0); // 23
7991 data << uint32(0x9e6) << uint32(0x0); // 24
7992 data << uint32(0x9e5) << uint32(0x0); // 25
7993 data << uint32(0xa00) << uint32(0x0); // 26
7994 data << uint32(0x9ff) << uint32(0x1); // 27
7995 data << uint32(0x9fe) << uint32(0x0); // 28
7996 data << uint32(0x9fd) << uint32(0x0); // 29
7997 data << uint32(0x9fc) << uint32(0x1); // 30
7998 data << uint32(0x9fb) << uint32(0x0); // 31
7999 data << uint32(0xa62) << uint32(0x0); // 32
8000 data << uint32(0xa61) << uint32(0x1); // 33
8001 data << uint32(0xa60) << uint32(0x1); // 34
8002 data << uint32(0xa5f) << uint32(0x0); // 35
8003 break;
8004 case 3698: // Nagrand Arena
8005 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
8006 bg->FillInitialWorldStates(data);
8007 else
8009 data << uint32(0xa0f) << uint32(0x0); // 7
8010 data << uint32(0xa10) << uint32(0x0); // 8
8011 data << uint32(0xa11) << uint32(0x0); // 9 show
8013 break;
8014 case 3702: // Blade's Edge Arena
8015 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8016 bg->FillInitialWorldStates(data);
8017 else
8019 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8020 data << uint32(0x9f1) << uint32(0x0); // 8 green
8021 data << uint32(0x9f3) << uint32(0x0); // 9 show
8023 break;
8024 case 3968: // Ruins of Lordaeron
8025 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8026 bg->FillInitialWorldStates(data);
8027 else
8029 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8030 data << uint32(0xbb9) << uint32(0x0); // 8 green
8031 data << uint32(0xbba) << uint32(0x0); // 9 show
8033 break;
8034 case 3703: // Shattrath City
8035 break;
8036 default:
8037 data << uint32(0x914) << uint32(0x0); // 7
8038 data << uint32(0x913) << uint32(0x0); // 8
8039 data << uint32(0x912) << uint32(0x0); // 9
8040 data << uint32(0x915) << uint32(0x0); // 10
8041 break;
8043 GetSession()->SendPacket(&data);
8046 uint32 Player::GetXPRestBonus(uint32 xp)
8048 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8050 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8051 rested_bonus = xp;
8053 SetRestBonus( GetRestBonus() - rested_bonus);
8055 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8056 return rested_bonus;
8059 void Player::SetBindPoint(uint64 guid)
8061 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8062 data << uint64(guid);
8063 GetSession()->SendPacket( &data );
8066 void Player::SendTalentWipeConfirm(uint64 guid)
8068 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8069 data << uint64(guid);
8070 data << uint32(resetTalentsCost());
8071 GetSession()->SendPacket( &data );
8074 void Player::SendPetSkillWipeConfirm()
8076 Pet* pet = GetPet();
8077 if(!pet)
8078 return;
8079 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8080 data << pet->GetGUID();
8081 data << uint32(pet->resetTalentsCost());
8082 GetSession()->SendPacket( &data );
8085 /*********************************************************/
8086 /*** STORAGE SYSTEM ***/
8087 /*********************************************************/
8089 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8091 assert(i < 3);
8092 if(i < 2 && item)
8094 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8095 return;
8096 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8097 if(charges == 0)
8098 return;
8099 if(charges > 1)
8100 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8101 else if(charges <= 1)
8103 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8104 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8109 void Player::SetSheath( SheathState sheathed )
8111 switch (sheathed)
8113 case SHEATH_STATE_UNARMED: // no prepared weapon
8114 SetVirtualItemSlot(0,NULL);
8115 SetVirtualItemSlot(1,NULL);
8116 SetVirtualItemSlot(2,NULL);
8117 break;
8118 case SHEATH_STATE_MELEE: // prepared melee weapon
8120 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
8121 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
8122 SetVirtualItemSlot(2,NULL);
8123 }; break;
8124 case SHEATH_STATE_RANGED: // prepared ranged weapon
8125 SetVirtualItemSlot(0,NULL);
8126 SetVirtualItemSlot(1,NULL);
8127 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
8128 break;
8129 default:
8130 SetVirtualItemSlot(0,NULL);
8131 SetVirtualItemSlot(1,NULL);
8132 SetVirtualItemSlot(2,NULL);
8133 break;
8135 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
8138 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8140 uint8 pClass = getClass();
8142 uint8 slots[4];
8143 slots[0] = NULL_SLOT;
8144 slots[1] = NULL_SLOT;
8145 slots[2] = NULL_SLOT;
8146 slots[3] = NULL_SLOT;
8147 switch( proto->InventoryType )
8149 case INVTYPE_HEAD:
8150 slots[0] = EQUIPMENT_SLOT_HEAD;
8151 break;
8152 case INVTYPE_NECK:
8153 slots[0] = EQUIPMENT_SLOT_NECK;
8154 break;
8155 case INVTYPE_SHOULDERS:
8156 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8157 break;
8158 case INVTYPE_BODY:
8159 slots[0] = EQUIPMENT_SLOT_BODY;
8160 break;
8161 case INVTYPE_CHEST:
8162 slots[0] = EQUIPMENT_SLOT_CHEST;
8163 break;
8164 case INVTYPE_ROBE:
8165 slots[0] = EQUIPMENT_SLOT_CHEST;
8166 break;
8167 case INVTYPE_WAIST:
8168 slots[0] = EQUIPMENT_SLOT_WAIST;
8169 break;
8170 case INVTYPE_LEGS:
8171 slots[0] = EQUIPMENT_SLOT_LEGS;
8172 break;
8173 case INVTYPE_FEET:
8174 slots[0] = EQUIPMENT_SLOT_FEET;
8175 break;
8176 case INVTYPE_WRISTS:
8177 slots[0] = EQUIPMENT_SLOT_WRISTS;
8178 break;
8179 case INVTYPE_HANDS:
8180 slots[0] = EQUIPMENT_SLOT_HANDS;
8181 break;
8182 case INVTYPE_FINGER:
8183 slots[0] = EQUIPMENT_SLOT_FINGER1;
8184 slots[1] = EQUIPMENT_SLOT_FINGER2;
8185 break;
8186 case INVTYPE_TRINKET:
8187 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8188 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8189 break;
8190 case INVTYPE_CLOAK:
8191 slots[0] = EQUIPMENT_SLOT_BACK;
8192 break;
8193 case INVTYPE_WEAPON:
8195 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8197 // suggest offhand slot only if know dual wielding
8198 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8199 if(CanDualWield())
8200 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8201 break;
8203 case INVTYPE_SHIELD:
8204 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8205 break;
8206 case INVTYPE_RANGED:
8207 slots[0] = EQUIPMENT_SLOT_RANGED;
8208 break;
8209 case INVTYPE_2HWEAPON:
8210 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8211 if (CanDualWield() && CanTitanGrip())
8212 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8213 break;
8214 case INVTYPE_TABARD:
8215 slots[0] = EQUIPMENT_SLOT_TABARD;
8216 break;
8217 case INVTYPE_WEAPONMAINHAND:
8218 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8219 break;
8220 case INVTYPE_WEAPONOFFHAND:
8221 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8222 break;
8223 case INVTYPE_HOLDABLE:
8224 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8225 break;
8226 case INVTYPE_THROWN:
8227 slots[0] = EQUIPMENT_SLOT_RANGED;
8228 break;
8229 case INVTYPE_RANGEDRIGHT:
8230 slots[0] = EQUIPMENT_SLOT_RANGED;
8231 break;
8232 case INVTYPE_BAG:
8233 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8234 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8235 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8236 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8237 break;
8238 case INVTYPE_RELIC:
8240 switch(proto->SubClass)
8242 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8243 if (pClass == CLASS_PALADIN)
8244 slots[0] = EQUIPMENT_SLOT_RANGED;
8245 break;
8246 case ITEM_SUBCLASS_ARMOR_IDOL:
8247 if (pClass == CLASS_DRUID)
8248 slots[0] = EQUIPMENT_SLOT_RANGED;
8249 break;
8250 case ITEM_SUBCLASS_ARMOR_TOTEM:
8251 if (pClass == CLASS_SHAMAN)
8252 slots[0] = EQUIPMENT_SLOT_RANGED;
8253 break;
8254 case ITEM_SUBCLASS_ARMOR_MISC:
8255 if (pClass == CLASS_WARLOCK)
8256 slots[0] = EQUIPMENT_SLOT_RANGED;
8257 break;
8258 case ITEM_SUBCLASS_ARMOR_SIGIL:
8259 if (pClass == CLASS_DEATH_KNIGHT)
8260 slots[0] = EQUIPMENT_SLOT_RANGED;
8261 break;
8263 break;
8265 default :
8266 return NULL_SLOT;
8269 if( slot != NULL_SLOT )
8271 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8273 for (int i = 0; i < 4; ++i)
8275 if ( slots[i] == slot )
8276 return slot;
8280 else
8282 // search free slot at first
8283 for (int i = 0; i < 4; ++i)
8285 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8287 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8288 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8289 return slots[i];
8293 // if not found free and can swap return first appropriate from used
8294 for (int i = 0; i < 4; ++i)
8296 if ( slots[i] != NULL_SLOT && swap )
8297 return slots[i];
8301 // no free position
8302 return NULL_SLOT;
8305 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8307 Item *pItem;
8308 uint32 tempcount = 0;
8310 uint8 res = EQUIP_ERR_OK;
8312 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8314 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8315 if( pItem && pItem->GetEntry() == item )
8317 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8318 if(ires==EQUIP_ERR_OK)
8320 tempcount += pItem->GetCount();
8321 if( tempcount >= count )
8322 return EQUIP_ERR_OK;
8324 else
8325 res = ires;
8328 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8330 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8331 if( pItem && pItem->GetEntry() == item )
8333 tempcount += pItem->GetCount();
8334 if( tempcount >= count )
8335 return EQUIP_ERR_OK;
8338 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8340 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8341 if( pItem && pItem->GetEntry() == item )
8343 tempcount += pItem->GetCount();
8344 if( tempcount >= count )
8345 return EQUIP_ERR_OK;
8348 Bag *pBag;
8349 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8351 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8352 if( pBag )
8354 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8356 pItem = GetItemByPos( i, j );
8357 if( pItem && pItem->GetEntry() == item )
8359 tempcount += pItem->GetCount();
8360 if( tempcount >= count )
8361 return EQUIP_ERR_OK;
8367 // not found req. item count and have unequippable items
8368 return res;
8371 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8373 uint32 count = 0;
8374 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8376 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8377 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8378 count += pItem->GetCount();
8380 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8382 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8383 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8384 count += pItem->GetCount();
8386 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8388 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8389 if( pBag )
8390 count += pBag->GetItemCount(item,skipItem);
8393 if(skipItem && skipItem->GetProto()->GemProperties)
8395 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8397 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8398 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8399 count += pItem->GetGemCountWithID(item);
8403 if(inBankAlso)
8405 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8407 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8408 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8409 count += pItem->GetCount();
8411 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8413 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8414 if( pBag )
8415 count += pBag->GetItemCount(item,skipItem);
8418 if(skipItem && skipItem->GetProto()->GemProperties)
8420 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8422 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8423 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8424 count += pItem->GetGemCountWithID(item);
8429 return count;
8432 Item* Player::GetItemByGuid( uint64 guid ) const
8434 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8436 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8437 if( pItem && pItem->GetGUID() == guid )
8438 return pItem;
8440 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8442 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8443 if( pItem && pItem->GetGUID() == guid )
8444 return pItem;
8447 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8449 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8450 if( pBag )
8452 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8454 Item* pItem = pBag->GetItemByPos( j );
8455 if( pItem && pItem->GetGUID() == guid )
8456 return pItem;
8460 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8462 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8463 if( pBag )
8465 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8467 Item* pItem = pBag->GetItemByPos( j );
8468 if( pItem && pItem->GetGUID() == guid )
8469 return pItem;
8474 return NULL;
8477 Item* Player::GetItemByPos( uint16 pos ) const
8479 uint8 bag = pos >> 8;
8480 uint8 slot = pos & 255;
8481 return GetItemByPos( bag, slot );
8484 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8486 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END )) )
8487 return m_items[slot];
8488 else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8489 || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END) )
8491 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8492 if ( pBag )
8493 return pBag->GetItemByPos(slot);
8495 return NULL;
8498 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8500 uint16 slot;
8501 switch (attackType)
8503 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8504 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8505 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8506 default: return NULL;
8509 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8510 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8511 return NULL;
8513 if(!useable)
8514 return item;
8516 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8517 return NULL;
8519 return item;
8522 Item* Player::GetShield(bool useable) const
8524 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8525 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8526 return NULL;
8528 if(!useable)
8529 return item;
8531 if( item->IsBroken())
8532 return NULL;
8534 return item;
8537 uint32 Player::GetAttackBySlot( uint8 slot )
8539 switch(slot)
8541 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8542 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8543 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8544 default: return MAX_ATTACK;
8548 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8550 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8551 return true;
8552 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8553 return true;
8554 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8555 return true;
8556 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8557 return true;
8558 return false;
8561 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8563 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8564 return true;
8565 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8566 return true;
8567 return false;
8570 bool Player::IsBankPos( uint8 bag, uint8 slot )
8572 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8573 return true;
8574 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8575 return true;
8576 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8577 return true;
8578 return false;
8581 bool Player::IsBagPos( uint16 pos )
8583 uint8 bag = pos >> 8;
8584 uint8 slot = pos & 255;
8585 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8586 return true;
8587 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8588 return true;
8589 return false;
8592 bool Player::IsValidPos( uint8 bag, uint8 slot )
8594 // post selected
8595 if(bag == NULL_BAG)
8596 return true;
8598 if (bag == INVENTORY_SLOT_BAG_0)
8600 // any post selected
8601 if (slot == NULL_SLOT)
8602 return true;
8604 // equipment
8605 if (slot < EQUIPMENT_SLOT_END)
8606 return true;
8608 // bag equip slots
8609 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8610 return true;
8612 // backpack slots
8613 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8614 return true;
8616 // keyring slots
8617 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8618 return true;
8620 // bank main slots
8621 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8622 return true;
8624 // bank bag slots
8625 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8626 return true;
8628 return false;
8631 // bag content slots
8632 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8634 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8635 if(!pBag)
8636 return false;
8638 // any post selected
8639 if (slot == NULL_SLOT)
8640 return true;
8642 return slot < pBag->GetBagSize();
8645 // bank bag content slots
8646 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8648 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8649 if(!pBag)
8650 return false;
8652 // any post selected
8653 if (slot == NULL_SLOT)
8654 return true;
8656 return slot < pBag->GetBagSize();
8659 // where this?
8660 return false;
8664 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8666 uint32 tempcount = 0;
8667 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8669 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8670 if( pItem && pItem->GetEntry() == item )
8672 tempcount += pItem->GetCount();
8673 if( tempcount >= count )
8674 return true;
8677 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8679 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8680 if( pItem && pItem->GetEntry() == item )
8682 tempcount += pItem->GetCount();
8683 if( tempcount >= count )
8684 return true;
8687 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8689 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8691 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8693 Item* pItem = GetItemByPos( i, j );
8694 if( pItem && pItem->GetEntry() == item )
8696 tempcount += pItem->GetCount();
8697 if( tempcount >= count )
8698 return true;
8704 if(inBankAlso)
8706 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8708 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8709 if( pItem && pItem->GetEntry() == item )
8711 tempcount += pItem->GetCount();
8712 if( tempcount >= count )
8713 return true;
8716 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8718 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8720 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8722 Item* pItem = GetItemByPos( i, j );
8723 if( pItem && pItem->GetEntry() == item )
8725 tempcount += pItem->GetCount();
8726 if( tempcount >= count )
8727 return true;
8734 return false;
8737 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8739 uint32 tempcount = 0;
8740 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8742 if(i==int(except_slot))
8743 continue;
8745 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8746 if( pItem && pItem->GetEntry() == item)
8748 tempcount += pItem->GetCount();
8749 if( tempcount >= count )
8750 return true;
8754 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item);
8755 if (pProto && pProto->GemProperties)
8757 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8759 if(i==int(except_slot))
8760 continue;
8762 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8763 if( pItem && pItem->GetProto()->Socket[0].Color)
8765 tempcount += pItem->GetGemCountWithID(item);
8766 if( tempcount >= count )
8767 return true;
8772 return false;
8775 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8777 uint32 tempcount = 0;
8778 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8780 if(i==int(except_slot))
8781 continue;
8783 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8784 if (!pItem)
8785 continue;
8787 ItemPrototype const *pProto = pItem->GetProto();
8788 if (!pProto)
8789 continue;
8791 if (pProto->ItemLimitCategory == limitCategory)
8793 tempcount += pItem->GetCount();
8794 if( tempcount >= count )
8795 return true;
8798 if( pProto->Socket[0].Color)
8800 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8801 if( tempcount >= count )
8802 return true;
8806 return false;
8809 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8811 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
8812 if( !pProto )
8814 if(no_space_count)
8815 *no_space_count = count;
8816 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8819 // no maximum
8820 if(pProto->MaxCount <= 0)
8821 return EQUIP_ERR_OK;
8823 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8825 if (curcount + count > uint32(pProto->MaxCount))
8827 if(no_space_count)
8828 *no_space_count = count +curcount - pProto->MaxCount;
8829 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8832 return EQUIP_ERR_OK;
8835 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8837 Item *pItem;
8838 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8840 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8841 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8842 return true;
8844 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8846 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8847 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8848 return true;
8850 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8852 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8854 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8856 pItem = GetItemByPos( i, j );
8857 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8858 return true;
8862 return false;
8865 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8867 Item* pItem2 = GetItemByPos( bag, slot );
8869 // ignore move item (this slot will be empty at move)
8870 if (pItem2==pSrcItem)
8871 pItem2 = NULL;
8873 uint32 need_space;
8875 // empty specific slot - check item fit to slot
8876 if (!pItem2 || swap)
8878 if (bag == INVENTORY_SLOT_BAG_0)
8880 // keyring case
8881 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8882 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8884 // currencytoken case
8885 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8886 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8888 // prevent cheating
8889 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8890 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8892 else
8894 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8895 if (!pBag)
8896 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8898 ItemPrototype const* pBagProto = pBag->GetProto();
8899 if (!pBagProto)
8900 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8902 if (slot >= pBagProto->ContainerSlots)
8903 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8905 if (!ItemCanGoIntoBag(pProto,pBagProto))
8906 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8909 // non empty stack with space
8910 need_space = pProto->GetMaxStackSize();
8912 // non empty slot, check item type
8913 else
8915 // check item type
8916 if (pItem2->GetEntry() != pProto->ItemId)
8917 return EQUIP_ERR_ITEM_CANT_STACK;
8919 // check free space
8920 if (pItem2->GetCount() >= pProto->GetMaxStackSize())
8921 return EQUIP_ERR_ITEM_CANT_STACK;
8923 // free stack space or infinity
8924 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8927 if (need_space > count)
8928 need_space = count;
8930 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8931 if (!newPosition.isContainedIn(dest))
8933 dest.push_back(newPosition);
8934 count -= need_space;
8936 return EQUIP_ERR_OK;
8939 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
8941 // skip specific bag already processed in first called _CanStoreItem_InBag
8942 if (bag==skip_bag)
8943 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8945 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8946 if (!pBag)
8947 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8949 ItemPrototype const* pBagProto = pBag->GetProto();
8950 if (!pBagProto)
8951 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8953 // specialized bag mode or non-specilized
8954 if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
8955 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8957 if (!ItemCanGoIntoBag(pProto,pBagProto))
8958 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8960 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8962 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8963 if (j==skip_slot)
8964 continue;
8966 Item* pItem2 = GetItemByPos( bag, j );
8968 // ignore move item (this slot will be empty at move)
8969 if (pItem2==pSrcItem)
8970 pItem2 = NULL;
8972 // if merge skip empty, if !merge skip non-empty
8973 if ((pItem2!=NULL)!=merge)
8974 continue;
8976 if (pItem2)
8978 if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8980 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8981 if(need_space > count)
8982 need_space = count;
8984 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8985 if (!newPosition.isContainedIn(dest))
8987 dest.push_back(newPosition);
8988 count -= need_space;
8990 if (count==0)
8991 return EQUIP_ERR_OK;
8995 else
8997 uint32 need_space = pProto->GetMaxStackSize();
8998 if (need_space > count)
8999 need_space = count;
9001 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9002 if (!newPosition.isContainedIn(dest))
9004 dest.push_back(newPosition);
9005 count -= need_space;
9007 if (count==0)
9008 return EQUIP_ERR_OK;
9012 return EQUIP_ERR_OK;
9015 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
9017 for(uint32 j = slot_begin; j < slot_end; ++j)
9019 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9020 if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
9021 continue;
9023 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
9025 // ignore move item (this slot will be empty at move)
9026 if (pItem2==pSrcItem)
9027 pItem2 = NULL;
9029 // if merge skip empty, if !merge skip non-empty
9030 if ((pItem2!=NULL)!=merge)
9031 continue;
9033 if (pItem2)
9035 if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9037 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9038 if (need_space > count)
9039 need_space = count;
9040 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9041 if (!newPosition.isContainedIn(dest))
9043 dest.push_back(newPosition);
9044 count -= need_space;
9046 if (count==0)
9047 return EQUIP_ERR_OK;
9051 else
9053 uint32 need_space = pProto->GetMaxStackSize();
9054 if (need_space > count)
9055 need_space = count;
9057 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9058 if (!newPosition.isContainedIn(dest))
9060 dest.push_back(newPosition);
9061 count -= need_space;
9063 if (count==0)
9064 return EQUIP_ERR_OK;
9068 return EQUIP_ERR_OK;
9071 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9073 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9075 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
9076 if (!pProto)
9078 if (no_space_count)
9079 *no_space_count = count;
9080 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9083 if (pItem && pItem->IsBindedNotWith(this))
9085 if (no_space_count)
9086 *no_space_count = count;
9087 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9090 // check count of items (skip for auto move for same player from bank)
9091 uint32 no_similar_count = 0; // can't store this amount similar items
9092 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9093 if (res!=EQUIP_ERR_OK)
9095 if (count==no_similar_count)
9097 if (no_space_count)
9098 *no_space_count = no_similar_count;
9099 return res;
9101 count -= no_similar_count;
9104 // in specific slot
9105 if (bag != NULL_BAG && slot != NULL_SLOT)
9107 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9108 if (res!=EQUIP_ERR_OK)
9110 if (no_space_count)
9111 *no_space_count = count + no_similar_count;
9112 return res;
9115 if (count==0)
9117 if (no_similar_count==0)
9118 return EQUIP_ERR_OK;
9120 if (no_space_count)
9121 *no_space_count = count + no_similar_count;
9122 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9126 // not specific slot or have space for partly store only in specific slot
9128 // in specific bag
9129 if (bag != NULL_BAG)
9131 // search stack in bag for merge to
9132 if (pProto->Stackable != 1)
9134 if (bag == INVENTORY_SLOT_BAG_0) // inventory
9136 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9137 if (res!=EQUIP_ERR_OK)
9139 if (no_space_count)
9140 *no_space_count = count + no_similar_count;
9141 return res;
9144 if (count==0)
9146 if (no_similar_count==0)
9147 return EQUIP_ERR_OK;
9149 if (no_space_count)
9150 *no_space_count = count + no_similar_count;
9151 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9154 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9155 if (res!=EQUIP_ERR_OK)
9157 if (no_space_count)
9158 *no_space_count = count + no_similar_count;
9159 return res;
9162 if (count==0)
9164 if (no_similar_count==0)
9165 return EQUIP_ERR_OK;
9167 if (no_space_count)
9168 *no_space_count = count + no_similar_count;
9169 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9172 else // equipped bag
9174 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9175 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9176 if (res!=EQUIP_ERR_OK)
9177 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_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;
9198 // search free slot in bag for place to
9199 if(bag == INVENTORY_SLOT_BAG_0) // inventory
9201 // search free slot - keyring case
9202 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9204 uint32 keyringSize = GetMaxKeyringSize();
9205 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9206 if (res!=EQUIP_ERR_OK)
9208 if (no_space_count)
9209 *no_space_count = count + no_similar_count;
9210 return res;
9213 if (count==0)
9215 if (no_similar_count==0)
9216 return EQUIP_ERR_OK;
9218 if (no_space_count)
9219 *no_space_count = count + no_similar_count;
9220 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9223 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9224 if (res!=EQUIP_ERR_OK)
9226 if (no_space_count)
9227 *no_space_count = count + no_similar_count;
9228 return res;
9231 if (count==0)
9233 if (no_similar_count==0)
9234 return EQUIP_ERR_OK;
9236 if (no_space_count)
9237 *no_space_count = count + no_similar_count;
9238 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9241 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9243 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9244 if (res!=EQUIP_ERR_OK)
9246 if (no_space_count)
9247 *no_space_count = count + no_similar_count;
9248 return res;
9251 if (count==0)
9253 if (no_similar_count==0)
9254 return EQUIP_ERR_OK;
9256 if (no_space_count)
9257 *no_space_count = count + no_similar_count;
9258 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9262 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9263 if (res!=EQUIP_ERR_OK)
9265 if (no_space_count)
9266 *no_space_count = count + no_similar_count;
9267 return res;
9270 if (count==0)
9272 if (no_similar_count==0)
9273 return EQUIP_ERR_OK;
9275 if (no_space_count)
9276 *no_space_count = count + no_similar_count;
9277 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9280 else // equipped bag
9282 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9283 if (res!=EQUIP_ERR_OK)
9284 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9286 if (res!=EQUIP_ERR_OK)
9288 if (no_space_count)
9289 *no_space_count = count + no_similar_count;
9290 return res;
9293 if (count==0)
9295 if (no_similar_count==0)
9296 return EQUIP_ERR_OK;
9298 if (no_space_count)
9299 *no_space_count = count + no_similar_count;
9300 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9305 // not specific bag or have space for partly store only in specific bag
9307 // search stack for merge to
9308 if (pProto->Stackable != 1)
9310 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9311 if (res!=EQUIP_ERR_OK)
9313 if (no_space_count)
9314 *no_space_count = count + no_similar_count;
9315 return res;
9318 if (count==0)
9320 if (no_similar_count==0)
9321 return EQUIP_ERR_OK;
9323 if (no_space_count)
9324 *no_space_count = count + no_similar_count;
9325 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9328 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9329 if (res!=EQUIP_ERR_OK)
9331 if (no_space_count)
9332 *no_space_count = count + no_similar_count;
9333 return res;
9336 if (count==0)
9338 if (no_similar_count==0)
9339 return EQUIP_ERR_OK;
9341 if (no_space_count)
9342 *no_space_count = count + no_similar_count;
9343 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9346 if (pProto->BagFamily)
9348 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9350 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9351 if (res!=EQUIP_ERR_OK)
9352 continue;
9354 if (count==0)
9356 if (no_similar_count==0)
9357 return EQUIP_ERR_OK;
9359 if (no_space_count)
9360 *no_space_count = count + no_similar_count;
9361 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9366 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9368 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9369 if (res!=EQUIP_ERR_OK)
9370 continue;
9372 if (count==0)
9374 if (no_similar_count==0)
9375 return EQUIP_ERR_OK;
9377 if (no_space_count)
9378 *no_space_count = count + no_similar_count;
9379 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9384 // search free slot - special bag case
9385 if (pProto->BagFamily)
9387 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9389 uint32 keyringSize = GetMaxKeyringSize();
9390 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9391 if (res!=EQUIP_ERR_OK)
9393 if (no_space_count)
9394 *no_space_count = count + no_similar_count;
9395 return res;
9398 if (count==0)
9400 if (no_similar_count==0)
9401 return EQUIP_ERR_OK;
9403 if (no_space_count)
9404 *no_space_count = count + no_similar_count;
9405 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9408 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9410 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9411 if (res!=EQUIP_ERR_OK)
9413 if (no_space_count)
9414 *no_space_count = count + no_similar_count;
9415 return res;
9418 if (count==0)
9420 if (no_similar_count==0)
9421 return EQUIP_ERR_OK;
9423 if (no_space_count)
9424 *no_space_count = count + no_similar_count;
9425 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9429 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9431 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9432 if (res!=EQUIP_ERR_OK)
9433 continue;
9435 if (count==0)
9437 if (no_similar_count==0)
9438 return EQUIP_ERR_OK;
9440 if (no_space_count)
9441 *no_space_count = count + no_similar_count;
9442 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9447 // search free slot
9448 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9449 if (res!=EQUIP_ERR_OK)
9451 if (no_space_count)
9452 *no_space_count = count + no_similar_count;
9453 return res;
9456 if (count==0)
9458 if (no_similar_count==0)
9459 return EQUIP_ERR_OK;
9461 if (no_space_count)
9462 *no_space_count = count + no_similar_count;
9463 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9466 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9468 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9469 if (res!=EQUIP_ERR_OK)
9470 continue;
9472 if (count==0)
9474 if (no_similar_count==0)
9475 return EQUIP_ERR_OK;
9477 if (no_space_count)
9478 *no_space_count = count + no_similar_count;
9479 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9483 if (no_space_count)
9484 *no_space_count = count + no_similar_count;
9486 return EQUIP_ERR_INVENTORY_FULL;
9489 //////////////////////////////////////////////////////////////////////////
9490 uint8 Player::CanStoreItems( Item **pItems,int count) const
9492 Item *pItem2;
9494 // fill space table
9495 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9496 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9497 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9498 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9500 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9501 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9502 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9503 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9505 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9507 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9509 if (pItem2 && !pItem2->IsInTrade())
9511 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9515 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9517 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9519 if (pItem2 && !pItem2->IsInTrade())
9521 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9525 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9527 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9529 if (pItem2 && !pItem2->IsInTrade())
9531 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9535 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9537 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9539 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9541 pItem2 = GetItemByPos( i, j );
9542 if (pItem2 && !pItem2->IsInTrade())
9544 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9550 // check free space for all items
9551 for (int k = 0; k < count; ++k)
9553 Item *pItem = pItems[k];
9555 // no item
9556 if (!pItem) continue;
9558 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9559 ItemPrototype const *pProto = pItem->GetProto();
9561 // strange item
9562 if( !pProto )
9563 return EQUIP_ERR_ITEM_NOT_FOUND;
9565 // item it 'bind'
9566 if(pItem->IsBindedNotWith(this))
9567 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9569 Bag *pBag;
9570 ItemPrototype const *pBagProto;
9572 // item is 'one item only'
9573 uint8 res = CanTakeMoreSimilarItems(pItem);
9574 if(res != EQUIP_ERR_OK)
9575 return res;
9577 // search stack for merge to
9578 if( pProto->Stackable != 1 )
9580 bool b_found = false;
9582 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9584 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9585 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9587 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9588 b_found = true;
9589 break;
9592 if (b_found) continue;
9594 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9596 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9597 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9599 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9600 b_found = true;
9601 break;
9604 if (b_found) continue;
9606 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9608 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9609 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9611 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9612 b_found = true;
9613 break;
9616 if (b_found) continue;
9618 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9620 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9621 if( pBag )
9623 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9625 pItem2 = GetItemByPos( t, j );
9626 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9628 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9629 b_found = true;
9630 break;
9635 if (b_found) continue;
9638 // special bag case
9639 if( pProto->BagFamily )
9641 bool b_found = false;
9642 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9644 uint32 keyringSize = GetMaxKeyringSize();
9645 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9647 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9649 inv_keys[t-KEYRING_SLOT_START] = 1;
9650 b_found = true;
9651 break;
9656 if (b_found) continue;
9658 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9660 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9662 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9664 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9665 b_found = true;
9666 break;
9671 if (b_found) continue;
9673 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9675 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9676 if( pBag )
9678 pBagProto = pBag->GetProto();
9680 // not plain container check
9681 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9682 ItemCanGoIntoBag(pProto,pBagProto) )
9684 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9686 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9688 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9689 b_found = true;
9690 break;
9696 if (b_found) continue;
9699 // search free slot
9700 bool b_found = false;
9701 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9703 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9705 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9706 b_found = true;
9707 break;
9710 if (b_found) continue;
9712 // search free slot in bags
9713 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9715 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9716 if( pBag )
9718 pBagProto = pBag->GetProto();
9720 // special bag already checked
9721 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9722 continue;
9724 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9726 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9728 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9729 b_found = true;
9730 break;
9736 // no free slot found?
9737 if (!b_found)
9738 return EQUIP_ERR_INVENTORY_FULL;
9741 return EQUIP_ERR_OK;
9744 //////////////////////////////////////////////////////////////////////////
9745 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9747 dest = 0;
9748 Item *pItem = Item::CreateItem( item, 1, this );
9749 if( pItem )
9751 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9752 delete pItem;
9753 return result;
9756 return EQUIP_ERR_ITEM_NOT_FOUND;
9759 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9761 dest = 0;
9762 if( pItem )
9764 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9765 ItemPrototype const *pProto = pItem->GetProto();
9766 if( pProto )
9768 if(pItem->IsBindedNotWith(this))
9769 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9771 // check count of items (skip for auto move for same player from bank)
9772 uint8 res = CanTakeMoreSimilarItems(pItem);
9773 if(res != EQUIP_ERR_OK)
9774 return res;
9776 // check this only in game
9777 if(not_loading)
9779 // May be here should be more stronger checks; STUNNED checked
9780 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9781 if (hasUnitState(UNIT_STAT_STUNNED))
9782 return EQUIP_ERR_YOU_ARE_STUNNED;
9784 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9785 // - combat
9786 // - in-progress arenas
9787 if( !pProto->CanChangeEquipStateInCombat() )
9789 if( isInCombat() )
9790 return EQUIP_ERR_NOT_IN_COMBAT;
9792 if(BattleGround* bg = GetBattleGround())
9793 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9794 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9797 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9798 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9800 if(IsNonMeleeSpellCasted(false))
9801 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9804 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
9805 // 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)
9806 if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
9807 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9809 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9810 if (eslot == NULL_SLOT)
9811 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9813 uint8 msg = CanUseItem(pItem , not_loading);
9814 if (msg != EQUIP_ERR_OK)
9815 return msg;
9816 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
9817 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9819 // if swap ignore item (equipped also)
9820 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9821 return res2;
9823 // check unique-equipped special item classes
9824 if (pProto->Class == ITEM_CLASS_QUIVER)
9826 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9828 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
9830 if (pBag != pItem)
9832 if (ItemPrototype const* pBagProto = pBag->GetProto())
9834 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
9835 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9836 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
9837 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9844 uint32 type = pProto->InventoryType;
9846 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9848 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9850 if (!CanDualWield())
9851 return EQUIP_ERR_CANT_DUAL_WIELD;
9853 else if (type == INVTYPE_2HWEAPON)
9855 if (!CanDualWield() || !CanTitanGrip())
9856 return EQUIP_ERR_CANT_DUAL_WIELD;
9859 if (IsTwoHandUsed())
9860 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9863 // equip two-hand weapon case (with possible unequip 2 items)
9864 if (type == INVTYPE_2HWEAPON)
9866 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9868 if (!CanTitanGrip())
9869 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9871 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9872 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9874 if (!CanTitanGrip())
9876 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9877 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9878 ItemPosCountVec off_dest;
9879 if (offItem && (!not_loading ||
9880 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9881 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
9882 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9885 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9886 return EQUIP_ERR_OK;
9890 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9893 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9895 // Applied only to equipped items and bank bags
9896 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9897 return EQUIP_ERR_OK;
9899 Item* pItem = GetItemByPos(pos);
9901 // Applied only to existed equipped item
9902 if( !pItem )
9903 return EQUIP_ERR_OK;
9905 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9907 ItemPrototype const *pProto = pItem->GetProto();
9908 if( !pProto )
9909 return EQUIP_ERR_ITEM_NOT_FOUND;
9911 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9912 // - combat
9913 // - in-progress arenas
9914 if( !pProto->CanChangeEquipStateInCombat() )
9916 if( isInCombat() )
9917 return EQUIP_ERR_NOT_IN_COMBAT;
9919 if(BattleGround* bg = GetBattleGround())
9920 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9921 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9924 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9925 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9927 return EQUIP_ERR_OK;
9930 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9932 if (!pItem)
9933 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9935 uint32 count = pItem->GetCount();
9937 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9938 ItemPrototype const *pProto = pItem->GetProto();
9939 if (!pProto)
9940 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9942 if (pItem->IsBindedNotWith(this))
9943 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9945 // check count of items (skip for auto move for same player from bank)
9946 uint8 res = CanTakeMoreSimilarItems(pItem);
9947 if (res != EQUIP_ERR_OK)
9948 return res;
9950 // in specific slot
9951 if (bag != NULL_BAG && slot != NULL_SLOT)
9953 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
9955 if (!pItem->IsBag())
9956 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9958 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
9959 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9961 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
9962 return cantuse;
9965 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9966 if (res!=EQUIP_ERR_OK)
9967 return res;
9969 if (count==0)
9970 return EQUIP_ERR_OK;
9973 // not specific slot or have space for partly store only in specific slot
9975 // in specific bag
9976 if( bag != NULL_BAG )
9978 if( pProto->InventoryType == INVTYPE_BAG )
9980 Bag *pBag = (Bag*)pItem;
9981 if( pBag && !pBag->IsEmpty() )
9982 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9985 // search stack in bag for merge to
9986 if( pProto->Stackable != 1 )
9988 if( bag == INVENTORY_SLOT_BAG_0 )
9990 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9991 if(res!=EQUIP_ERR_OK)
9992 return res;
9994 if(count==0)
9995 return EQUIP_ERR_OK;
9997 else
9999 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
10000 if(res!=EQUIP_ERR_OK)
10001 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
10003 if(res!=EQUIP_ERR_OK)
10004 return res;
10006 if(count==0)
10007 return EQUIP_ERR_OK;
10011 // search free slot in bag
10012 if( bag == INVENTORY_SLOT_BAG_0 )
10014 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10015 if(res!=EQUIP_ERR_OK)
10016 return res;
10018 if(count==0)
10019 return EQUIP_ERR_OK;
10021 else
10023 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
10024 if(res != EQUIP_ERR_OK)
10025 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
10027 if(res != EQUIP_ERR_OK)
10028 return res;
10030 if(count == 0)
10031 return EQUIP_ERR_OK;
10035 // not specific bag or have space for partly store only in specific bag
10037 // search stack for merge to
10038 if( pProto->Stackable != 1 )
10040 // in slots
10041 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10042 if(res != EQUIP_ERR_OK)
10043 return res;
10045 if(count == 0)
10046 return EQUIP_ERR_OK;
10048 // in special bags
10049 if( pProto->BagFamily )
10051 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10053 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10054 if(res!=EQUIP_ERR_OK)
10055 continue;
10057 if(count==0)
10058 return EQUIP_ERR_OK;
10062 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10064 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10065 if(res!=EQUIP_ERR_OK)
10066 continue;
10068 if(count==0)
10069 return EQUIP_ERR_OK;
10073 // search free place in special bag
10074 if( pProto->BagFamily )
10076 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10078 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10079 if(res!=EQUIP_ERR_OK)
10080 continue;
10082 if(count==0)
10083 return EQUIP_ERR_OK;
10087 // search free space
10088 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10089 if(res!=EQUIP_ERR_OK)
10090 return res;
10092 if(count==0)
10093 return EQUIP_ERR_OK;
10095 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10097 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10098 if(res!=EQUIP_ERR_OK)
10099 continue;
10101 if(count==0)
10102 return EQUIP_ERR_OK;
10104 return EQUIP_ERR_BANK_FULL;
10107 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10109 if (pItem)
10111 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10113 if (!isAlive() && not_loading)
10114 return EQUIP_ERR_YOU_ARE_DEAD;
10116 //if (isStunned())
10117 // return EQUIP_ERR_YOU_ARE_STUNNED;
10119 ItemPrototype const *pProto = pItem->GetProto();
10120 if (pProto)
10122 if (pItem->IsBindedNotWith(this))
10123 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10125 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
10126 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10128 if (uint32 item_use_skill = pItem->GetSkill())
10130 if (GetSkillValue(item_use_skill) == 0)
10132 // armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
10133 if (pProto->Class != ITEM_CLASS_ARMOR)
10134 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10136 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : NULL;
10137 if (!ssd)
10138 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10140 bool allowScaleSkill = false;
10141 for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i)
10143 SkillLineAbilityEntry const *skillInfo = sSkillLineAbilityStore.LookupEntry(i);
10144 if (!skillInfo)
10145 continue;
10147 if (skillInfo->skillId != item_use_skill)
10148 continue;
10150 // can't learn
10151 if (skillInfo->classmask && (skillInfo->classmask & getClassMask()) == 0)
10152 continue;
10154 if (skillInfo->racemask && (skillInfo->racemask & getRaceMask()) == 0)
10155 continue;
10157 allowScaleSkill = true;
10158 break;
10161 if (!allowScaleSkill)
10162 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10166 if (pProto->RequiredSkill != 0)
10168 if (GetSkillValue( pProto->RequiredSkill ) == 0)
10169 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10171 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
10172 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10175 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
10176 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10178 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
10179 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10181 if (getLevel() < pProto->RequiredLevel)
10182 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10184 return EQUIP_ERR_OK;
10187 return EQUIP_ERR_ITEM_NOT_FOUND;
10190 bool Player::CanUseItem( ItemPrototype const *pProto )
10192 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10194 if( pProto )
10196 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10197 return false;
10198 if( pProto->RequiredSkill != 0 )
10200 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10201 return false;
10202 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10203 return false;
10205 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10206 return false;
10207 if( getLevel() < pProto->RequiredLevel )
10208 return false;
10209 return true;
10211 return false;
10214 uint8 Player::CanUseAmmo( uint32 item ) const
10216 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10217 if( !isAlive() )
10218 return EQUIP_ERR_YOU_ARE_DEAD;
10219 //if( isStunned() )
10220 // return EQUIP_ERR_YOU_ARE_STUNNED;
10221 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
10222 if( pProto )
10224 if( pProto->InventoryType!= INVTYPE_AMMO )
10225 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10226 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10227 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10228 if( pProto->RequiredSkill != 0 )
10230 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10231 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10232 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10233 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10235 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10236 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10237 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10238 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10240 if( getLevel() < pProto->RequiredLevel )
10241 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10243 // Requires No Ammo
10244 if(GetDummyAura(46699))
10245 return EQUIP_ERR_BAG_FULL6;
10247 return EQUIP_ERR_OK;
10249 return EQUIP_ERR_ITEM_NOT_FOUND;
10252 void Player::SetAmmo( uint32 item )
10254 if(!item)
10255 return;
10257 // already set
10258 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10259 return;
10261 // check ammo
10262 if(item)
10264 uint8 msg = CanUseAmmo( item );
10265 if( msg != EQUIP_ERR_OK )
10267 SendEquipError( msg, NULL, NULL );
10268 return;
10272 SetUInt32Value(PLAYER_AMMO_ID, item);
10274 _ApplyAmmoBonuses();
10277 void Player::RemoveAmmo()
10279 SetUInt32Value(PLAYER_AMMO_ID, 0);
10281 m_ammoDPS = 0.0f;
10283 if(CanModifyStats())
10284 UpdateDamagePhysical(RANGED_ATTACK);
10287 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10288 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10290 uint32 count = 0;
10291 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10292 count += itr->count;
10294 Item *pItem = Item::CreateItem( item, count, this );
10295 if( pItem )
10297 ItemAddedQuestCheck( item, count );
10298 if(randomPropertyId)
10299 pItem->SetItemRandomProperties(randomPropertyId);
10300 pItem = StoreItem( dest, pItem, update );
10302 return pItem;
10305 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10307 if( !pItem )
10308 return NULL;
10310 Item* lastItem = pItem;
10311 uint32 entry = pItem->GetEntry();
10312 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10314 uint16 pos = itr->pos;
10315 uint32 count = itr->count;
10317 ++itr;
10319 if(itr == dest.end())
10321 lastItem = _StoreItem(pos,pItem,count,false,update);
10322 break;
10325 lastItem = _StoreItem(pos,pItem,count,true,update);
10327 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10328 return lastItem;
10331 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10332 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10334 if( !pItem )
10335 return NULL;
10337 uint8 bag = pos >> 8;
10338 uint8 slot = pos & 255;
10340 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10342 Item *pItem2 = GetItemByPos( bag, slot );
10344 if (!pItem2)
10346 if (clone)
10347 pItem = pItem->CloneItem(count, this);
10348 else
10349 pItem->SetCount(count);
10351 if (!pItem)
10352 return NULL;
10354 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10355 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10356 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10357 pItem->SetBinding( true );
10359 if (bag == INVENTORY_SLOT_BAG_0)
10361 m_items[slot] = pItem;
10362 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10363 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10364 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10366 pItem->SetSlot( slot );
10367 pItem->SetContainer( NULL );
10369 // need update known currency
10370 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10371 UpdateKnownCurrencies(pItem->GetEntry(), true);
10373 if (IsInWorld() && update)
10375 pItem->AddToWorld();
10376 pItem->SendCreateUpdateToPlayer( this );
10379 pItem->SetState(ITEM_CHANGED, this);
10381 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10383 pBag->StoreItem( slot, pItem, update );
10384 if( IsInWorld() && update )
10386 pItem->AddToWorld();
10387 pItem->SendCreateUpdateToPlayer( this );
10389 pItem->SetState(ITEM_CHANGED, this);
10390 pBag->SetState(ITEM_CHANGED, this);
10393 AddEnchantmentDurations(pItem);
10394 AddItemDurations(pItem);
10396 return pItem;
10398 else
10400 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10401 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10402 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10403 pItem2->SetBinding( true );
10405 pItem2->SetCount( pItem2->GetCount() + count );
10406 if (IsInWorld() && update)
10407 pItem2->SendCreateUpdateToPlayer( this );
10409 if (!clone)
10411 // delete item (it not in any slot currently)
10412 if (IsInWorld() && update)
10414 pItem->RemoveFromWorld();
10415 pItem->DestroyForPlayer( this );
10418 RemoveEnchantmentDurations(pItem);
10419 RemoveItemDurations(pItem);
10421 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10422 pItem->SetState(ITEM_REMOVED, this);
10425 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10426 AddEnchantmentDurations(pItem2);
10428 pItem2->SetState(ITEM_CHANGED, this);
10430 return pItem2;
10434 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10436 if (Item *pItem = Item::CreateItem( item, 1, this ))
10438 ItemAddedQuestCheck( item, 1 );
10439 return EquipItem( pos, pItem, update );
10442 return NULL;
10445 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10447 AddEnchantmentDurations(pItem);
10448 AddItemDurations(pItem);
10450 uint8 bag = pos >> 8;
10451 uint8 slot = pos & 255;
10453 Item *pItem2 = GetItemByPos( bag, slot );
10455 if( !pItem2 )
10457 VisualizeItem( slot, pItem);
10459 if(isAlive())
10461 ItemPrototype const *pProto = pItem->GetProto();
10463 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10464 if(pProto && pProto->ItemSet)
10465 AddItemsSetItem(this, pItem);
10467 _ApplyItemMods(pItem, slot, true);
10469 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10471 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10473 if (getClass() == CLASS_ROGUE)
10474 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10476 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10478 if (!spellProto)
10479 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10480 else
10482 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10484 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10485 data << uint64(GetGUID());
10486 data << uint8(1);
10487 data << uint32(cooldownSpell);
10488 data << uint32(0);
10489 GetSession()->SendPacket(&data);
10494 if( IsInWorld() && update )
10496 pItem->AddToWorld();
10497 pItem->SendCreateUpdateToPlayer( this );
10500 ApplyEquipCooldown(pItem);
10502 if( slot == EQUIPMENT_SLOT_MAINHAND )
10504 UpdateExpertise(BASE_ATTACK);
10505 UpdateArmorPenetration();
10507 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10509 UpdateExpertise(OFF_ATTACK);
10510 UpdateArmorPenetration();
10513 else
10515 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10516 if( IsInWorld() && update )
10517 pItem2->SendCreateUpdateToPlayer( this );
10519 // delete item (it not in any slot currently)
10520 //pItem->DeleteFromDB();
10521 if( IsInWorld() && update )
10523 pItem->RemoveFromWorld();
10524 pItem->DestroyForPlayer( this );
10527 RemoveEnchantmentDurations(pItem);
10528 RemoveItemDurations(pItem);
10530 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10531 pItem->SetState(ITEM_REMOVED, this);
10532 pItem2->SetState(ITEM_CHANGED, this);
10534 ApplyEquipCooldown(pItem2);
10536 return pItem2;
10539 // only for full equip instead adding to stack
10540 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10542 return pItem;
10545 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10547 if( pItem )
10549 AddEnchantmentDurations(pItem);
10550 AddItemDurations(pItem);
10552 uint8 slot = pos & 255;
10553 VisualizeItem( slot, pItem);
10555 if( IsInWorld() )
10557 pItem->AddToWorld();
10558 pItem->SendCreateUpdateToPlayer( this );
10561 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10565 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10567 if(pItem)
10569 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10570 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10571 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10573 else
10575 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10576 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10580 void Player::VisualizeItem( uint8 slot, Item *pItem)
10582 if(!pItem)
10583 return;
10585 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10586 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10587 pItem->SetBinding( true );
10589 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10591 m_items[slot] = pItem;
10592 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10593 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10594 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10595 pItem->SetSlot( slot );
10596 pItem->SetContainer( NULL );
10598 if( slot < EQUIPMENT_SLOT_END )
10599 SetVisibleItemSlot(slot, pItem);
10601 pItem->SetState(ITEM_CHANGED, this);
10604 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10606 // note: removeitem does not actually change the item
10607 // it only takes the item out of storage temporarily
10608 // note2: if removeitem is to be used for delinking
10609 // the item must be removed from the player's updatequeue
10611 Item *pItem = GetItemByPos( bag, slot );
10612 if( pItem )
10614 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10616 RemoveEnchantmentDurations(pItem);
10617 RemoveItemDurations(pItem);
10619 if( bag == INVENTORY_SLOT_BAG_0 )
10621 if ( slot < INVENTORY_SLOT_BAG_END )
10623 ItemPrototype const *pProto = pItem->GetProto();
10624 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10626 if(pProto && pProto->ItemSet)
10627 RemoveItemsSetItem(this, pProto);
10629 _ApplyItemMods(pItem, slot, false);
10631 // remove item dependent auras and casts (only weapon and armor slots)
10632 if(slot < EQUIPMENT_SLOT_END)
10634 RemoveItemDependentAurasAndCasts(pItem);
10636 // remove held enchantments, update expertise
10637 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10639 if (pItem->GetItemSuffixFactor())
10641 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10642 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10644 else
10646 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10647 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10650 UpdateExpertise(BASE_ATTACK);
10651 UpdateArmorPenetration();
10653 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10655 UpdateExpertise(OFF_ATTACK);
10656 UpdateArmorPenetration();
10660 // need update known currency
10661 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10662 UpdateKnownCurrencies(pItem->GetEntry(), false);
10664 m_items[slot] = NULL;
10665 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10667 if ( slot < EQUIPMENT_SLOT_END )
10668 SetVisibleItemSlot(slot, NULL);
10670 else
10672 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10673 if( pBag )
10674 pBag->RemoveItem(slot, update);
10676 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10677 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10678 pItem->SetSlot( NULL_SLOT );
10679 if( IsInWorld() && update )
10680 pItem->SendCreateUpdateToPlayer( this );
10684 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10685 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10687 if(Item* it = GetItemByPos(bag,slot))
10689 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10690 RemoveItem(bag, slot, update);
10691 it->RemoveFromUpdateQueueOf(this);
10692 if(it->IsInWorld())
10694 it->RemoveFromWorld();
10695 it->DestroyForPlayer( this );
10700 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10701 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10703 // update quest counters
10704 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10706 // store item
10707 Item* pLastItem = StoreItem(dest, pItem, update);
10709 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10710 if(pLastItem == pItem)
10712 // update owner for last item (this can be original item with wrong owner
10713 if(pLastItem->GetOwnerGUID() != GetGUID())
10714 pLastItem->SetOwnerGUID(GetGUID());
10716 // if this original item then it need create record in inventory
10717 // in case trade we already have item in other player inventory
10718 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10722 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10724 Item *pItem = GetItemByPos( bag, slot );
10725 if( pItem )
10727 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10729 // start from destroy contained items (only equipped bag can have its)
10730 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10732 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10733 DestroyItem(slot, i, update);
10736 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10737 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10739 RemoveEnchantmentDurations(pItem);
10740 RemoveItemDurations(pItem);
10742 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10744 if( bag == INVENTORY_SLOT_BAG_0 )
10746 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10748 // equipment and equipped bags can have applied bonuses
10749 if ( slot < INVENTORY_SLOT_BAG_END )
10751 ItemPrototype const *pProto = pItem->GetProto();
10753 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10754 if(pProto && pProto->ItemSet)
10755 RemoveItemsSetItem(this, pProto);
10757 _ApplyItemMods(pItem, slot, false);
10760 if ( slot < EQUIPMENT_SLOT_END )
10762 // remove item dependent auras and casts (only weapon and armor slots)
10763 RemoveItemDependentAurasAndCasts(pItem);
10765 // update expertise
10766 if( slot == EQUIPMENT_SLOT_MAINHAND )
10768 UpdateExpertise(BASE_ATTACK);
10769 UpdateArmorPenetration();
10771 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10773 UpdateExpertise(OFF_ATTACK);
10774 UpdateArmorPenetration();
10777 // equipment visual show
10778 SetVisibleItemSlot(slot, NULL);
10780 // need update known currency
10781 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10782 UpdateKnownCurrencies(pItem->GetEntry(), false);
10784 m_items[slot] = NULL;
10786 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10787 pBag->RemoveItem(slot, update);
10789 if( IsInWorld() && update )
10791 pItem->RemoveFromWorld();
10792 pItem->DestroyForPlayer(this);
10795 //pItem->SetOwnerGUID(0);
10796 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10797 pItem->SetSlot( NULL_SLOT );
10798 pItem->SetState(ITEM_REMOVED, this);
10802 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10804 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10805 uint32 remcount = 0;
10807 // in inventory
10808 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10810 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10812 if (pItem->GetEntry() == item)
10814 if (pItem->GetCount() + remcount <= count)
10816 // all items in inventory can unequipped
10817 remcount += pItem->GetCount();
10818 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10820 if (remcount >= count)
10821 return;
10823 else
10825 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10826 pItem->SetCount( pItem->GetCount() - count + remcount );
10827 if (IsInWorld() & update)
10828 pItem->SendCreateUpdateToPlayer( this );
10829 pItem->SetState(ITEM_CHANGED, this);
10830 return;
10836 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10838 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10840 if (pItem->GetEntry() == item)
10842 if (pItem->GetCount() + remcount <= count)
10844 // all keys can be unequipped
10845 remcount += pItem->GetCount();
10846 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10848 if (remcount >= count)
10849 return;
10851 else
10853 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10854 pItem->SetCount( pItem->GetCount() - count + remcount );
10855 if (IsInWorld() & update)
10856 pItem->SendCreateUpdateToPlayer( this );
10857 pItem->SetState(ITEM_CHANGED, this);
10858 return;
10864 // in inventory bags
10865 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10867 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10869 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10871 if(Item* pItem = pBag->GetItemByPos(j))
10873 if (pItem->GetEntry() == item)
10875 // all items in bags can be unequipped
10876 if (pItem->GetCount() + remcount <= count)
10878 remcount += pItem->GetCount();
10879 DestroyItem( i, j, update );
10881 if (remcount >= count)
10882 return;
10884 else
10886 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10887 pItem->SetCount( pItem->GetCount() - count + remcount );
10888 if (IsInWorld() && update)
10889 pItem->SendCreateUpdateToPlayer( this );
10890 pItem->SetState(ITEM_CHANGED, this);
10891 return;
10899 // in equipment and bag list
10900 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10902 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10904 if (pItem && pItem->GetEntry() == item)
10906 if (pItem->GetCount() + remcount <= count)
10908 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
10910 remcount += pItem->GetCount();
10911 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10913 if (remcount >= count)
10914 return;
10917 else
10919 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10920 pItem->SetCount( pItem->GetCount() - count + remcount );
10921 if (IsInWorld() & update)
10922 pItem->SendCreateUpdateToPlayer( this );
10923 pItem->SetState(ITEM_CHANGED, this);
10924 return;
10931 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10933 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10935 // in inventory
10936 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10937 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10938 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10939 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10941 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10942 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10943 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10944 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10946 // in inventory bags
10947 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10948 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10949 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10950 if (Item* pItem = pBag->GetItemByPos(j))
10951 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10952 DestroyItem(i, j, update);
10954 // in equipment and bag list
10955 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10956 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10957 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10958 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10961 void Player::DestroyConjuredItems( bool update )
10963 // used when entering arena
10964 // destroys all conjured items
10965 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10967 // in inventory
10968 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10969 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10970 if (pItem->IsConjuredConsumable())
10971 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10973 // in inventory bags
10974 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10975 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10976 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10977 if (Item* pItem = pBag->GetItemByPos(j))
10978 if (pItem->IsConjuredConsumable())
10979 DestroyItem( i, j, update);
10981 // in equipment and bag list
10982 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10983 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10984 if (pItem->IsConjuredConsumable())
10985 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10988 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10990 if(!pItem)
10991 return;
10993 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10995 if( pItem->GetCount() <= count )
10997 count -= pItem->GetCount();
10999 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
11001 else
11003 ItemRemovedQuestCheck( pItem->GetEntry(), count);
11004 pItem->SetCount( pItem->GetCount() - count );
11005 count = 0;
11006 if( IsInWorld() & update )
11007 pItem->SendCreateUpdateToPlayer( this );
11008 pItem->SetState(ITEM_CHANGED, this);
11012 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
11014 uint8 srcbag = src >> 8;
11015 uint8 srcslot = src & 255;
11017 uint8 dstbag = dst >> 8;
11018 uint8 dstslot = dst & 255;
11020 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11021 if( !pSrcItem )
11023 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11024 return;
11027 // not let split all items (can be only at cheating)
11028 if(pSrcItem->GetCount() == count)
11030 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11031 return;
11034 // not let split more existed items (can be only at cheating)
11035 if(pSrcItem->GetCount() < count)
11037 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
11038 return;
11041 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11043 //best error message found for attempting to split while looting
11044 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11045 return;
11048 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11049 Item *pNewItem = pSrcItem->CloneItem( count, this );
11050 if( !pNewItem )
11052 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11053 return;
11056 if( IsInventoryPos( dst ) )
11058 // change item amount before check (for unique max count check)
11059 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11061 ItemPosCountVec dest;
11062 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11063 if( msg != EQUIP_ERR_OK )
11065 delete pNewItem;
11066 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11067 SendEquipError( msg, pSrcItem, NULL );
11068 return;
11071 if( IsInWorld() )
11072 pSrcItem->SendCreateUpdateToPlayer( this );
11073 pSrcItem->SetState(ITEM_CHANGED, this);
11074 StoreItem( dest, pNewItem, true);
11076 else if( IsBankPos ( dst ) )
11078 // change item amount before check (for unique max count check)
11079 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11081 ItemPosCountVec dest;
11082 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11083 if( msg != EQUIP_ERR_OK )
11085 delete pNewItem;
11086 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11087 SendEquipError( msg, pSrcItem, NULL );
11088 return;
11091 if( IsInWorld() )
11092 pSrcItem->SendCreateUpdateToPlayer( this );
11093 pSrcItem->SetState(ITEM_CHANGED, this);
11094 BankItem( dest, pNewItem, true);
11096 else if( IsEquipmentPos ( dst ) )
11098 // change item amount before check (for unique max count check), provide space for splitted items
11099 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11101 uint16 dest;
11102 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11103 if( msg != EQUIP_ERR_OK )
11105 delete pNewItem;
11106 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11107 SendEquipError( msg, pSrcItem, NULL );
11108 return;
11111 if( IsInWorld() )
11112 pSrcItem->SendCreateUpdateToPlayer( this );
11113 pSrcItem->SetState(ITEM_CHANGED, this);
11114 EquipItem( dest, pNewItem, true);
11115 AutoUnequipOffhandIfNeed();
11119 void Player::SwapItem( uint16 src, uint16 dst )
11121 uint8 srcbag = src >> 8;
11122 uint8 srcslot = src & 255;
11124 uint8 dstbag = dst >> 8;
11125 uint8 dstslot = dst & 255;
11127 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11128 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11130 if( !pSrcItem )
11131 return;
11133 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11135 if(!isAlive() )
11137 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11138 return;
11141 // SRC checks
11143 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11145 //best error message found for attempting to swap while looting
11146 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11147 return;
11150 // check unequip potability for equipped items and bank bags
11151 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11153 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11154 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty()));
11155 if(msg != EQUIP_ERR_OK)
11157 SendEquipError( msg, pSrcItem, pDstItem );
11158 return;
11162 // prevent put equipped/bank bag in self
11163 if( IsBagPos ( src ) && srcslot == dstbag)
11165 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11166 return;
11169 // DST checks
11171 if (pDstItem)
11173 if(pDstItem->m_lootGenerated) // prevent swap looting item
11175 //best error message found for attempting to swap while looting
11176 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11177 return;
11180 // check unequip potability for equipped items and bank bags
11181 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11183 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11184 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty()));
11185 if(msg != EQUIP_ERR_OK)
11187 SendEquipError( msg, pSrcItem, pDstItem );
11188 return;
11193 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11194 // or swap empty bag with another empty or not empty bag (with items exchange)
11196 // Move case
11197 if( !pDstItem )
11199 if( IsInventoryPos( dst ) )
11201 ItemPosCountVec dest;
11202 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11203 if( msg != EQUIP_ERR_OK )
11205 SendEquipError( msg, pSrcItem, NULL );
11206 return;
11209 RemoveItem(srcbag, srcslot, true);
11210 StoreItem( dest, pSrcItem, true);
11212 else if( IsBankPos ( dst ) )
11214 ItemPosCountVec dest;
11215 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11216 if( msg != EQUIP_ERR_OK )
11218 SendEquipError( msg, pSrcItem, NULL );
11219 return;
11222 RemoveItem(srcbag, srcslot, true);
11223 BankItem( dest, pSrcItem, true);
11225 else if( IsEquipmentPos ( dst ) )
11227 uint16 dest;
11228 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11229 if( msg != EQUIP_ERR_OK )
11231 SendEquipError( msg, pSrcItem, NULL );
11232 return;
11235 RemoveItem(srcbag, srcslot, true);
11236 EquipItem(dest, pSrcItem, true);
11237 AutoUnequipOffhandIfNeed();
11240 return;
11243 // attempt merge to / fill target item
11244 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11246 uint8 msg;
11247 ItemPosCountVec sDest;
11248 uint16 eDest;
11249 if( IsInventoryPos( dst ) )
11250 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11251 else if( IsBankPos ( dst ) )
11252 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11253 else if( IsEquipmentPos ( dst ) )
11254 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11255 else
11256 return;
11258 // can be merge/fill
11259 if(msg == EQUIP_ERR_OK)
11261 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11263 RemoveItem(srcbag, srcslot, true);
11265 if( IsInventoryPos( dst ) )
11266 StoreItem( sDest, pSrcItem, true);
11267 else if( IsBankPos ( dst ) )
11268 BankItem( sDest, pSrcItem, true);
11269 else if( IsEquipmentPos ( dst ) )
11271 EquipItem( eDest, pSrcItem, true);
11272 AutoUnequipOffhandIfNeed();
11275 else
11277 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11278 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11279 pSrcItem->SetState(ITEM_CHANGED, this);
11280 pDstItem->SetState(ITEM_CHANGED, this);
11281 if( IsInWorld() )
11283 pSrcItem->SendCreateUpdateToPlayer( this );
11284 pDstItem->SendCreateUpdateToPlayer( this );
11287 return;
11291 // impossible merge/fill, do real swap
11292 uint8 msg;
11294 // check src->dest move possibility
11295 ItemPosCountVec sDest;
11296 uint16 eDest = 0;
11297 if( IsInventoryPos( dst ) )
11298 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11299 else if( IsBankPos( dst ) )
11300 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11301 else if( IsEquipmentPos( dst ) )
11303 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11304 if( msg == EQUIP_ERR_OK )
11305 msg = CanUnequipItem( eDest, true );
11308 if( msg != EQUIP_ERR_OK )
11310 SendEquipError( msg, pSrcItem, pDstItem );
11311 return;
11314 // check dest->src move possibility
11315 ItemPosCountVec sDest2;
11316 uint16 eDest2 = 0;
11317 if( IsInventoryPos( src ) )
11318 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11319 else if( IsBankPos( src ) )
11320 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11321 else if( IsEquipmentPos( src ) )
11323 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11324 if( msg == EQUIP_ERR_OK )
11325 msg = CanUnequipItem( eDest2, true);
11328 if( msg != EQUIP_ERR_OK )
11330 SendEquipError( msg, pDstItem, pSrcItem );
11331 return;
11334 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11335 if(pSrcItem->IsBag() && pDstItem->IsBag())
11337 Bag* emptyBag = NULL;
11338 Bag* fullBag = NULL;
11339 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11341 emptyBag = (Bag*)pSrcItem;
11342 fullBag = (Bag*)pDstItem;
11344 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11346 emptyBag = (Bag*)pDstItem;
11347 fullBag = (Bag*)pSrcItem;
11350 // bag swap (with items exchange) case
11351 if(emptyBag && fullBag)
11353 ItemPrototype const* emotyProto = emptyBag->GetProto();
11355 uint32 count = 0;
11357 for(int i=0; i < fullBag->GetBagSize(); ++i)
11359 Item *bagItem = fullBag->GetItemByPos(i);
11360 if (!bagItem)
11361 continue;
11363 ItemPrototype const* bagItemProto = bagItem->GetProto();
11364 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11366 // one from items not go to empty target bag
11367 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11368 return;
11371 ++count;
11375 if (count > emptyBag->GetBagSize())
11377 // too small targeted bag
11378 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11379 return;
11382 // Items swap
11383 count = 0; // will pos in new bag
11384 for(int i = 0; i< fullBag->GetBagSize(); ++i)
11386 Item *bagItem = fullBag->GetItemByPos(i);
11387 if (!bagItem)
11388 continue;
11390 fullBag->RemoveItem(i, true);
11391 emptyBag->StoreItem(count, bagItem, true);
11392 bagItem->SetState(ITEM_CHANGED, this);
11394 ++count;
11399 // now do moves, remove...
11400 RemoveItem(dstbag, dstslot, false);
11401 RemoveItem(srcbag, srcslot, false);
11403 // add to dest
11404 if (IsInventoryPos(dst))
11405 StoreItem(sDest, pSrcItem, true);
11406 else if (IsBankPos(dst))
11407 BankItem(sDest, pSrcItem, true);
11408 else if (IsEquipmentPos(dst))
11409 EquipItem(eDest, pSrcItem, true);
11411 // add to src
11412 if (IsInventoryPos(src))
11413 StoreItem(sDest2, pDstItem, true);
11414 else if (IsBankPos(src))
11415 BankItem(sDest2, pDstItem, true);
11416 else if (IsEquipmentPos(src))
11417 EquipItem(eDest2, pDstItem, true);
11419 AutoUnequipOffhandIfNeed();
11422 void Player::AddItemToBuyBackSlot( Item *pItem )
11424 if (pItem)
11426 uint32 slot = m_currentBuybackSlot;
11427 // if current back slot non-empty search oldest or free
11428 if (m_items[slot])
11430 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11431 uint32 oldest_slot = BUYBACK_SLOT_START;
11433 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11435 // found empty
11436 if (!m_items[i])
11438 slot = i;
11439 break;
11442 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11444 if (oldest_time > i_time)
11446 oldest_time = i_time;
11447 oldest_slot = i;
11451 // find oldest
11452 slot = oldest_slot;
11455 RemoveItemFromBuyBackSlot( slot, true );
11456 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11458 m_items[slot] = pItem;
11459 time_t base = time(NULL);
11460 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11461 uint32 eslot = slot - BUYBACK_SLOT_START;
11463 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11464 if (ItemPrototype const *pProto = pItem->GetProto())
11465 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11466 else
11467 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11468 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11470 // move to next (for non filled list is move most optimized choice)
11471 if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11472 ++m_currentBuybackSlot;
11476 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11478 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11479 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11480 return m_items[slot];
11481 return NULL;
11484 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11486 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11487 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11489 Item *pItem = m_items[slot];
11490 if (pItem)
11492 pItem->RemoveFromWorld();
11493 if(del) pItem->SetState(ITEM_REMOVED, this);
11496 m_items[slot] = NULL;
11498 uint32 eslot = slot - BUYBACK_SLOT_START;
11499 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11500 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11501 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11503 // if current backslot is filled set to now free slot
11504 if (m_items[m_currentBuybackSlot])
11505 m_currentBuybackSlot = slot;
11509 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11511 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11512 WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : (msg == EQUIP_ERR_OK ? 1 : 18)));
11513 data << uint8(msg);
11515 if (msg != EQUIP_ERR_OK)
11517 data << uint64(pItem ? pItem->GetGUID() : 0);
11518 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11519 data << uint8(0); // not 0 there...
11521 if (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11523 uint32 level = 0;
11525 if (pItem)
11526 if (ItemPrototype const* proto = pItem->GetProto())
11527 level = proto->RequiredLevel;
11529 data << uint32(level); // new 2.4.0
11532 GetSession()->SendPacket(&data);
11535 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11537 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11538 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11539 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11540 data << uint32(item);
11541 if (param > 0)
11542 data << uint32(param);
11543 data << uint8(msg);
11544 GetSession()->SendPacket(&data);
11547 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11549 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11550 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11551 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11552 data << uint64(guid);
11553 if (param > 0)
11554 data << uint32(param);
11555 data << uint8(msg);
11556 GetSession()->SendPacket(&data);
11559 void Player::ClearTrade()
11561 tradeGold = 0;
11562 acceptTrade = false;
11563 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11564 tradeItems[i] = NULL_SLOT;
11567 void Player::TradeCancel(bool sendback)
11569 if (pTrader)
11571 // send yellow "Trade canceled" message to both traders
11572 WorldSession* ws;
11573 ws = GetSession();
11574 if (sendback)
11575 ws->SendCancelTrade();
11576 ws = pTrader->GetSession();
11577 if (!ws->PlayerLogout())
11578 ws->SendCancelTrade();
11580 // cleanup
11581 ClearTrade();
11582 pTrader->ClearTrade();
11583 // prevent loss of reference
11584 pTrader->pTrader = NULL;
11585 pTrader = NULL;
11589 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11591 if (m_itemDuration.empty())
11592 return;
11594 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11596 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11598 Item* item = *itr;
11599 ++itr; // current element can be erased in UpdateDuration
11601 if ((realtimeonly && item->GetProto()->Duration < 0) || !realtimeonly)
11602 item->UpdateDuration(this,time);
11606 void Player::UpdateEnchantTime(uint32 time)
11608 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11610 assert(itr->item);
11611 next = itr;
11612 if (!itr->item->GetEnchantmentId(itr->slot))
11614 next = m_enchantDuration.erase(itr);
11616 else if (itr->leftduration <= time)
11618 ApplyEnchantment(itr->item, itr->slot, false, false);
11619 itr->item->ClearEnchantment(itr->slot);
11620 next = m_enchantDuration.erase(itr);
11622 else if (itr->leftduration > time)
11624 itr->leftduration -= time;
11625 ++next;
11630 void Player::AddEnchantmentDurations(Item *item)
11632 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11634 if (!item->GetEnchantmentId(EnchantmentSlot(x)))
11635 continue;
11637 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11638 if (duration > 0)
11639 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11643 void Player::RemoveEnchantmentDurations(Item *item)
11645 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11647 if (itr->item == item)
11649 // save duration in item
11650 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11651 itr = m_enchantDuration.erase(itr);
11653 else
11654 ++itr;
11658 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11660 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11661 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11663 next = itr;
11664 if (itr->slot == slot)
11666 if (itr->item && itr->item->GetEnchantmentId(slot))
11668 // remove from stats
11669 ApplyEnchantment(itr->item, slot, false, false);
11670 // remove visual
11671 itr->item->ClearEnchantment(slot);
11673 // remove from update list
11674 next = m_enchantDuration.erase(itr);
11676 else
11677 ++next;
11680 // remove enchants from inventory items
11681 // NOTE: no need to remove these from stats, since these aren't equipped
11682 // in inventory
11683 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11684 if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
11685 if (pItem->GetEnchantmentId(slot))
11686 pItem->ClearEnchantment(slot);
11688 // in inventory bags
11689 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11690 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11691 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11692 if (Item* pItem = pBag->GetItemByPos(j))
11693 if (pItem->GetEnchantmentId(slot))
11694 pItem->ClearEnchantment(slot);
11697 // duration == 0 will remove item enchant
11698 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11700 if (!item)
11701 return;
11703 if (slot >= MAX_ENCHANTMENT_SLOT)
11704 return;
11706 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11708 if (itr->item == item && itr->slot == slot)
11710 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11711 m_enchantDuration.erase(itr);
11712 break;
11715 if (item && duration > 0 )
11717 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11718 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11722 void Player::ApplyEnchantment(Item *item,bool apply)
11724 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11725 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11728 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11730 if (!item)
11731 return;
11733 if (!item->IsEquipped())
11734 return;
11736 if (slot >= MAX_ENCHANTMENT_SLOT)
11737 return;
11739 uint32 enchant_id = item->GetEnchantmentId(slot);
11740 if (!enchant_id)
11741 return;
11743 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11744 if (!pEnchant)
11745 return;
11747 if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11748 return;
11750 if (!item->IsBroken())
11752 for (int s = 0; s < 3; ++s)
11754 uint32 enchant_display_type = pEnchant->type[s];
11755 uint32 enchant_amount = pEnchant->amount[s];
11756 uint32 enchant_spell_id = pEnchant->spellid[s];
11758 switch(enchant_display_type)
11760 case ITEM_ENCHANTMENT_TYPE_NONE:
11761 break;
11762 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11763 // processed in Player::CastItemCombatSpell
11764 break;
11765 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11766 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11767 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11768 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11769 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11770 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11771 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11772 break;
11773 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11774 if (enchant_spell_id)
11776 if (apply)
11778 int32 basepoints = 0;
11779 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11780 if (item->GetItemRandomPropertyId())
11782 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11783 if (item_rand)
11785 // Search enchant_amount
11786 for (int k = 0; k < 3; ++k)
11788 if(item_rand->enchant_id[k] == enchant_id)
11790 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11791 break;
11796 // Cast custom spell vs all equal basepoints getted from enchant_amount
11797 if (basepoints)
11798 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11799 else
11800 CastSpell(this, enchant_spell_id, true, item);
11802 else
11803 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11805 break;
11806 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11807 if (!enchant_amount)
11809 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11810 if(item_rand)
11812 for (int k = 0; k < 3; ++k)
11814 if(item_rand->enchant_id[k] == enchant_id)
11816 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11817 break;
11823 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11824 break;
11825 case ITEM_ENCHANTMENT_TYPE_STAT:
11827 if (!enchant_amount)
11829 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11830 if(item_rand_suffix)
11832 for (int k = 0; k < 3; ++k)
11834 if(item_rand_suffix->enchant_id[k] == enchant_id)
11836 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11837 break;
11843 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11844 switch (enchant_spell_id)
11846 case ITEM_MOD_MANA:
11847 sLog.outDebug("+ %u MANA",enchant_amount);
11848 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
11849 break;
11850 case ITEM_MOD_HEALTH:
11851 sLog.outDebug("+ %u HEALTH",enchant_amount);
11852 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
11853 break;
11854 case ITEM_MOD_AGILITY:
11855 sLog.outDebug("+ %u AGILITY",enchant_amount);
11856 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11857 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11858 break;
11859 case ITEM_MOD_STRENGTH:
11860 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11861 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11862 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11863 break;
11864 case ITEM_MOD_INTELLECT:
11865 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11866 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11867 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11868 break;
11869 case ITEM_MOD_SPIRIT:
11870 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11871 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11872 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11873 break;
11874 case ITEM_MOD_STAMINA:
11875 sLog.outDebug("+ %u STAMINA",enchant_amount);
11876 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11877 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11878 break;
11879 case ITEM_MOD_DEFENSE_SKILL_RATING:
11880 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11881 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11882 break;
11883 case ITEM_MOD_DODGE_RATING:
11884 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11885 sLog.outDebug("+ %u DODGE", enchant_amount);
11886 break;
11887 case ITEM_MOD_PARRY_RATING:
11888 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11889 sLog.outDebug("+ %u PARRY", enchant_amount);
11890 break;
11891 case ITEM_MOD_BLOCK_RATING:
11892 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11893 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11894 break;
11895 case ITEM_MOD_HIT_MELEE_RATING:
11896 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11897 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11898 break;
11899 case ITEM_MOD_HIT_RANGED_RATING:
11900 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11901 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11902 break;
11903 case ITEM_MOD_HIT_SPELL_RATING:
11904 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11905 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11906 break;
11907 case ITEM_MOD_CRIT_MELEE_RATING:
11908 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11909 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11910 break;
11911 case ITEM_MOD_CRIT_RANGED_RATING:
11912 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11913 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11914 break;
11915 case ITEM_MOD_CRIT_SPELL_RATING:
11916 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11917 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11918 break;
11919 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11920 // in Enchantments
11921 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11922 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11923 // break;
11924 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11925 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11926 // break;
11927 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11928 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11929 // break;
11930 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11931 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11932 // break;
11933 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11934 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11935 // break;
11936 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11937 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11938 // break;
11939 // case ITEM_MOD_HASTE_MELEE_RATING:
11940 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11941 // break;
11942 // case ITEM_MOD_HASTE_RANGED_RATING:
11943 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11944 // break;
11945 case ITEM_MOD_HASTE_SPELL_RATING:
11946 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11947 break;
11948 case ITEM_MOD_HIT_RATING:
11949 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11950 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11951 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11952 sLog.outDebug("+ %u HIT", enchant_amount);
11953 break;
11954 case ITEM_MOD_CRIT_RATING:
11955 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11956 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11957 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11958 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11959 break;
11960 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11961 // case ITEM_MOD_HIT_TAKEN_RATING:
11962 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11963 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11964 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11965 // break;
11966 // case ITEM_MOD_CRIT_TAKEN_RATING:
11967 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11968 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11969 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11970 // break;
11971 case ITEM_MOD_RESILIENCE_RATING:
11972 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11973 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11974 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11975 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11976 break;
11977 case ITEM_MOD_HASTE_RATING:
11978 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11979 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11980 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11981 sLog.outDebug("+ %u HASTE", enchant_amount);
11982 break;
11983 case ITEM_MOD_EXPERTISE_RATING:
11984 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11985 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11986 break;
11987 case ITEM_MOD_ATTACK_POWER:
11988 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11989 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11990 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11991 break;
11992 case ITEM_MOD_RANGED_ATTACK_POWER:
11993 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11994 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11995 break;
11996 case ITEM_MOD_FERAL_ATTACK_POWER:
11997 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11998 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11999 break;
12000 case ITEM_MOD_MANA_REGENERATION:
12001 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
12002 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
12003 break;
12004 case ITEM_MOD_ARMOR_PENETRATION_RATING:
12005 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
12006 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
12007 break;
12008 case ITEM_MOD_SPELL_POWER:
12009 ((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
12010 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
12011 break;
12012 case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
12013 case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
12014 default:
12015 break;
12017 break;
12019 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
12021 if(getClass() == CLASS_SHAMAN)
12023 float addValue = 0.0f;
12024 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12026 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12027 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
12029 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
12031 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12032 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
12035 break;
12037 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
12038 // processed in Player::CastItemUseSpell
12039 break;
12040 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
12041 // nothing do..
12042 break;
12043 default:
12044 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
12045 break;
12046 } /*switch(enchant_display_type)*/
12047 } /*for*/
12050 // visualize enchantment at player and equipped items
12051 if(slot == PERM_ENCHANTMENT_SLOT)
12052 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
12054 if(slot == TEMP_ENCHANTMENT_SLOT)
12055 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
12058 if(apply_dur)
12060 if(apply)
12062 // set duration
12063 uint32 duration = item->GetEnchantmentDuration(slot);
12064 if(duration > 0)
12065 AddEnchantmentDuration(item, slot, duration);
12067 else
12069 // duration == 0 will remove EnchantDuration
12070 AddEnchantmentDuration(item, slot, 0);
12075 void Player::SendEnchantmentDurations()
12077 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
12079 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
12083 void Player::SendItemDurations()
12085 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
12087 (*itr)->SendTimeUpdate(this);
12091 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12093 if(!item) // prevent crash
12094 return;
12096 // last check 2.0.10
12097 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12098 data << uint64(GetGUID()); // player GUID
12099 data << uint32(received); // 0=looted, 1=from npc
12100 data << uint32(created); // 0=received, 1=created
12101 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12102 data << uint8(item->GetBagSlot()); // bagslot
12103 // item slot, but when added to stack: 0xFFFFFFFF
12104 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
12105 data << uint32(item->GetEntry()); // item id
12106 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12107 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12108 data << uint32(count); // count of items
12109 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
12111 if (broadcast && GetGroup())
12112 GetGroup()->BroadcastPacket(&data, true);
12113 else
12114 GetSession()->SendPacket(&data);
12117 /*********************************************************/
12118 /*** QUEST SYSTEM ***/
12119 /*********************************************************/
12121 void Player::PrepareQuestMenu( uint64 guid )
12123 Object *pObject;
12124 QuestRelations* pObjectQR;
12125 QuestRelations* pObjectQIR;
12127 // pets also can have quests
12128 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12130 pObject = (Object*)pCreature;
12131 pObjectQR = &objmgr.mCreatureQuestRelations;
12132 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12134 else
12136 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12137 //only for quests which cast teleport spells on player
12138 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
12139 ASSERT(_map);
12140 GameObject *pGameObject = _map->GetGameObject(guid);
12141 if( pGameObject )
12143 pObject = (Object*)pGameObject;
12144 pObjectQR = &objmgr.mGOQuestRelations;
12145 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12147 else
12148 return;
12151 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12152 qm.ClearMenu();
12154 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12156 uint32 quest_id = i->second;
12157 QuestStatus status = GetQuestStatus( quest_id );
12158 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12159 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12160 else if ( status == QUEST_STATUS_INCOMPLETE )
12161 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12162 else if (status == QUEST_STATUS_AVAILABLE )
12163 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12166 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12168 uint32 quest_id = i->second;
12169 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12170 if(!pQuest) continue;
12172 QuestStatus status = GetQuestStatus( quest_id );
12174 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12175 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12176 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12177 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12181 void Player::SendPreparedQuest(uint64 guid)
12183 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12185 if (questMenu.Empty())
12186 return;
12188 QuestMenuItem const& qmi0 = questMenu.GetItem(0);
12190 uint32 status = qmi0.m_qIcon;
12192 // single element case
12193 if (questMenu.MenuItemCount() == 1)
12195 // Auto open -- maybe also should verify there is no greeting
12196 uint32 quest_id = qmi0.m_qId;
12197 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12199 if (pQuest)
12201 if (status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus(quest_id))
12202 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12203 else if (status == DIALOG_STATUS_UNK2)
12204 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12205 // Send completable on repeatable and autoCompletable quest if player don't have quest
12206 // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
12207 else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDaily())
12208 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true);
12209 else
12210 PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true);
12213 // multiply entries
12214 else
12216 QEmote qe;
12217 qe._Delay = 0;
12218 qe._Emote = 0;
12219 std::string title = "";
12221 // need pet case for some quests
12222 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12224 uint32 textid = pCreature->GetNpcTextId();
12225 GossipText const* gossiptext = objmgr.GetGossipText(textid);
12226 if (!gossiptext)
12228 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12229 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12230 title = "";
12232 else
12234 qe = gossiptext->Options[0].Emotes[0];
12236 if(!gossiptext->Options[0].Text_0.empty())
12238 title = gossiptext->Options[0].Text_0;
12240 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12241 if (loc_idx >= 0)
12243 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12244 if (nl)
12246 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12247 title = nl->Text_0[0][loc_idx];
12251 else
12253 title = gossiptext->Options[0].Text_1;
12255 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12256 if (loc_idx >= 0)
12258 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12259 if (nl)
12261 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12262 title = nl->Text_1[0][loc_idx];
12268 PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
12272 bool Player::IsActiveQuest( uint32 quest_id ) const
12274 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12276 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12279 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12281 Object *pObject;
12282 QuestRelations* pObjectQR;
12283 QuestRelations* pObjectQIR;
12285 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12287 pObject = (Object*)pCreature;
12288 pObjectQR = &objmgr.mCreatureQuestRelations;
12289 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12291 else
12293 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12294 //only for quests which cast teleport spells on player
12295 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
12296 ASSERT(_map);
12297 GameObject *pGameObject = _map->GetGameObject(guid);
12298 if( pGameObject )
12300 pObject = (Object*)pGameObject;
12301 pObjectQR = &objmgr.mGOQuestRelations;
12302 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12304 else
12305 return NULL;
12308 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12309 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12311 if (itr->second == nextQuestID)
12312 return objmgr.GetQuestTemplate(nextQuestID);
12315 return NULL;
12318 bool Player::CanSeeStartQuest( Quest const *pQuest )
12320 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12321 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12322 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12323 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12325 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12328 return false;
12331 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12333 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12334 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12335 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12336 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12337 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12338 && SatisfyQuestDay( pQuest, msg );
12341 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12343 if( !SatisfyQuestLog( msg ) )
12344 return false;
12346 uint32 srcitem = pQuest->GetSrcItemId();
12347 if( srcitem > 0 )
12349 uint32 count = pQuest->GetSrcItemCount();
12350 ItemPosCountVec dest;
12351 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12353 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12354 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12355 return true;
12356 else if( msg2 != EQUIP_ERR_OK )
12358 SendEquipError( msg2, NULL, NULL );
12359 return false;
12362 return true;
12365 bool Player::CanCompleteQuest( uint32 quest_id )
12367 if( quest_id )
12369 QuestStatusData& q_status = mQuestStatus[quest_id];
12370 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12371 return false; // not allow re-complete quest
12373 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12375 if(!qInfo)
12376 return false;
12378 // auto complete quest
12379 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12380 return true;
12382 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12385 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12387 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12389 if( qInfo->ReqItemCount[i] != 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12390 return false;
12394 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12396 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12398 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12399 continue;
12401 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12402 return false;
12406 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12407 return false;
12409 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12410 return false;
12412 if ( qInfo->GetRewOrReqMoney() < 0 )
12414 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12415 return false;
12418 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12419 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12420 return false;
12422 return true;
12425 return false;
12428 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12430 // Solve problem that player don't have the quest and try complete it.
12431 // if repeatable she must be able to complete event if player don't have it.
12432 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12433 if( !CanTakeQuest(pQuest, false) )
12434 return false;
12436 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12437 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12438 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i], pQuest->ReqItemCount[i]) )
12439 return false;
12441 if( !CanRewardQuest(pQuest, false) )
12442 return false;
12444 return true;
12447 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12449 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12450 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12451 return false;
12453 // daily quest can't be rewarded (25 daily quest already completed)
12454 if(!SatisfyQuestDay(pQuest,true))
12455 return false;
12457 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12458 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12459 return false;
12461 // prevent receive reward with quest items in bank
12462 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12464 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12466 if( pQuest->ReqItemCount[i] != 0 &&
12467 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12469 if(msg)
12470 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12471 return false;
12476 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12477 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12478 return false;
12480 return true;
12483 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12485 // prevent receive reward with quest items in bank or for not completed quest
12486 if(!CanRewardQuest(pQuest,msg))
12487 return false;
12489 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12491 if( pQuest->RewChoiceItemId[reward] )
12493 ItemPosCountVec dest;
12494 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12495 if( res != EQUIP_ERR_OK )
12497 SendEquipError( res, NULL, NULL );
12498 return false;
12503 if ( pQuest->GetRewItemsCount() > 0 )
12505 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12507 if( pQuest->RewItemId[i] )
12509 ItemPosCountVec dest;
12510 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12511 if( res != EQUIP_ERR_OK )
12513 SendEquipError( res, NULL, NULL );
12514 return false;
12520 return true;
12523 void Player::SendPetTameFailure(PetTameFailureReason reason)
12525 WorldPacket data(SMSG_PET_TAME_FAILURE, 1);
12526 data << uint8(reason);
12527 GetSession()->SendPacket(&data);
12530 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12532 uint16 log_slot = FindQuestSlot( 0 );
12533 assert(log_slot < MAX_QUEST_LOG_SIZE);
12535 uint32 quest_id = pQuest->GetQuestId();
12537 // if not exist then created with set uState==NEW and rewarded=false
12538 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12540 // check for repeatable quests status reset
12541 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12542 questStatusData.m_explored = false;
12544 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12546 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12547 questStatusData.m_itemcount[i] = 0;
12550 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12552 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12553 questStatusData.m_creatureOrGOcount[i] = 0;
12556 GiveQuestSourceItem( pQuest );
12557 AdjustQuestReqItemCount( pQuest, questStatusData );
12559 if( pQuest->GetRepObjectiveFaction() )
12560 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12561 GetReputationMgr().SetVisible(factionEntry);
12563 uint32 qtime = 0;
12564 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12566 uint32 limittime = pQuest->GetLimitTime();
12568 // shared timed quest
12569 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12570 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12572 AddTimedQuest( quest_id );
12573 questStatusData.m_timer = limittime * IN_MILISECONDS;
12574 qtime = static_cast<uint32>(time(NULL)) + limittime;
12576 else
12577 questStatusData.m_timer = 0;
12579 SetQuestSlot(log_slot, quest_id, qtime);
12581 if (questStatusData.uState != QUEST_NEW)
12582 questStatusData.uState = QUEST_CHANGED;
12584 //starting initial quest script
12585 if(questGiver && pQuest->GetQuestStartScript()!=0)
12586 GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12588 // Some spells applied at quest activation
12589 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12590 if(saBounds.first != saBounds.second)
12592 uint32 zone, area;
12593 GetZoneAndAreaId(zone,area);
12595 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12596 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12597 if( !HasAura(itr->second->spellId,0) )
12598 CastSpell(this,itr->second->spellId,true);
12601 UpdateForQuestWorldObjects();
12604 void Player::CompleteQuest( uint32 quest_id )
12606 if( quest_id )
12608 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12610 uint16 log_slot = FindQuestSlot( quest_id );
12611 if( log_slot < MAX_QUEST_LOG_SIZE)
12612 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12614 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12616 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12617 RewardQuest(qInfo,0,this,false);
12618 else
12619 SendQuestComplete( quest_id );
12624 void Player::IncompleteQuest( uint32 quest_id )
12626 if( quest_id )
12628 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12630 uint16 log_slot = FindQuestSlot( quest_id );
12631 if( log_slot < MAX_QUEST_LOG_SIZE)
12632 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12636 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12638 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
12639 //should work fine, cause far teleport will be executed in Player::Update()
12640 SetCanDelayTeleport(true);
12642 uint32 quest_id = pQuest->GetQuestId();
12644 for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i )
12646 if (pQuest->ReqItemId[i])
12647 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12650 RemoveTimedQuest(quest_id);
12652 if (BattleGround* bg = GetBattleGround())
12653 if (bg->GetTypeID() == BATTLEGROUND_AV)
12654 ((BattleGroundAV*)bg)->HandleQuestComplete(pQuest->GetQuestId(), this);
12656 if (pQuest->GetRewChoiceItemsCount() > 0)
12658 if (uint32 itemId = pQuest->RewChoiceItemId[reward])
12660 ItemPosCountVec dest;
12661 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK)
12663 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
12664 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12669 if (pQuest->GetRewItemsCount() > 0)
12671 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12673 if (uint32 itemId = pQuest->RewItemId[i])
12675 ItemPosCountVec dest;
12676 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i] ) == EQUIP_ERR_OK)
12678 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
12679 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12685 RewardReputation( pQuest );
12687 uint16 log_slot = FindQuestSlot( quest_id );
12688 if (log_slot < MAX_QUEST_LOG_SIZE)
12689 SetQuestSlot(log_slot,0);
12691 QuestStatusData& q_status = mQuestStatus[quest_id];
12693 // Not give XP in case already completed once repeatable quest
12694 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12696 if (getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
12697 GiveXP( XP , NULL );
12698 else
12700 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12701 ModifyMoney( money );
12702 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12705 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12706 if (pQuest->GetRewOrReqMoney())
12708 ModifyMoney( pQuest->GetRewOrReqMoney() );
12710 if (pQuest->GetRewOrReqMoney() > 0)
12711 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12714 // honor reward
12715 if (pQuest->GetRewHonorableKills())
12716 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12718 // title reward
12719 if (pQuest->GetCharTitleId())
12721 if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12722 SetTitle(titleEntry);
12725 if (pQuest->GetBonusTalents())
12727 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12728 InitTalentForLevel();
12731 // Send reward mail
12732 if (uint32 mail_template_id = pQuest->GetRewMailTemplateId())
12733 MailDraft(mail_template_id).SendMailTo(this, questGiver, MAIL_CHECK_MASK_NONE, pQuest->GetRewMailDelaySecs());
12735 if (pQuest->IsDaily())
12737 SetDailyQuestStatus(quest_id);
12738 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12741 if (!pQuest->IsRepeatable())
12742 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12743 else
12744 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12746 q_status.m_rewarded = true;
12747 if (q_status.uState != QUEST_NEW)
12748 q_status.uState = QUEST_CHANGED;
12750 if (announce)
12751 SendQuestReward( pQuest, XP, questGiver );
12753 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
12754 if (pQuest->GetRewSpellCast() > 0)
12755 CastSpell( this, pQuest->GetRewSpellCast(), true);
12756 else if ( pQuest->GetRewSpell() > 0)
12757 CastSpell( this, pQuest->GetRewSpell(), true);
12759 if (pQuest->GetZoneOrSort() > 0)
12760 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12761 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12762 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
12764 uint32 zone = 0;
12765 uint32 area = 0;
12767 // remove auras from spells with quest reward state limitations
12768 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12769 if(saEndBounds.first != saEndBounds.second)
12771 GetZoneAndAreaId(zone,area);
12773 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12774 if(!itr->second->IsFitToRequirements(this,zone,area))
12775 RemoveAurasDueToSpell(itr->second->spellId);
12778 // Some spells applied at quest reward
12779 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12780 if(saBounds.first != saBounds.second)
12782 if(!zone || !area)
12783 GetZoneAndAreaId(zone,area);
12785 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12786 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12787 if( !HasAura(itr->second->spellId,0) )
12788 CastSpell(this,itr->second->spellId,true);
12791 //lets remove flag for delayed teleports
12792 SetCanDelayTeleport(false);
12795 void Player::FailQuest(uint32 questId)
12797 if (Quest const* pQuest = objmgr.GetQuestTemplate(questId))
12799 SetQuestStatus(questId, QUEST_STATUS_FAILED);
12801 uint16 log_slot = FindQuestSlot(questId);
12803 if (log_slot < MAX_QUEST_LOG_SIZE)
12805 SetQuestSlotTimer(log_slot, 1);
12806 SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
12809 if (pQuest->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
12811 QuestStatusData& q_status = mQuestStatus[questId];
12813 RemoveTimedQuest(questId);
12814 q_status.m_timer = 0;
12816 SendQuestTimerFailed(questId);
12818 else
12819 SendQuestFailed(questId);
12823 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12825 int32 zoneOrSort = qInfo->GetZoneOrSort();
12826 int32 skillOrClass = qInfo->GetSkillOrClass();
12828 // skip zone zoneOrSort and 0 case skillOrClass
12829 if( zoneOrSort >= 0 && skillOrClass == 0 )
12830 return true;
12832 int32 questSort = -zoneOrSort;
12833 uint8 reqSortClass = ClassByQuestSort(questSort);
12835 // check class sort cases in zoneOrSort
12836 if( reqSortClass != 0 && getClass() != reqSortClass)
12838 if( msg )
12839 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12840 return false;
12843 // check class
12844 if( skillOrClass < 0 )
12846 uint8 reqClass = -int32(skillOrClass);
12847 if(getClass() != reqClass)
12849 if( msg )
12850 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12851 return false;
12854 // check skill
12855 else if( skillOrClass > 0 )
12857 uint32 reqSkill = skillOrClass;
12858 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12860 if( msg )
12861 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12862 return false;
12866 return true;
12869 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12871 if( getLevel() < qInfo->GetMinLevel() )
12873 if( msg )
12874 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12875 return false;
12877 return true;
12880 bool Player::SatisfyQuestLog( bool msg )
12882 // exist free slot
12883 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12884 return true;
12886 if( msg )
12888 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12889 GetSession()->SendPacket( &data );
12890 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12892 return false;
12895 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12897 // No previous quest (might be first quest in a series)
12898 if( qInfo->prevQuests.empty())
12899 return true;
12901 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12903 uint32 prevId = abs(*iter);
12905 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12906 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12908 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12910 // If any of the positive previous quests completed, return true
12911 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12913 // skip one-from-all exclusive group
12914 if(qPrevInfo->GetExclusiveGroup() >= 0)
12915 return true;
12917 // each-from-all exclusive group ( < 0)
12918 // can be start if only all quests in prev quest exclusive group completed and rewarded
12919 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12920 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12922 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12924 for(; iter2 != end; ++iter2)
12926 uint32 exclude_Id = iter2->second;
12928 // skip checked quest id, only state of other quests in group is interesting
12929 if(exclude_Id == prevId)
12930 continue;
12932 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12934 // alternative quest from group also must be completed and rewarded(reported)
12935 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12937 if( msg )
12938 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12939 return false;
12942 return true;
12944 // If any of the negative previous quests active, return true
12945 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12946 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12948 // skip one-from-all exclusive group
12949 if(qPrevInfo->GetExclusiveGroup() >= 0)
12950 return true;
12952 // each-from-all exclusive group ( < 0)
12953 // can be start if only all quests in prev quest exclusive group active
12954 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12955 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12957 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12959 for(; iter2 != end; ++iter2)
12961 uint32 exclude_Id = iter2->second;
12963 // skip checked quest id, only state of other quests in group is interesting
12964 if(exclude_Id == prevId)
12965 continue;
12967 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12969 // alternative quest from group also must be active
12970 if( i_exstatus == mQuestStatus.end() ||
12971 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12972 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12974 if( msg )
12975 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12976 return false;
12979 return true;
12984 // Has only positive prev. quests in non-rewarded state
12985 // and negative prev. quests in non-active state
12986 if( msg )
12987 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12989 return false;
12992 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12994 uint32 reqraces = qInfo->GetRequiredRaces();
12995 if ( reqraces == 0 )
12996 return true;
12997 if( (reqraces & getRaceMask()) == 0 )
12999 if( msg )
13000 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13001 return false;
13003 return true;
13006 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13008 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13009 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13011 if( msg )
13012 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13013 return false;
13016 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13017 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13019 if( msg )
13020 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13021 return false;
13024 return true;
13027 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13029 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13030 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13032 if( msg )
13033 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13034 return false;
13036 return true;
13039 bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
13041 if (!m_timedquests.empty() && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13043 if (msg)
13044 SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
13046 return false;
13048 return true;
13051 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13053 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13054 if(qInfo->GetExclusiveGroup() <= 0)
13055 return true;
13057 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13058 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13060 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13062 for(; iter != end; ++iter)
13064 uint32 exclude_Id = iter->second;
13066 // skip checked quest id, only state of other quests in group is interesting
13067 if(exclude_Id == qInfo->GetQuestId())
13068 continue;
13070 // not allow have daily quest if daily quest from exclusive group already recently completed
13071 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
13072 if( !SatisfyQuestDay(Nquest, false) )
13074 if( msg )
13075 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13076 return false;
13079 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13081 // alternative quest already started or completed
13082 if( i_exstatus != mQuestStatus.end()
13083 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13085 if( msg )
13086 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13087 return false;
13090 return true;
13093 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13095 if(!qInfo->GetNextQuestInChain())
13096 return true;
13098 // next quest in chain already started or completed
13099 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13100 if( itr != mQuestStatus.end()
13101 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13103 if( msg )
13104 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13105 return false;
13108 // check for all quests further up the chain
13109 // only necessary if there are quest chains with more than one quest that can be skipped
13110 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13111 return true;
13114 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13116 // No previous quest in chain
13117 if( qInfo->prevChainQuests.empty())
13118 return true;
13120 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13122 uint32 prevId = *iter;
13124 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13126 if( i_prevstatus != mQuestStatus.end() )
13128 // If any of the previous quests in chain active, return false
13129 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13130 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13132 if( msg )
13133 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13134 return false;
13138 // check for all quests further down the chain
13139 // only necessary if there are quest chains with more than one quest that can be skipped
13140 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13141 // return false;
13144 // No previous quest in chain active
13145 return true;
13148 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13150 if(!qInfo->IsDaily())
13151 return true;
13153 bool have_slot = false;
13154 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13156 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13157 if(qInfo->GetQuestId()==id)
13158 return false;
13160 if(!id)
13161 have_slot = true;
13164 if(!have_slot)
13166 if( msg )
13167 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13168 return false;
13171 return true;
13174 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13176 uint32 srcitem = pQuest->GetSrcItemId();
13177 if( srcitem > 0 )
13179 uint32 count = pQuest->GetSrcItemCount();
13180 if( count <= 0 )
13181 count = 1;
13183 ItemPosCountVec dest;
13184 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13185 if( msg == EQUIP_ERR_OK )
13187 Item * item = StoreNewItem(dest, srcitem, true);
13188 SendNewItem(item, count, true, false);
13189 return true;
13191 // player already have max amount required item, just report success
13192 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13193 return true;
13194 else
13195 SendEquipError( msg, NULL, NULL );
13196 return false;
13199 return true;
13202 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13204 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13205 if( qInfo )
13207 uint32 srcitem = qInfo->GetSrcItemId();
13208 if( srcitem > 0 )
13210 uint32 count = qInfo->GetSrcItemCount();
13211 if( count <= 0 )
13212 count = 1;
13214 // exist one case when destroy source quest item not possible:
13215 // non un-equippable item (equipped non-empty bag, for example)
13216 uint8 res = CanUnequipItems(srcitem,count);
13217 if(res != EQUIP_ERR_OK)
13219 if(msg)
13220 SendEquipError( res, NULL, NULL );
13221 return false;
13224 DestroyItemCount(srcitem, count, true, true);
13227 return true;
13230 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13232 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13233 if( qInfo )
13235 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13236 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13237 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13238 && !qInfo->IsRepeatable() )
13239 return itr->second.m_rewarded;
13241 return false;
13243 return false;
13246 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13248 if( quest_id )
13250 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13251 if( itr != mQuestStatus.end() )
13252 return itr->second.m_status;
13254 return QUEST_STATUS_NONE;
13257 bool Player::CanShareQuest(uint32 quest_id) const
13259 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13260 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13262 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13263 if( itr != mQuestStatus.end() )
13264 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13266 return false;
13269 void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
13271 if (Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
13273 QuestStatusData& q_status = mQuestStatus[quest_id];
13275 q_status.m_status = status;
13277 if (q_status.uState != QUEST_NEW)
13278 q_status.uState = QUEST_CHANGED;
13281 UpdateForQuestWorldObjects();
13284 // not used in MaNGOS, but used in scripting code
13285 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13287 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13288 if( !qInfo )
13289 return 0;
13291 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13292 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13293 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13295 return 0;
13298 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13300 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13302 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13304 uint32 reqitemcount = pQuest->ReqItemCount[i];
13305 if( reqitemcount != 0 )
13307 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i], true);
13309 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13310 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13316 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13318 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13319 if ( GetQuestSlotQuestId(i) == quest_id )
13320 return i;
13322 return MAX_QUEST_LOG_SIZE;
13325 void Player::AreaExploredOrEventHappens( uint32 questId )
13327 if( questId )
13329 uint16 log_slot = FindQuestSlot( questId );
13330 if( log_slot < MAX_QUEST_LOG_SIZE)
13332 QuestStatusData& q_status = mQuestStatus[questId];
13334 if(!q_status.m_explored)
13336 q_status.m_explored = true;
13337 if (q_status.uState != QUEST_NEW)
13338 q_status.uState = QUEST_CHANGED;
13341 if( CanCompleteQuest( questId ) )
13342 CompleteQuest( questId );
13346 //not used in mangosd, function for external script library
13347 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13349 if( Group *pGroup = GetGroup() )
13351 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13353 Player *pGroupGuy = itr->getSource();
13355 // for any leave or dead (with not released body) group member at appropriate distance
13356 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13357 pGroupGuy->AreaExploredOrEventHappens(questId);
13360 else
13361 AreaExploredOrEventHappens(questId);
13364 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13366 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13368 uint32 questid = GetQuestSlotQuestId(i);
13369 if ( questid == 0 )
13370 continue;
13372 QuestStatusData& q_status = mQuestStatus[questid];
13374 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13375 continue;
13377 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13378 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13379 continue;
13381 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
13383 uint32 reqitem = qInfo->ReqItemId[j];
13384 if ( reqitem == entry )
13386 uint32 reqitemcount = qInfo->ReqItemCount[j];
13387 uint32 curitemcount = q_status.m_itemcount[j];
13388 if ( curitemcount < reqitemcount )
13390 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13391 q_status.m_itemcount[j] += additemcount;
13392 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13394 SendQuestUpdateAddItem( qInfo, j, additemcount );
13396 if ( CanCompleteQuest( questid ) )
13397 CompleteQuest( questid );
13398 return;
13402 UpdateForQuestWorldObjects();
13405 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13407 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13409 uint32 questid = GetQuestSlotQuestId(i);
13410 if(!questid)
13411 continue;
13412 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13413 if ( !qInfo )
13414 continue;
13415 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13416 continue;
13418 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
13420 uint32 reqitem = qInfo->ReqItemId[j];
13421 if ( reqitem == entry )
13423 QuestStatusData& q_status = mQuestStatus[questid];
13425 uint32 reqitemcount = qInfo->ReqItemCount[j];
13426 uint32 curitemcount;
13427 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13428 curitemcount = q_status.m_itemcount[j];
13429 else
13430 curitemcount = GetItemCount(entry, true);
13431 if ( curitemcount < reqitemcount + count )
13433 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13434 q_status.m_itemcount[j] = curitemcount - remitemcount;
13435 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13437 IncompleteQuest( questid );
13439 return;
13443 UpdateForQuestWorldObjects();
13446 void Player::KilledMonster( CreatureInfo const* cInfo, uint64 guid )
13448 if(cInfo->Entry)
13449 KilledMonsterCredit(cInfo->Entry,guid);
13451 for(int i = 0; i < MAX_KILL_CREDIT; ++i)
13452 if(cInfo->KillCredit[i])
13453 KilledMonsterCredit(cInfo->KillCredit[i],guid);
13456 void Player::KilledMonsterCredit( uint32 entry, uint64 guid )
13458 uint32 addkillcount = 1;
13459 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13460 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13462 uint32 questid = GetQuestSlotQuestId(i);
13463 if(!questid)
13464 continue;
13466 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13467 if( !qInfo )
13468 continue;
13469 // just if !ingroup || !noraidgroup || raidgroup
13470 QuestStatusData& q_status = mQuestStatus[questid];
13471 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13473 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13475 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13477 // skip GO activate objective or none
13478 if(qInfo->ReqCreatureOrGOId[j] <=0)
13479 continue;
13481 // skip Cast at creature objective
13482 if(qInfo->ReqSpell[j] !=0 )
13483 continue;
13485 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13487 if ( reqkill == entry )
13489 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13490 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13491 if ( curkillcount < reqkillcount )
13493 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13494 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13496 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13498 if ( CanCompleteQuest( questid ) )
13499 CompleteQuest( questid );
13501 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13502 continue;
13510 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13512 bool isCreature = IS_CREATURE_GUID(guid);
13514 uint32 addCastCount = 1;
13515 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13517 uint32 questid = GetQuestSlotQuestId(i);
13518 if(!questid)
13519 continue;
13521 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13522 if ( !qInfo )
13523 continue;
13525 QuestStatusData& q_status = mQuestStatus[questid];
13527 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13529 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13531 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13533 // skip kill creature objective (0) or wrong spell casts
13534 if(qInfo->ReqSpell[j] != spell_id )
13535 continue;
13537 uint32 reqTarget = 0;
13539 if(isCreature)
13541 // creature activate objectives
13542 if(qInfo->ReqCreatureOrGOId[j] > 0)
13543 // checked at quest_template loading
13544 reqTarget = qInfo->ReqCreatureOrGOId[j];
13546 else
13548 // GO activate objective
13549 if(qInfo->ReqCreatureOrGOId[j] < 0)
13550 // checked at quest_template loading
13551 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13554 // other not this creature/GO related objectives
13555 if( reqTarget != entry )
13556 continue;
13558 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13559 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13560 if ( curCastCount < reqCastCount )
13562 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13563 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13565 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13568 if ( CanCompleteQuest( questid ) )
13569 CompleteQuest( questid );
13571 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13572 break;
13579 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13581 uint32 addTalkCount = 1;
13582 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13584 uint32 questid = GetQuestSlotQuestId(i);
13585 if(!questid)
13586 continue;
13588 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13589 if ( !qInfo )
13590 continue;
13592 QuestStatusData& q_status = mQuestStatus[questid];
13594 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13596 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13598 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13600 // skip spell casts and Gameobject objectives
13601 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13602 continue;
13604 uint32 reqTarget = 0;
13606 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13607 // checked at quest_template loading
13608 reqTarget = qInfo->ReqCreatureOrGOId[j];
13609 else
13610 continue;
13612 if ( reqTarget == entry )
13614 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13615 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13616 if ( curTalkCount < reqTalkCount )
13618 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13619 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13621 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13623 if ( CanCompleteQuest( questid ) )
13624 CompleteQuest( questid );
13626 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13627 continue;
13635 void Player::MoneyChanged( uint32 count )
13637 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13639 uint32 questid = GetQuestSlotQuestId(i);
13640 if (!questid)
13641 continue;
13643 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13644 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13646 QuestStatusData& q_status = mQuestStatus[questid];
13648 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13650 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13652 if ( CanCompleteQuest( questid ) )
13653 CompleteQuest( questid );
13656 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13658 if(int32(count) < -qInfo->GetRewOrReqMoney())
13659 IncompleteQuest( questid );
13665 void Player::ReputationChanged(FactionEntry const* factionEntry )
13667 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13669 if(uint32 questid = GetQuestSlotQuestId(i))
13671 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13673 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13675 QuestStatusData& q_status = mQuestStatus[questid];
13676 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13678 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13679 if ( CanCompleteQuest( questid ) )
13680 CompleteQuest( questid );
13682 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13684 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13685 IncompleteQuest( questid );
13693 bool Player::HasQuestForItem( uint32 itemid ) const
13695 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13697 uint32 questid = GetQuestSlotQuestId(i);
13698 if ( questid == 0 )
13699 continue;
13701 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13702 if(qs_itr == mQuestStatus.end())
13703 continue;
13705 QuestStatusData const& q_status = qs_itr->second;
13707 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13709 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13710 if(!qinfo)
13711 continue;
13713 // hide quest if player is in raid-group and quest is no raid quest
13714 if (GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID
13715 && !InBattleGround())
13716 continue;
13718 // There should be no mixed ReqItem/ReqSource drop
13719 // This part for ReqItem drop
13720 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
13722 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13723 return true;
13725 // This part - for ReqSource
13726 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
13728 // examined item is a source item
13729 if (qinfo->ReqSourceId[j] == itemid)
13731 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(itemid);
13733 // 'unique' item
13734 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13735 return true;
13737 // allows custom amount drop when not 0
13738 if (qinfo->ReqSourceCount[j])
13740 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13741 return true;
13742 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13743 return true;
13748 return false;
13751 void Player::SendQuestComplete( uint32 quest_id )
13753 if( quest_id )
13755 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13756 data << uint32(quest_id);
13757 GetSession()->SendPacket( &data );
13758 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13762 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13764 uint32 questid = pQuest->GetQuestId();
13765 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13766 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13767 data << uint32(questid);
13769 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13771 data << uint32(XP);
13772 data << uint32(pQuest->GetRewOrReqMoney());
13774 else
13776 data << uint32(0);
13777 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13780 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13781 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13782 GetSession()->SendPacket( &data );
13784 if (pQuest->GetQuestCompleteScript() != 0)
13785 GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13788 void Player::SendQuestFailed( uint32 quest_id )
13790 if( quest_id )
13792 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13793 data << uint32(quest_id);
13794 data << uint32(0); // failed reason (4 for inventory is full)
13795 GetSession()->SendPacket( &data );
13796 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13800 void Player::SendQuestTimerFailed( uint32 quest_id )
13802 if( quest_id )
13804 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13805 data << uint32(quest_id);
13806 GetSession()->SendPacket( &data );
13807 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13811 void Player::SendCanTakeQuestResponse( uint32 msg )
13813 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13814 data << uint32(msg);
13815 GetSession()->SendPacket( &data );
13816 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13819 void Player::SendQuestConfirmAccept(const Quest* pQuest, Player* pReceiver)
13821 if (pReceiver)
13823 std::string strTitle = pQuest->GetTitle();
13825 int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
13827 if (loc_idx >= 0)
13829 if (const QuestLocale* pLocale = objmgr.GetQuestLocale(pQuest->GetQuestId()))
13831 if (pLocale->Title.size() > loc_idx && !pLocale->Title[loc_idx].empty())
13832 strTitle = pLocale->Title[loc_idx];
13836 WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8));
13837 data << uint32(pQuest->GetQuestId());
13838 data << strTitle;
13839 data << uint64(GetGUID());
13840 pReceiver->GetSession()->SendPacket(&data);
13842 sLog.outDebug("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
13846 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13848 if( pPlayer )
13850 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13851 data << uint64(pPlayer->GetGUID());
13852 data << uint8(msg); // valid values: 0-8
13853 GetSession()->SendPacket( &data );
13854 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13858 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13860 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13861 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13862 //data << pQuest->ReqItemId[item_idx];
13863 //data << count;
13864 GetSession()->SendPacket( &data );
13867 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13869 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13871 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13872 if (entry < 0)
13873 // client expected gameobject template id in form (id|0x80000000)
13874 entry = (-entry) | 0x80000000;
13876 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13877 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13878 data << uint32(pQuest->GetQuestId());
13879 data << uint32(entry);
13880 data << uint32(old_count + add_count);
13881 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13882 data << uint64(guid);
13883 GetSession()->SendPacket(&data);
13885 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13886 if( log_slot < MAX_QUEST_LOG_SIZE)
13887 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13890 /*********************************************************/
13891 /*** LOAD SYSTEM ***/
13892 /*********************************************************/
13894 void Player::_LoadDeclinedNames(QueryResult* result)
13896 if(!result)
13897 return;
13899 if(m_declinedname)
13900 delete m_declinedname;
13902 m_declinedname = new DeclinedName;
13903 Field *fields = result->Fetch();
13904 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13905 m_declinedname->name[i] = fields[i].GetCppString();
13907 delete result;
13910 void Player::_LoadArenaTeamInfo(QueryResult *result)
13912 // arenateamid, played_week, played_season, personal_rating
13913 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
13914 if (!result)
13915 return;
13919 Field *fields = result->Fetch();
13921 uint32 arenateamid = fields[0].GetUInt32();
13922 uint32 played_week = fields[1].GetUInt32();
13923 uint32 played_season = fields[2].GetUInt32();
13924 uint32 wons_season = fields[3].GetUInt32();
13925 uint32 personal_rating = fields[4].GetUInt32();
13927 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13928 if(!aTeam)
13930 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid);
13931 continue;
13933 uint8 arenaSlot = aTeam->GetSlot();
13935 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_ID] = arenateamid; // TeamID
13936 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_TYPE] = aTeam->GetType(); // team type
13937 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_MEMBER] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13938 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_GAMES_WEEK] = played_week; // Played Week
13939 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_GAMES_SEASON] = played_season; // Played Season
13940 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_WINS_SEASON] = wons_season; // wins season
13941 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING] = personal_rating; // Personal Rating
13943 } while (result->NextRow());
13944 delete result;
13947 void Player::_LoadEquipmentSets(QueryResult *result)
13949 // 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));
13950 if (!result)
13951 return;
13953 uint32 count = 0;
13956 Field *fields = result->Fetch();
13958 EquipmentSet eqSet;
13960 eqSet.Guid = fields[0].GetUInt64();
13961 uint32 index = fields[1].GetUInt32();
13962 eqSet.Name = fields[2].GetCppString();
13963 eqSet.IconName = fields[3].GetCppString();
13964 eqSet.state = EQUIPMENT_SET_UNCHANGED;
13966 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
13967 eqSet.Items[i] = fields[4+i].GetUInt32();
13969 m_EquipmentSets[index] = eqSet;
13971 ++count;
13973 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
13974 break;
13975 } while (result->NextRow());
13976 delete result;
13979 void Player::_LoadBGData(QueryResult* result)
13981 if (!result)
13982 return;
13984 // Expecting only one row
13985 Field *fields = result->Fetch();
13986 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
13987 m_bgData.bgInstanceID = fields[0].GetUInt32();
13988 m_bgData.bgTeam = fields[1].GetUInt32();
13989 m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
13990 fields[2].GetFloat(), // X
13991 fields[3].GetFloat(), // Y
13992 fields[4].GetFloat(), // Z
13993 fields[5].GetFloat()); // Orientation
13994 m_bgData.taxiPath[0] = fields[7].GetUInt32();
13995 m_bgData.taxiPath[1] = fields[8].GetUInt32();
13996 m_bgData.mountSpell = fields[9].GetUInt32();
13998 delete result;
14001 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
14003 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
14004 if(!result)
14005 return false;
14007 Field *fields = result->Fetch();
14009 x = fields[0].GetFloat();
14010 y = fields[1].GetFloat();
14011 z = fields[2].GetFloat();
14012 o = fields[3].GetFloat();
14013 mapid = fields[4].GetUInt32();
14014 in_flight = !fields[5].GetCppString().empty();
14016 delete result;
14017 return true;
14020 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
14022 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
14023 if( !result )
14024 return false;
14026 Field *fields = result->Fetch();
14028 data = StrSplit(fields[0].GetCppString(), " ");
14030 delete result;
14032 return true;
14035 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
14037 if(index >= data.size())
14038 return 0;
14040 return (uint32)atoi(data[index].c_str());
14043 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
14045 float result;
14046 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
14047 memcpy(&result, &temp, sizeof(result));
14049 return result;
14052 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14054 Tokens data;
14055 if(!LoadValuesArrayFromDB(data,guid))
14056 return 0;
14058 return GetUInt32ValueFromArray(data,index);
14061 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14063 float result;
14064 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14065 memcpy(&result, &temp, sizeof(result));
14067 return result;
14070 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14072 //// 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
14073 //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);
14074 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14076 if(!result)
14078 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14079 return false;
14082 Field *fields = result->Fetch();
14084 uint32 dbAccountId = fields[1].GetUInt32();
14086 // check if the character's account in the db and the logged in account match.
14087 // player should be able to load/delete character only with correct account!
14088 if( dbAccountId != GetSession()->GetAccountId() )
14090 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14091 delete result;
14092 return false;
14095 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14097 m_name = fields[3].GetCppString();
14099 // check name limitations
14100 if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
14101 (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name)))
14103 delete result;
14104 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14105 return false;
14108 if(!LoadValues( fields[2].GetString()))
14110 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
14111 delete result;
14112 return false;
14115 // overwrite possible wrong/corrupted guid
14116 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14118 // overwrite some data fields
14119 uint32 bytes0 = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0xFF000000;
14120 bytes0 |= fields[4].GetUInt8(); // race
14121 bytes0 |= fields[5].GetUInt8() << 8; // class
14122 bytes0 |= fields[6].GetUInt8() << 16; // gender
14123 SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
14125 SetUInt32Value(UNIT_FIELD_LEVEL, fields[7].GetUInt8());
14126 SetUInt32Value(PLAYER_XP, fields[8].GetUInt32());
14127 SetUInt32Value(PLAYER_FIELD_COINAGE, fields[9].GetUInt32());
14128 SetUInt32Value(PLAYER_BYTES, fields[10].GetUInt32());
14129 SetUInt32Value(PLAYER_BYTES_2, fields[11].GetUInt32());
14130 SetUInt32Value(PLAYER_BYTES_3, (GetUInt32Value(PLAYER_BYTES_3) & ~1) | fields[6].GetUInt8());
14131 SetUInt32Value(PLAYER_FLAGS, fields[12].GetUInt32());
14133 InitDisplayIds();
14135 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14136 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14138 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
14139 SetVisibleItemSlot(slot, NULL);
14141 if (m_items[slot])
14143 delete m_items[slot];
14144 m_items[slot] = NULL;
14148 // update money limits
14149 if(GetMoney() > MAX_MONEY_AMOUNT)
14150 SetMoney(MAX_MONEY_AMOUNT);
14152 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14153 outDebugValues();
14155 //Need to call it to initialize m_team (m_team can be calculated from race)
14156 //Other way is to saves m_team into characters table.
14157 setFactionForRace(getRace());
14158 SetCharm(NULL);
14160 // load home bind and check in same time class/race pair, it used later for restore broken positions
14161 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14163 delete result;
14164 return false;
14167 InitPrimaryProfessions(); // to max set before any spell loaded
14169 // init saved position, and fix it later if problematic
14170 uint32 transGUID = fields[31].GetUInt32();
14171 Relocate(fields[13].GetFloat(),fields[14].GetFloat(),fields[15].GetFloat(),fields[17].GetFloat());
14172 SetLocationMapId(fields[16].GetUInt32());
14174 uint32 difficulty = fields[39].GetUInt32();
14175 if(difficulty >= MAX_DUNGEON_DIFFICULTY)
14176 difficulty = DUNGEON_DIFFICULTY_NORMAL;
14177 SetDungeonDifficulty(Difficulty(difficulty)); // may be changed in _LoadGroup
14179 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14181 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14183 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[40].GetUInt32();
14184 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
14185 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14187 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14189 // check arena teams integrity
14190 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14192 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14193 if(!arena_team_id)
14194 continue;
14196 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
14197 if(at->HaveMember(GetGUID()))
14198 continue;
14200 // arena team not exist or not member, cleanup fields
14201 for(int j = 0; j < ARENA_TEAM_END; ++j)
14202 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arena_slot * ARENA_TEAM_END) + j, 0);
14205 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14207 if(!IsPositionValid())
14209 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());
14210 RelocateToHomebind();
14212 transGUID = 0;
14214 m_movementInfo.t_x = 0.0f;
14215 m_movementInfo.t_y = 0.0f;
14216 m_movementInfo.t_z = 0.0f;
14217 m_movementInfo.t_o = 0.0f;
14218 m_movementInfo.t_time = 0;
14219 m_movementInfo.t_seat = -1;
14222 _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
14224 if(m_bgData.bgInstanceID) //saved in BattleGround
14226 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
14228 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14230 BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14231 AddBattleGroundQueueId(bgQueueTypeId);
14233 m_bgData.bgTypeID = currentBg->GetTypeID();
14235 //join player to battleground group
14236 currentBg->EventPlayerLoggedIn(this, GetGUID());
14237 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData.bgTeam);
14239 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14241 else
14243 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14244 SetLocationMapId(_loc.mapid);
14245 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14247 // We are not in BG anymore
14248 m_bgData.bgInstanceID = 0;
14251 else
14253 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14254 // if server restart after player save in BG or area
14255 // player can have current coordinates in to BG/Arena map, fix this
14256 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14258 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14259 SetLocationMapId(_loc.mapid);
14260 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14264 if (transGUID != 0)
14266 m_movementInfo.t_x = fields[27].GetFloat();
14267 m_movementInfo.t_y = fields[28].GetFloat();
14268 m_movementInfo.t_z = fields[29].GetFloat();
14269 m_movementInfo.t_o = fields[30].GetFloat();
14271 if( !MaNGOS::IsValidMapCoord(
14272 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14273 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14274 // transport size limited
14275 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14277 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14278 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14279 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14281 RelocateToHomebind();
14283 m_movementInfo.t_x = 0.0f;
14284 m_movementInfo.t_y = 0.0f;
14285 m_movementInfo.t_z = 0.0f;
14286 m_movementInfo.t_o = 0.0f;
14287 m_movementInfo.t_time = 0;
14288 m_movementInfo.t_seat = -1;
14290 transGUID = 0;
14294 if (transGUID != 0)
14296 for (MapManager::TransportSet::const_iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14298 if( (*iter)->GetGUIDLow() == transGUID)
14300 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14301 // client without expansion support
14302 if(GetSession()->Expansion() < transMapEntry->Expansion())
14304 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14305 break;
14308 m_transport = *iter;
14309 m_transport->AddPassenger(this);
14310 SetLocationMapId(m_transport->GetMapId());
14311 break;
14315 if(!m_transport)
14317 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14318 guid,transGUID);
14320 RelocateToHomebind();
14322 m_movementInfo.t_x = 0.0f;
14323 m_movementInfo.t_y = 0.0f;
14324 m_movementInfo.t_z = 0.0f;
14325 m_movementInfo.t_o = 0.0f;
14326 m_movementInfo.t_time = 0;
14327 m_movementInfo.t_seat = -1;
14329 transGUID = 0;
14332 else // not transport case
14334 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14335 // client without expansion support
14336 if(GetSession()->Expansion() < mapEntry->Expansion())
14338 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14339 RelocateToHomebind();
14343 // NOW player must have valid map
14344 // load the player's map here if it's not already loaded
14345 SetMap(MapManager::Instance().CreateMap(GetMapId(), this));
14347 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14348 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14350 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14351 if(at)
14352 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14353 else
14354 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());
14357 SaveRecallPosition();
14359 time_t now = time(NULL);
14360 time_t logoutTime = time_t(fields[23].GetUInt64());
14362 // since last logout (in seconds)
14363 uint64 time_diff = uint64(now - logoutTime);
14365 // set value, including drunk invisibility detection
14366 // calculate sobering. after 15 minutes logged out, the player will be sober again
14367 float soberFactor;
14368 if(time_diff > 15*MINUTE)
14369 soberFactor = 0;
14370 else
14371 soberFactor = 1-time_diff/(15.0f*MINUTE);
14372 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14373 SetDrunkValue(newDrunkenValue);
14375 m_rest_bonus = fields[22].GetFloat();
14376 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14377 float bubble0 = 0.031;
14378 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14379 float bubble1 = 0.125;
14381 if(time_diff > 0)
14383 float bubble = fields[24].GetUInt32() > 0
14384 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14385 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14387 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14390 m_cinematic = fields[19].GetUInt32();
14391 m_Played_time[PLAYED_TIME_TOTAL]= fields[20].GetUInt32();
14392 m_Played_time[PLAYED_TIME_LEVEL]= fields[21].GetUInt32();
14394 m_resetTalentsCost = fields[25].GetUInt32();
14395 m_resetTalentsTime = time_t(fields[26].GetUInt64());
14397 // reserve some flags
14398 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14400 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14401 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14403 m_taxi.LoadTaxiMask( fields[18].GetString() ); // must be before InitTaxiNodesForLevel
14405 uint32 extraflags = fields[32].GetUInt32();
14407 m_stableSlots = fields[33].GetUInt32();
14408 if(m_stableSlots > MAX_PET_STABLES)
14410 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14411 m_stableSlots = MAX_PET_STABLES;
14414 m_atLoginFlags = fields[34].GetUInt32();
14416 // Honor system
14417 // Update Honor kills data
14418 m_lastHonorUpdateTime = logoutTime;
14419 UpdateHonorFields();
14421 m_deathExpireTime = (time_t)fields[37].GetUInt64();
14422 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14423 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14425 std::string taxi_nodes = fields[38].GetCppString();
14427 delete result;
14429 // clear channel spell data (if saved at channel spell casting)
14430 SetChannelObjectGUID(0);
14431 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14433 // clear charm/summon related fields
14434 SetCharm(NULL);
14435 SetPet(NULL);
14436 SetCharmerGUID(0);
14437 SetOwnerGUID(0);
14438 SetCreatorGUID(0);
14440 // reset some aura modifiers before aura apply
14441 SetFarSightGUID(0);
14442 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14443 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14445 _LoadSkills();
14447 // make sure the unit is considered out of combat for proper loading
14448 ClearInCombat();
14450 // make sure the unit is considered not in duel for proper loading
14451 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14452 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14454 // remember loaded power/health values to restore after stats initialization and modifier applying
14455 uint32 savedHealth = GetHealth();
14456 uint32 savedPower[MAX_POWERS];
14457 for(uint32 i = 0; i < MAX_POWERS; ++i)
14458 savedPower[i] = GetPower(Powers(i));
14460 // reset stats before loading any modifiers
14461 InitStatsForLevel();
14462 InitTaxiNodesForLevel();
14463 InitGlyphsForLevel();
14464 InitRunes();
14466 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14468 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14469 //_LoadMail();
14471 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14472 _LoadGlyphAuras();
14474 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14475 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14476 m_deathState = DEAD;
14478 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14480 // after spell load, learn rewarded spell if need also
14481 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14482 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14484 // after spell and quest load
14485 InitTalentForLevel();
14486 learnDefaultSpells();
14488 // must be before inventory (some items required reputation check)
14489 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14491 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14493 // update items with duration and realtime
14494 UpdateItemDuration(time_diff, true);
14496 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14498 // unread mails and next delivery time, actual mails not loaded
14499 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14501 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14503 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14504 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14505 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14507 if(!HasTitle(curTitle))
14508 SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
14511 // Not finish taxi flight path
14512 if(m_bgData.HasTaxiPath())
14514 m_taxi.ClearTaxiDestinations();
14515 for (int i = 0; i < 2; ++i)
14516 m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
14518 else if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14520 // problems with taxi path loading
14521 TaxiNodesEntry const* nodeEntry = NULL;
14522 if(uint32 node_id = m_taxi.GetTaxiSource())
14523 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14525 if(!nodeEntry) // don't know taxi start node, to homebind
14527 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14528 RelocateToHomebind();
14530 else // have start node, to it
14532 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14533 SetLocationMapId(nodeEntry->map_id);
14534 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14537 //we can be relocated from taxi and still have an outdated Map pointer!
14538 //so we need to get a new Map pointer!
14539 SetMap(MapManager::Instance().CreateMap(GetMapId(), this));
14540 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14542 m_taxi.ClearTaxiDestinations();
14545 if(uint32 node_id = m_taxi.GetTaxiSource())
14547 // save source node as recall coord to prevent recall and fall from sky
14548 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14549 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14550 m_recallMap = nodeEntry->map_id;
14551 m_recallX = nodeEntry->x;
14552 m_recallY = nodeEntry->y;
14553 m_recallZ = nodeEntry->z;
14555 // flight will started later
14558 // has to be called after last Relocate() in Player::LoadFromDB
14559 SetFallInformation(0, GetPositionZ());
14561 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14563 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14564 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14565 if(!isAlive())
14566 RemoveAllAurasOnDeath();
14568 //apply all stat bonuses from items and auras
14569 SetCanModifyStats(true);
14570 UpdateAllStats();
14572 // restore remembered power/health values (but not more max values)
14573 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14574 for(uint32 i = 0; i < MAX_POWERS; ++i)
14575 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14577 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14578 outDebugValues();
14580 // GM state
14581 if(GetSession()->GetSecurity() > SEC_PLAYER)
14583 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14585 default:
14586 case 0: break; // disable
14587 case 1: SetGameMaster(true); break; // enable
14588 case 2: // save state
14589 if(extraflags & PLAYER_EXTRA_GM_ON)
14590 SetGameMaster(true);
14591 break;
14594 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14596 default:
14597 case 0: SetGMVisible(false); break; // invisible
14598 case 1: break; // visible
14599 case 2: // save state
14600 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14601 SetGMVisible(false);
14602 break;
14605 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14607 default:
14608 case 0: break; // disable
14609 case 1: SetAcceptTicket(true); break; // enable
14610 case 2: // save state
14611 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14612 SetAcceptTicket(true);
14613 break;
14616 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14618 default:
14619 case 0: break; // disable
14620 case 1: SetGMChat(true); break; // enable
14621 case 2: // save state
14622 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14623 SetGMChat(true);
14624 break;
14627 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14629 default:
14630 case 0: break; // disable
14631 case 1: SetAcceptWhispers(true); break; // enable
14632 case 2: // save state
14633 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14634 SetAcceptWhispers(true);
14635 break;
14639 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14641 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14642 m_achievementMgr.CheckAllAchievementCriteria();
14644 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
14646 return true;
14649 bool Player::isAllowedToLoot(Creature* creature)
14651 if(Player* recipient = creature->GetLootRecipient())
14653 if (recipient == this)
14654 return true;
14655 if( Group* otherGroup = recipient->GetGroup())
14657 Group* thisGroup = GetGroup();
14658 if(!thisGroup)
14659 return false;
14660 return thisGroup == otherGroup;
14662 return false;
14664 else
14665 // prevent other players from looting if the recipient got disconnected
14666 return !creature->hasLootRecipient();
14669 void Player::_LoadActions(QueryResult *result)
14671 m_actionButtons.clear();
14673 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14675 if(result)
14679 Field *fields = result->Fetch();
14681 uint8 button = fields[0].GetUInt8();
14682 uint32 action = fields[1].GetUInt32();
14683 uint8 type = fields[2].GetUInt8();
14685 if(ActionButton* ab = addActionButton(button, action, type))
14686 ab->uState = ACTIONBUTTON_UNCHANGED;
14687 else
14689 sLog.outError( " ...at loading, and will deleted in DB also");
14691 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14692 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14695 while( result->NextRow() );
14697 delete result;
14701 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14703 RemoveAllAuras();
14705 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14707 if(result)
14711 Field *fields = result->Fetch();
14712 uint64 caster_guid = fields[0].GetUInt64();
14713 uint32 spellid = fields[1].GetUInt32();
14714 uint32 effindex = fields[2].GetUInt32();
14715 uint32 stackcount = fields[3].GetUInt32();
14716 int32 damage = (int32)fields[4].GetUInt32();
14717 int32 maxduration = (int32)fields[5].GetUInt32();
14718 int32 remaintime = (int32)fields[6].GetUInt32();
14719 int32 remaincharges = (int32)fields[7].GetUInt32();
14721 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14722 if(!spellproto)
14724 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14725 continue;
14728 if(effindex >= 3)
14730 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14731 continue;
14734 // negative effects should continue counting down after logout
14735 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14737 if (remaintime/IN_MILISECONDS <= int32(timediff))
14738 continue;
14740 remaintime -= timediff*IN_MILISECONDS;
14743 // prevent wrong values of remaincharges
14744 if(spellproto->procCharges)
14746 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14747 remaincharges = spellproto->procCharges;
14749 else
14750 remaincharges = 0;
14753 for(uint32 i=0; i<stackcount; ++i)
14755 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14756 if(!damage)
14757 damage = aura->GetModifier()->m_amount;
14759 // reset stolen single target auras
14760 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14761 aura->SetIsSingleTarget(false);
14763 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14764 AddAura(aura);
14765 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14768 while( result->NextRow() );
14770 delete result;
14773 if(getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
14774 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14777 void Player::_LoadGlyphAuras()
14779 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14781 if (uint32 glyph = GetGlyph(i))
14783 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14785 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14787 if(gp->TypeFlags == gs->TypeFlags)
14789 CastSpell(this, gp->SpellId, true);
14790 continue;
14792 else
14793 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14795 else
14796 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14798 else
14799 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14801 // On any error remove glyph
14802 SetGlyph(i, 0);
14807 void Player::LoadCorpse()
14809 if( isAlive() )
14811 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14813 else
14815 if(Corpse *corpse = GetCorpse())
14817 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14819 else
14821 //Prevent Dead Player login without corpse
14822 ResurrectPlayer(0.5f);
14827 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14829 //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());
14830 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14831 //NOTE: the "order by `bag`" is important because it makes sure
14832 //the bagMap is filled before items in the bags are loaded
14833 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14834 //expected to be equipped before offhand items (TODO: fixme)
14836 uint32 zone = GetZoneId();
14838 if (result)
14840 std::list<Item*> problematicItems;
14842 // prevent items from being added to the queue when stored
14843 m_itemUpdateQueueBlocked = true;
14846 Field *fields = result->Fetch();
14847 uint32 bag_guid = fields[1].GetUInt32();
14848 uint8 slot = fields[2].GetUInt8();
14849 uint32 item_guid = fields[3].GetUInt32();
14850 uint32 item_id = fields[4].GetUInt32();
14852 ItemPrototype const * proto = ObjectMgr::GetItemPrototype(item_id);
14854 if(!proto)
14856 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14857 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14858 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14859 continue;
14862 Item *item = NewItemOrBag(proto);
14864 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14866 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14867 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14868 item->FSetState(ITEM_REMOVED);
14869 item->SaveToDB(); // it also deletes item object !
14870 continue;
14873 // not allow have in alive state item limited to another map/zone
14874 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14876 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14877 item->FSetState(ITEM_REMOVED);
14878 item->SaveToDB(); // it also deletes item object !
14879 continue;
14882 // "Conjured items disappear if you are logged out for more than 15 minutes"
14883 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14885 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14886 item->FSetState(ITEM_REMOVED);
14887 item->SaveToDB(); // it also deletes item object !
14888 continue;
14891 bool success = true;
14893 if (!bag_guid)
14895 // the item is not in a bag
14896 item->SetContainer( NULL );
14897 item->SetSlot(slot);
14899 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14901 ItemPosCountVec dest;
14902 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14903 item = StoreItem(dest, item, true);
14904 else
14905 success = false;
14907 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14909 uint16 dest;
14910 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14911 QuickEquipItem(dest, item);
14912 else
14913 success = false;
14915 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14917 ItemPosCountVec dest;
14918 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14919 item = BankItem(dest, item, true);
14920 else
14921 success = false;
14924 if(success)
14926 // store bags that may contain items in them
14927 if(item->IsBag() && IsBagPos(item->GetPos()))
14928 bagMap[item_guid] = (Bag*)item;
14931 else
14933 item->SetSlot(NULL_SLOT);
14934 // the item is in a bag, find the bag
14935 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
14936 if(itr != bagMap.end() && slot < itr->second->GetBagSize())
14937 itr->second->StoreItem(slot, item, true );
14938 else
14939 success = false;
14942 // item's state may have changed after stored
14943 if (success)
14944 item->SetState(ITEM_UNCHANGED, this);
14945 else
14947 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);
14948 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14949 problematicItems.push_back(item);
14951 } while (result->NextRow());
14953 delete result;
14954 m_itemUpdateQueueBlocked = false;
14956 // send by mail problematic items
14957 while(!problematicItems.empty())
14959 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14961 // fill mail
14962 MailDraft draft(subject);
14964 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14966 Item* item = problematicItems.front();
14967 problematicItems.pop_front();
14969 draft.AddItem(item);
14972 draft.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
14975 //if(isAlive())
14976 _ApplyAllItemMods();
14979 // load mailed item which should receive current player
14980 void Player::_LoadMailedItems(Mail *mail)
14982 // data needs to be at first place for Item::LoadFromDB
14983 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);
14984 if(!result)
14985 return;
14989 Field *fields = result->Fetch();
14990 uint32 item_guid_low = fields[1].GetUInt32();
14991 uint32 item_template = fields[2].GetUInt32();
14993 mail->AddItem(item_guid_low, item_template);
14995 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(item_template);
14997 if(!proto)
14999 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);
15000 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15001 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
15002 continue;
15005 Item *item = NewItemOrBag(proto);
15007 if(!item->LoadFromDB(item_guid_low, 0, result))
15009 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
15010 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15011 item->FSetState(ITEM_REMOVED);
15012 item->SaveToDB(); // it also deletes item object !
15013 continue;
15016 AddMItem(item);
15017 } while (result->NextRow());
15019 delete result;
15022 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
15024 //set a count of unread mails
15025 //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);
15026 if (resultUnread)
15028 Field *fieldMail = resultUnread->Fetch();
15029 unReadMails = fieldMail[0].GetUInt8();
15030 delete resultUnread;
15033 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
15034 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
15035 if (resultDelivery)
15037 Field *fieldMail = resultDelivery->Fetch();
15038 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
15039 delete resultDelivery;
15043 void Player::_LoadMail()
15045 m_mail.clear();
15046 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15047 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());
15048 if(result)
15052 Field *fields = result->Fetch();
15053 Mail *m = new Mail;
15054 m->messageID = fields[0].GetUInt32();
15055 m->messageType = fields[1].GetUInt8();
15056 m->sender = fields[2].GetUInt32();
15057 m->receiver = fields[3].GetUInt32();
15058 m->subject = fields[4].GetCppString();
15059 m->itemTextId = fields[5].GetUInt32();
15060 bool has_items = fields[6].GetBool();
15061 m->expire_time = (time_t)fields[7].GetUInt64();
15062 m->deliver_time = (time_t)fields[8].GetUInt64();
15063 m->money = fields[9].GetUInt32();
15064 m->COD = fields[10].GetUInt32();
15065 m->checked = fields[11].GetUInt32();
15066 m->stationery = fields[12].GetUInt8();
15067 m->mailTemplateId = fields[13].GetInt16();
15069 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15071 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15072 m->mailTemplateId = 0;
15075 m->state = MAIL_STATE_UNCHANGED;
15077 if (has_items)
15078 _LoadMailedItems(m);
15080 m_mail.push_back(m);
15081 } while( result->NextRow() );
15082 delete result;
15084 m_mailsLoaded = true;
15087 void Player::LoadPet()
15089 //fixme: the pet should still be loaded if the player is not in world
15090 // just not added to the map
15091 if(IsInWorld())
15093 Pet *pet = new Pet;
15094 if(!pet->LoadPetFromDB(this,0,0,true))
15095 delete pet;
15099 void Player::_LoadQuestStatus(QueryResult *result)
15101 mQuestStatus.clear();
15103 uint32 slot = 0;
15105 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15106 //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());
15108 if(result)
15112 Field *fields = result->Fetch();
15114 uint32 quest_id = fields[0].GetUInt32();
15115 // used to be new, no delete?
15116 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15117 if( pQuest )
15119 // find or create
15120 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15122 uint32 qstatus = fields[1].GetUInt32();
15123 if(qstatus < MAX_QUEST_STATUS)
15124 questStatusData.m_status = QuestStatus(qstatus);
15125 else
15127 questStatusData.m_status = QUEST_STATUS_NONE;
15128 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15131 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15132 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15134 time_t quest_time = time_t(fields[4].GetUInt64());
15136 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15138 AddTimedQuest( quest_id );
15140 if (quest_time <= sWorld.GetGameTime())
15141 questStatusData.m_timer = 1;
15142 else
15143 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
15145 else
15146 quest_time = 0;
15148 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15149 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15150 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15151 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15152 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15153 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15154 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15155 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15157 questStatusData.uState = QUEST_UNCHANGED;
15159 // add to quest log
15160 if (slot < MAX_QUEST_LOG_SIZE &&
15161 ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
15162 questStatusData.m_status == QUEST_STATUS_COMPLETE ||
15163 questStatusData.m_status == QUEST_STATUS_FAILED) &&
15164 (!questStatusData.m_rewarded || pQuest->IsRepeatable())))
15166 SetQuestSlot(slot, quest_id, quest_time);
15168 if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
15169 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
15171 if (questStatusData.m_status == QUEST_STATUS_FAILED)
15172 SetQuestSlotState(slot, QUEST_STATE_FAIL);
15174 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15175 if(questStatusData.m_creatureOrGOcount[idx])
15176 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
15178 ++slot;
15181 if(questStatusData.m_rewarded)
15183 // learn rewarded spell if unknown
15184 learnQuestRewardedSpells(pQuest);
15186 // set rewarded title if any
15187 if(pQuest->GetCharTitleId())
15189 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15190 SetTitle(titleEntry);
15193 if(pQuest->GetBonusTalents())
15194 m_questRewardTalentCount += pQuest->GetBonusTalents();
15197 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15200 while( result->NextRow() );
15202 delete result;
15205 // clear quest log tail
15206 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15207 SetQuestSlot(i, 0);
15210 void Player::_LoadDailyQuestStatus(QueryResult *result)
15212 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15213 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15215 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15217 if(result)
15219 uint32 quest_daily_idx = 0;
15223 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15225 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15226 break;
15229 Field *fields = result->Fetch();
15231 uint32 quest_id = fields[0].GetUInt32();
15233 // save _any_ from daily quest times (it must be after last reset anyway)
15234 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15236 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15237 if( !pQuest )
15238 continue;
15240 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15241 ++quest_daily_idx;
15243 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15245 while( result->NextRow() );
15247 delete result;
15250 m_DailyQuestChanged = false;
15253 void Player::_LoadSpells(QueryResult *result)
15255 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15257 if(result)
15261 Field *fields = result->Fetch();
15263 addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool());
15265 while( result->NextRow() );
15267 delete result;
15271 void Player::_LoadGroup(QueryResult *result)
15273 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15274 if (result)
15276 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15277 delete result;
15279 if (Group* group = objmgr.GetGroupByLeader(leaderGuid))
15281 uint8 subgroup = group->GetMemberGroup(GetGUID());
15282 SetGroup(group, subgroup);
15283 if (getLevel() >= LEVELREQUIREMENT_HEROIC)
15285 // the group leader may change the instance difficulty while the player is offline
15286 SetDungeonDifficulty(group->GetDungeonDifficulty());
15287 SetRaidDifficulty(group->GetRaidDifficulty());
15293 void Player::_LoadBoundInstances(QueryResult *result)
15295 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15296 m_boundInstances[i].clear();
15298 Group *group = GetGroup();
15300 //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));
15301 if(result)
15305 Field *fields = result->Fetch();
15306 bool perm = fields[1].GetBool();
15307 uint32 mapId = fields[2].GetUInt32();
15308 uint32 instanceId = fields[0].GetUInt32();
15309 uint8 difficulty = fields[3].GetUInt8();
15311 time_t resetTime = (time_t)fields[4].GetUInt64();
15312 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15313 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15314 // and in that case it is not used
15316 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15317 if(!mapEntry || !mapEntry->IsDungeon())
15319 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15320 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15321 continue;
15324 if(difficulty >= MAX_DIFFICULTY)
15326 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15327 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15328 continue;
15331 MapDifficulty const* mapDiff = GetMapDifficultyData(mapId,Difficulty(difficulty));
15332 if(!mapDiff)
15334 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15335 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15336 continue;
15339 if(!perm && group)
15341 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);
15342 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15343 continue;
15346 // since non permanent binds are always solo bind, they can always be reset
15347 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, !perm, true);
15348 if(save) BindToInstance(save, perm, true);
15349 } while(result->NextRow());
15350 delete result;
15354 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
15356 // some instances only have one difficulty
15357 MapDifficulty const* mapDiff = GetMapDifficultyData(mapid,difficulty);
15358 if(!mapDiff)
15359 return NULL;
15361 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15362 if(itr != m_boundInstances[difficulty].end())
15363 return &itr->second;
15364 else
15365 return NULL;
15368 void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
15370 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15371 UnbindInstance(itr, difficulty, unload);
15374 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
15376 if(itr != m_boundInstances[difficulty].end())
15378 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15379 itr->second.save->RemovePlayer(this); // save can become invalid
15380 m_boundInstances[difficulty].erase(itr++);
15384 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15386 if(save)
15388 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15389 if(bind.save)
15391 // update the save when the group kills a boss
15392 if(permanent != bind.perm || save != bind.save)
15393 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());
15395 else
15396 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15398 if(bind.save != save)
15400 if(bind.save) bind.save->RemovePlayer(this);
15401 save->AddPlayer(this);
15404 if(permanent) save->SetCanReset(false);
15406 bind.save = save;
15407 bind.perm = permanent;
15408 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());
15409 return &bind;
15411 else
15412 return NULL;
15415 void Player::SendRaidInfo()
15417 uint32 counter = 0;
15419 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15421 size_t p_counter = data.wpos();
15422 data << uint32(counter); // placeholder
15424 time_t now = time(NULL);
15426 for(int i = 0; i < MAX_DIFFICULTY; ++i)
15428 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15430 if(itr->second.perm)
15432 InstanceSave *save = itr->second.save;
15433 data << uint32(save->GetMapId()); // map id
15434 data << uint32(save->GetDifficulty()); // difficulty
15435 data << uint64(save->GetInstanceId()); // instance id
15436 data << uint8(1); // expired = 0
15437 data << uint8(0); // extended = 1
15438 data << uint32(save->GetResetTime() - now); // reset time
15439 ++counter;
15443 data.put<uint32>(p_counter, counter);
15444 GetSession()->SendPacket(&data);
15448 - called on every successful teleportation to a map
15450 void Player::SendSavedInstances()
15452 bool hasBeenSaved = false;
15453 WorldPacket data;
15455 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15457 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15459 if(itr->second.perm) // only permanent binds are sent
15461 hasBeenSaved = true;
15462 break;
15467 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15468 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15469 data << uint32(hasBeenSaved);
15470 GetSession()->SendPacket(&data);
15472 if(!hasBeenSaved)
15473 return;
15475 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15477 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15479 if(itr->second.perm)
15481 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15482 data << uint32(itr->second.save->GetMapId());
15483 GetSession()->SendPacket(&data);
15489 /// convert the player's binds to the group
15490 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15492 bool has_binds = false;
15493 bool has_solo = false;
15495 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15496 assert(player_guid);
15498 // copy all binds to the group, when changing leader it's assumed the character
15499 // will not have any solo binds
15501 if(player)
15503 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15505 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15507 has_binds = true;
15508 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15509 // permanent binds are not removed
15510 if(!itr->second.perm)
15512 // increments itr in call
15513 player->UnbindInstance(itr, Difficulty(i), true);
15514 has_solo = true;
15516 else
15517 ++itr;
15522 // if the player's not online we don't know what binds it has
15523 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));
15524 // the following should not get executed when changing leaders
15525 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15528 bool Player::_LoadHomeBind(QueryResult *result)
15530 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15531 if(!info)
15533 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15534 return false;
15537 bool ok = false;
15538 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15539 if (result)
15541 Field *fields = result->Fetch();
15542 m_homebindMapId = fields[0].GetUInt32();
15543 m_homebindZoneId = fields[1].GetUInt16();
15544 m_homebindX = fields[2].GetFloat();
15545 m_homebindY = fields[3].GetFloat();
15546 m_homebindZ = fields[4].GetFloat();
15547 delete result;
15549 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15551 // accept saved data only for valid position (and non instanceable), and accessable
15552 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15553 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15555 ok = true;
15557 else
15558 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15561 if(!ok)
15563 m_homebindMapId = info->mapId;
15564 m_homebindZoneId = info->zoneId;
15565 m_homebindX = info->positionX;
15566 m_homebindY = info->positionY;
15567 m_homebindZ = info->positionZ;
15569 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);
15572 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15573 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15575 return true;
15578 /*********************************************************/
15579 /*** SAVE SYSTEM ***/
15580 /*********************************************************/
15582 void Player::SaveToDB()
15584 // delay auto save at any saves (manual, in code, or autosave)
15585 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15587 //lets allow only players in world to be saved
15588 if(IsBeingTeleportedFar())
15590 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
15591 return;
15594 // first save/honor gain after midnight will also update the player's honor fields
15595 UpdateHonorFields();
15597 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15598 outDebugValues();
15600 CharacterDatabase.BeginTransaction();
15602 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15604 std::string sql_name = m_name;
15605 CharacterDatabase.escape_string(sql_name);
15607 std::ostringstream ss;
15608 ss << "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
15609 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15610 "taximask, online, cinematic, "
15611 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15612 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15613 "death_expire_time, taxi_path, arena_pending_points) VALUES ("
15614 << GetGUIDLow() << ", "
15615 << GetSession()->GetAccountId() << ", '"
15616 << sql_name << "', "
15617 << (uint32)getRace() << ", "
15618 << (uint32)getClass() << ", "
15619 << (uint32)getGender() << ", "
15620 << getLevel() << ", "
15621 << GetUInt32Value(PLAYER_XP) << ", "
15622 << GetMoney() << ", "
15623 << GetUInt32Value(PLAYER_BYTES) << ", "
15624 << GetUInt32Value(PLAYER_BYTES_2) << ", "
15625 << GetUInt32Value(PLAYER_FLAGS) << ", ";
15627 if(!IsBeingTeleported())
15629 ss << GetMapId() << ", "
15630 << (uint32)GetDungeonDifficulty() << ", "
15631 << finiteAlways(GetPositionX()) << ", "
15632 << finiteAlways(GetPositionY()) << ", "
15633 << finiteAlways(GetPositionZ()) << ", "
15634 << finiteAlways(GetOrientation()) << ", '";
15636 else
15638 ss << GetTeleportDest().mapid << ", "
15639 << (uint32)GetDungeonDifficulty() << ", "
15640 << finiteAlways(GetTeleportDest().coord_x) << ", "
15641 << finiteAlways(GetTeleportDest().coord_y) << ", "
15642 << finiteAlways(GetTeleportDest().coord_z) << ", "
15643 << finiteAlways(GetTeleportDest().orientation) << ", '";
15646 uint16 i;
15647 for( i = 0; i < m_valuesCount; ++i )
15649 ss << GetUInt32Value(i) << " ";
15652 ss << "', ";
15654 ss << m_taxi << ", "; // string with TaxiMaskSize numbers
15656 ss << (IsInWorld() ? 1 : 0) << ", ";
15658 ss << m_cinematic << ", ";
15660 ss << m_Played_time[PLAYED_TIME_TOTAL] << ", ";
15661 ss << m_Played_time[PLAYED_TIME_LEVEL] << ", ";
15663 ss << finiteAlways(m_rest_bonus) << ", ";
15664 ss << (uint64)time(NULL) << ", ";
15665 ss << (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0) << ", ";
15666 //save, far from tavern/city
15667 //save, but in tavern/city
15668 ss << m_resetTalentsCost << ", ";
15669 ss << (uint64)m_resetTalentsTime << ", ";
15671 ss << finiteAlways(m_movementInfo.t_x) << ", ";
15672 ss << finiteAlways(m_movementInfo.t_y) << ", ";
15673 ss << finiteAlways(m_movementInfo.t_z) << ", ";
15674 ss << finiteAlways(m_movementInfo.t_o) << ", ";
15675 if (m_transport)
15676 ss << m_transport->GetGUIDLow();
15677 else
15678 ss << "0";
15679 ss << ", ";
15681 ss << m_ExtraFlags << ", ";
15683 ss << uint32(m_stableSlots) << ", "; // to prevent save uint8 as char
15685 ss << uint32(m_atLoginFlags) << ", ";
15687 ss << GetZoneId() << ", ";
15689 ss << (uint64)m_deathExpireTime << ", '";
15691 ss << m_taxi.SaveTaxiDestinationsToString() << "', ";
15692 ss << "'0' "; // arena_pending_points
15693 ss << ")";
15695 CharacterDatabase.Execute( ss.str().c_str() );
15697 if(m_mailsUpdated) //save mails only when needed
15698 _SaveMail();
15700 _SaveBGData();
15701 _SaveInventory();
15702 _SaveQuestStatus();
15703 _SaveDailyQuestStatus();
15704 _SaveSpells();
15705 _SaveSpellCooldowns();
15706 _SaveActions();
15707 _SaveAuras();
15708 m_achievementMgr.SaveToDB();
15709 m_reputationMgr.SaveToDB();
15710 _SaveEquipmentSets();
15711 GetSession()->SaveTutorialsData(); // changed only while character in game
15713 CharacterDatabase.CommitTransaction();
15715 // save pet (hunter pet level and experience and all type pets health/mana).
15716 if(Pet* pet = GetPet())
15717 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15720 // fast save function for item/money cheating preventing - save only inventory and money state
15721 void Player::SaveInventoryAndGoldToDB()
15723 _SaveInventory();
15724 SaveGoldToDB();
15727 void Player::SaveGoldToDB()
15729 CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
15732 void Player::_SaveActions()
15734 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15736 switch (itr->second.uState)
15738 case ACTIONBUTTON_NEW:
15739 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type) VALUES ('%u', '%u', '%u', '%u')",
15740 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.GetAction(), (uint32)itr->second.GetType() );
15741 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15742 ++itr;
15743 break;
15744 case ACTIONBUTTON_CHANGED:
15745 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' ",
15746 (uint32)itr->second.GetAction(), (uint32)itr->second.GetType(), GetGUIDLow(), (uint32)itr->first );
15747 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15748 ++itr;
15749 break;
15750 case ACTIONBUTTON_DELETED:
15751 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15752 m_actionButtons.erase(itr++);
15753 break;
15754 default:
15755 ++itr;
15756 break;
15761 void Player::_SaveAuras()
15763 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15765 AuraMap const& auras = GetAuras();
15767 if (auras.empty())
15768 return;
15770 spellEffectPair lastEffectPair = auras.begin()->first;
15771 uint32 stackCounter = 1;
15773 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15775 if(itr == auras.end() || lastEffectPair != itr->first)
15777 AuraMap::const_iterator itr2 = itr;
15778 // save previous spellEffectPair to db
15779 itr2--;
15781 //skip all auras from spells that are passive
15782 //do not save single target auras (unless they were cast by the player)
15783 if (!itr2->second->IsPassive() && (itr2->second->GetCasterGUID() == GetGUID() || !itr2->second->IsSingleTarget()))
15785 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15786 "VALUES ('%u', '" UI64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15787 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()));
15790 if(itr == auras.end())
15791 break;
15794 if (lastEffectPair == itr->first)
15795 stackCounter++;
15796 else
15798 lastEffectPair = itr->first;
15799 stackCounter = 1;
15804 void Player::_SaveInventory()
15806 // force items in buyback slots to new state
15807 // and remove those that aren't already
15808 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
15810 Item *item = m_items[i];
15811 if (!item || item->GetState() == ITEM_NEW) continue;
15812 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15813 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15814 m_items[i]->FSetState(ITEM_NEW);
15817 // update enchantment durations
15818 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15820 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15823 // if no changes
15824 if (m_itemUpdateQueue.empty()) return;
15826 // do not save if the update queue is corrupt
15827 bool error = false;
15828 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15830 Item *item = m_itemUpdateQueue[i];
15831 if(!item || item->GetState() == ITEM_REMOVED) continue;
15832 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15834 if (test == NULL)
15836 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());
15837 error = true;
15839 else if (test != item)
15841 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());
15842 error = true;
15846 if (error)
15848 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15849 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15850 return;
15853 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15855 Item *item = m_itemUpdateQueue[i];
15856 if(!item) continue;
15858 Bag *container = item->GetContainer();
15859 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15861 switch(item->GetState())
15863 case ITEM_NEW:
15864 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());
15865 break;
15866 case ITEM_CHANGED:
15867 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());
15868 break;
15869 case ITEM_REMOVED:
15870 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15871 break;
15872 case ITEM_UNCHANGED:
15873 break;
15876 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15878 m_itemUpdateQueue.clear();
15881 void Player::_SaveMail()
15883 if (!m_mailsLoaded)
15884 return;
15886 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15888 Mail *m = (*itr);
15889 if (m->state == MAIL_STATE_CHANGED)
15891 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'",
15892 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15893 if(m->removedItems.size())
15895 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15896 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15897 m->removedItems.clear();
15899 m->state = MAIL_STATE_UNCHANGED;
15901 else if (m->state == MAIL_STATE_DELETED)
15903 if (m->HasItems())
15904 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15905 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15906 if (m->itemTextId)
15907 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15908 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15909 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15913 //deallocate deleted mails...
15914 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15916 if ((*itr)->state == MAIL_STATE_DELETED)
15918 Mail* m = *itr;
15919 m_mail.erase(itr);
15920 delete m;
15921 itr = m_mail.begin();
15923 else
15924 ++itr;
15927 m_mailsUpdated = false;
15930 void Player::_SaveQuestStatus()
15932 // we don't need transactions here.
15933 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15935 switch (i->second.uState)
15937 case QUEST_NEW :
15938 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15939 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15940 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]);
15941 break;
15942 case QUEST_CHANGED :
15943 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' ",
15944 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 );
15945 break;
15946 case QUEST_UNCHANGED:
15947 break;
15949 i->second.uState = QUEST_UNCHANGED;
15953 void Player::_SaveDailyQuestStatus()
15955 if(!m_DailyQuestChanged)
15956 return;
15958 m_DailyQuestChanged = false;
15960 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15962 // we don't need transactions here.
15963 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15964 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15965 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15966 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
15967 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15970 void Player::_SaveSpells()
15972 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15974 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15975 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15977 // add only changed/new not dependent spells
15978 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15979 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);
15981 if (itr->second->state == PLAYERSPELL_REMOVED)
15983 delete itr->second;
15984 m_spells.erase(itr++);
15986 else
15988 itr->second->state = PLAYERSPELL_UNCHANGED;
15989 ++itr;
15995 void Player::outDebugValues() const
15997 if(!sLog.IsOutDebug()) // optimize disabled debug output
15998 return;
16000 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
16001 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
16002 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
16003 sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
16004 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
16005 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
16006 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
16007 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
16008 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
16009 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
16010 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
16011 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
16014 /*********************************************************/
16015 /*** FLOOD FILTER SYSTEM ***/
16016 /*********************************************************/
16018 void Player::UpdateSpeakTime()
16020 // ignore chat spam protection for GMs in any mode
16021 if(GetSession()->GetSecurity() > SEC_PLAYER)
16022 return;
16024 time_t current = time (NULL);
16025 if(m_speakTime > current)
16027 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
16028 if(!max_count)
16029 return;
16031 ++m_speakCount;
16032 if(m_speakCount >= max_count)
16034 // prevent overwrite mute time, if message send just before mutes set, for example.
16035 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
16036 if(GetSession()->m_muteTime < new_mute)
16037 GetSession()->m_muteTime = new_mute;
16039 m_speakCount = 0;
16042 else
16043 m_speakCount = 0;
16045 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
16048 bool Player::CanSpeak() const
16050 return GetSession()->m_muteTime <= time (NULL);
16053 /*********************************************************/
16054 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16055 /*********************************************************/
16057 void Player::SendAttackSwingNotInRange()
16059 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16060 GetSession()->SendPacket( &data );
16063 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16065 std::ostringstream ss;
16066 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16067 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16068 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16069 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16070 sLog.outDebug(ss.str().c_str());
16071 CharacterDatabase.Execute(ss.str().c_str());
16074 void Player::SaveDataFieldToDB()
16076 std::ostringstream ss;
16077 ss<<"UPDATE characters SET data='";
16079 for(uint16 i = 0; i < m_valuesCount; ++i )
16081 ss << GetUInt32Value(i) << " ";
16083 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16085 CharacterDatabase.Execute(ss.str().c_str());
16088 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16090 std::ostringstream ss2;
16091 ss2<<"UPDATE characters SET data='";
16092 int i=0;
16093 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16095 ss2<<tokens[i]<<" ";
16097 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16099 return CharacterDatabase.Execute(ss2.str().c_str());
16102 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16104 char buf[11];
16105 snprintf(buf,11,"%u",value);
16107 if(index >= tokens.size())
16108 return;
16110 tokens[index] = buf;
16113 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16115 Tokens tokens;
16116 if(!LoadValuesArrayFromDB(tokens,guid))
16117 return;
16119 if(index >= tokens.size())
16120 return;
16122 char buf[11];
16123 snprintf(buf,11,"%u",value);
16124 tokens[index] = buf;
16126 SaveValuesArrayInDB(tokens,guid);
16129 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16131 uint32 temp;
16132 memcpy(&temp, &value, sizeof(value));
16133 Player::SetUInt32ValueInDB(index, temp, guid);
16136 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16138 // 0
16139 QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
16140 if(!result)
16141 return;
16143 Field* fields = result->Fetch();
16145 uint32 player_bytes2 = fields[0].GetUInt32();
16146 player_bytes2 &= ~0xFF;
16147 player_bytes2 |= facialHair;
16149 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));
16151 delete result;
16154 void Player::SendAttackSwingDeadTarget()
16156 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16157 GetSession()->SendPacket( &data );
16160 void Player::SendAttackSwingCantAttack()
16162 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16163 GetSession()->SendPacket( &data );
16166 void Player::SendAttackSwingCancelAttack()
16168 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16169 GetSession()->SendPacket( &data );
16172 void Player::SendAttackSwingBadFacingAttack()
16174 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16175 GetSession()->SendPacket( &data );
16178 void Player::SendAutoRepeatCancel(Unit *target)
16180 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
16181 data.append(target->GetPackGUID()); // may be it's target guid
16182 GetSession()->SendPacket( &data );
16185 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16187 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16188 data << Area;
16189 data << Experience;
16190 GetSession()->SendPacket(&data);
16193 void Player::SendDungeonDifficulty(bool IsInGroup)
16195 uint8 val = 0x00000001;
16196 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16197 data << (uint32)GetDungeonDifficulty();
16198 data << uint32(val);
16199 data << uint32(IsInGroup);
16200 GetSession()->SendPacket(&data);
16203 void Player::SendRaidDifficulty(bool IsInGroup)
16205 uint8 val = 0x00000001;
16206 WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
16207 data << uint32(GetRaidDifficulty());
16208 data << uint32(val);
16209 data << uint32(IsInGroup);
16210 GetSession()->SendPacket(&data);
16213 void Player::SendResetFailedNotify(uint32 mapid)
16215 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16216 data << uint32(mapid);
16217 GetSession()->SendPacket(&data);
16220 /// Reset all solo instances and optionally send a message on success for each
16221 void Player::ResetInstances(uint8 method, bool isRaid)
16223 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16225 // we assume that when the difficulty changes, all instances that can be reset will be
16226 Difficulty diff = GetDifficulty(isRaid);
16228 for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
16230 InstanceSave *p = itr->second.save;
16231 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16232 if(!entry || entry->IsRaid() != isRaid || !p->CanReset())
16234 ++itr;
16235 continue;
16238 if(method == INSTANCE_RESET_ALL)
16240 // the "reset all instances" method can only reset normal maps
16241 if(entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
16243 ++itr;
16244 continue;
16248 // if the map is loaded, reset it
16249 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16250 if(map && map->IsDungeon())
16251 ((InstanceMap*)map)->Reset(method);
16253 // since this is a solo instance there should not be any players inside
16254 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16255 SendResetInstanceSuccess(p->GetMapId());
16257 p->DeleteFromDB();
16258 m_boundInstances[diff].erase(itr++);
16260 // the following should remove the instance save from the manager and delete it as well
16261 p->RemovePlayer(this);
16265 void Player::SendResetInstanceSuccess(uint32 MapId)
16267 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16268 data << MapId;
16269 GetSession()->SendPacket(&data);
16272 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16274 // TODO: find what other fail reasons there are besides players in the instance
16275 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16276 data << reason;
16277 data << MapId;
16278 GetSession()->SendPacket(&data);
16281 /*********************************************************/
16282 /*** Update timers ***/
16283 /*********************************************************/
16285 ///checks the 15 afk reports per 5 minutes limit
16286 void Player::UpdateAfkReport(time_t currTime)
16288 if(m_bgData.bgAfkReportedTimer <= currTime)
16290 m_bgData.bgAfkReportedCount = 0;
16291 m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
16295 void Player::UpdateContestedPvP(uint32 diff)
16297 if(!m_contestedPvPTimer||isInCombat())
16298 return;
16299 if(m_contestedPvPTimer <= diff)
16301 ResetContestedPvP();
16303 else
16304 m_contestedPvPTimer -= diff;
16307 void Player::UpdatePvPFlag(time_t currTime)
16309 if(!IsPvP())
16310 return;
16311 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16312 return;
16314 UpdatePvP(false);
16317 void Player::UpdateDuelFlag(time_t currTime)
16319 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16320 return;
16322 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16323 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16325 duel->startTimer = 0;
16326 duel->startTime = currTime;
16327 duel->opponent->duel->startTimer = 0;
16328 duel->opponent->duel->startTime = currTime;
16331 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16333 if(!pet)
16334 pet = GetPet();
16336 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16338 //returning of reagents only for players, so best done here
16339 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16340 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16342 if(spellInfo)
16344 for(uint32 i = 0; i < 7; ++i)
16346 if(spellInfo->Reagent[i] > 0)
16348 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16349 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16350 if( msg == EQUIP_ERR_OK )
16352 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16353 if(IsInWorld())
16354 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16359 m_temporaryUnsummonedPetNumber = 0;
16362 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16363 return;
16365 // only if current pet in slot
16366 switch(pet->getPetType())
16368 case MINI_PET:
16369 m_miniPet = 0;
16370 break;
16371 case GUARDIAN_PET:
16372 RemoveGuardian(pet);
16373 break;
16374 default:
16375 if(GetPetGUID() == pet->GetGUID())
16376 SetPet(NULL);
16377 break;
16380 pet->CombatStop();
16382 if(returnreagent)
16384 switch(pet->GetEntry())
16386 //warlock pets except imp are removed(?) when logging out
16387 case 1860:
16388 case 1863:
16389 case 417:
16390 case 17252:
16391 mode = PET_SAVE_NOT_IN_SLOT;
16392 break;
16396 pet->SavePetToDB(mode);
16398 pet->AddObjectToRemoveList();
16399 pet->m_removed = true;
16401 if(pet->isControlled())
16403 RemovePetActionBar();
16405 if(GetGroup())
16406 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16410 void Player::RemoveMiniPet()
16412 if(Pet* pet = GetMiniPet())
16414 pet->Remove(PET_SAVE_AS_DELETED);
16415 m_miniPet = 0;
16419 Pet* Player::GetMiniPet()
16421 if(!m_miniPet)
16422 return NULL;
16423 return GetMap()->GetPet(m_miniPet);
16426 void Player::Uncharm()
16428 Unit* charm = GetCharm();
16429 if(!charm)
16430 return;
16432 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16433 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16436 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16438 *data << (uint8)msgtype;
16439 *data << (uint32)language;
16440 *data << (uint64)GetGUID();
16441 *data << (uint32)language; //language 2.1.0 ?
16442 *data << (uint64)GetGUID();
16443 *data << (uint32)(text.length()+1);
16444 *data << text;
16445 *data << (uint8)chatTag();
16448 void Player::Say(const std::string& text, const uint32 language)
16450 WorldPacket data(SMSG_MESSAGECHAT, 200);
16451 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16452 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16455 void Player::Yell(const std::string& text, const uint32 language)
16457 WorldPacket data(SMSG_MESSAGECHAT, 200);
16458 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16459 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16462 void Player::TextEmote(const std::string& text)
16464 WorldPacket data(SMSG_MESSAGECHAT, 200);
16465 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16466 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16469 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16471 if (language != LANG_ADDON) // if not addon data
16472 language = LANG_UNIVERSAL; // whispers should always be readable
16474 Player *rPlayer = objmgr.GetPlayer(receiver);
16476 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16477 if(!rPlayer->isDND() || isGameMaster())
16479 WorldPacket data(SMSG_MESSAGECHAT, 200);
16480 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16481 rPlayer->GetSession()->SendPacket(&data);
16483 // not send confirmation for addon messages
16484 if (language != LANG_ADDON)
16486 data.Initialize(SMSG_MESSAGECHAT, 200);
16487 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16488 GetSession()->SendPacket(&data);
16491 else
16493 // announce to player that player he is whispering to is dnd and cannot receive his message
16494 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16497 if(!isAcceptWhispers())
16499 SetAcceptWhispers(true);
16500 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16503 // announce to player that player he is whispering to is afk
16504 if(rPlayer->isAFK())
16505 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16507 // if player whisper someone, auto turn of dnd to be able to receive an answer
16508 if(isDND() && !rPlayer->isGameMaster())
16509 ToggleDND();
16512 void Player::PetSpellInitialize()
16514 Pet* pet = GetPet();
16516 if(!pet)
16517 return;
16519 sLog.outDebug("Pet Spells Groups");
16521 CharmInfo *charmInfo = pet->GetCharmInfo();
16523 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16524 data << uint64(pet->GetGUID());
16525 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16526 data << uint32(0);
16527 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16529 // action bar loop
16530 charmInfo->BuildActionBar(&data);
16532 size_t spellsCountPos = data.wpos();
16534 // spells count
16535 uint8 addlist = 0;
16536 data << uint8(addlist); // placeholder
16538 if (pet->IsPermanentPetFor(this))
16540 // spells loop
16541 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16543 if(itr->second.state == PETSPELL_REMOVED)
16544 continue;
16546 data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
16547 ++addlist;
16551 data.put<uint8>(spellsCountPos, addlist);
16553 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16554 data << uint8(cooldownsCount);
16556 time_t curTime = time(NULL);
16558 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16560 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16562 data << uint32(itr->first); // spellid
16563 data << uint16(0); // spell category?
16564 data << uint32(cooldown); // cooldown
16565 data << uint32(0); // category cooldown
16568 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16570 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16572 data << uint32(itr->first); // spellid
16573 data << uint16(0); // spell category?
16574 data << uint32(0); // cooldown
16575 data << uint32(cooldown); // category cooldown
16578 GetSession()->SendPacket(&data);
16581 void Player::PossessSpellInitialize()
16583 Unit* charm = GetCharm();
16585 if(!charm)
16586 return;
16588 CharmInfo *charmInfo = charm->GetCharmInfo();
16590 if(!charmInfo)
16592 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16593 return;
16596 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16597 data << uint64(charm->GetGUID());
16598 data << uint16(0);
16599 data << uint32(0);
16600 data << uint32(0);
16602 charmInfo->BuildActionBar(&data);
16604 data << uint8(0); // spells count
16605 data << uint8(0); // cooldowns count
16607 GetSession()->SendPacket(&data);
16610 void Player::CharmSpellInitialize()
16612 Unit* charm = GetCharm();
16614 if(!charm)
16615 return;
16617 CharmInfo *charmInfo = charm->GetCharmInfo();
16618 if(!charmInfo)
16620 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16621 return;
16624 uint8 addlist = 0;
16626 if(charm->GetTypeId() != TYPEID_PLAYER)
16628 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16630 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16632 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16634 if(charmInfo->GetCharmSpell(i)->GetAction())
16635 ++addlist;
16640 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
16641 data << uint64(charm->GetGUID());
16642 data << uint16(0);
16643 data << uint32(0);
16645 if(charm->GetTypeId() != TYPEID_PLAYER)
16646 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16647 else
16648 data << uint8(0) << uint8(0) << uint16(0);
16650 charmInfo->BuildActionBar(&data);
16652 data << uint8(addlist);
16654 if(addlist)
16656 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16658 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16659 if(cspell->GetAction())
16660 data << uint32(cspell->packedData);
16664 data << uint8(0); // cooldowns count
16666 GetSession()->SendPacket(&data);
16669 void Player::RemovePetActionBar()
16671 WorldPacket data(SMSG_PET_SPELLS, 8);
16672 data << uint64(0);
16673 SendDirectMessage(&data);
16676 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16678 if (!mod || !spellInfo)
16679 return false;
16681 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16683 // prevent apply to any spell except spell that trigger expire
16684 if(spell)
16686 if(mod->lastAffected != spell)
16687 return false;
16689 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16690 return false;
16693 return spellmgr.IsAffectedByMod(spellInfo, mod);
16696 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16698 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16700 for(int eff=0;eff<96;++eff)
16702 uint64 _mask = 0;
16703 uint64 _mask2= 0;
16704 if (eff<64) _mask = uint64(1) << (eff- 0);
16705 else _mask2= uint64(1) << (eff-64);
16706 if ( mod->mask & _mask || mod->mask2 & _mask2)
16708 int32 val = 0;
16709 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16711 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16712 val += (*itr)->value;
16714 val += apply ? mod->value : -(mod->value);
16715 WorldPacket data(Opcode, (1+1+4));
16716 data << uint8(eff);
16717 data << uint8(mod->op);
16718 data << int32(val);
16719 SendDirectMessage(&data);
16723 if (apply)
16724 m_spellMods[mod->op].push_back(mod);
16725 else
16727 if (mod->charges == -1)
16728 --m_SpellModRemoveCount;
16729 m_spellMods[mod->op].remove(mod);
16730 delete mod;
16734 void Player::RemoveSpellMods(Spell const* spell)
16736 if(!spell || (m_SpellModRemoveCount == 0))
16737 return;
16739 for(int i=0;i<MAX_SPELLMOD;++i)
16741 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16743 SpellModifier *mod = *itr;
16744 ++itr;
16746 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16748 RemoveAurasDueToSpell(mod->spellId);
16749 if (m_spellMods[i].empty())
16750 break;
16751 else
16752 itr = m_spellMods[i].begin();
16758 // send Proficiency
16759 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16761 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16762 data << pr1 << pr2;
16763 GetSession()->SendPacket (&data);
16766 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16768 QueryResult *result = NULL;
16769 if(type==10)
16770 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16771 else
16772 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16773 if(result)
16775 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.
16776 { // and SendPetitionQueryOpcode reads data from the DB
16777 Field *fields = result->Fetch();
16778 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16779 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16781 // send update if charter owner in game
16782 Player* owner = objmgr.GetPlayer(ownerguid);
16783 if(owner)
16784 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16786 } while ( result->NextRow() );
16788 delete result;
16790 if(type==10)
16791 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16792 else
16793 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16796 CharacterDatabase.BeginTransaction();
16797 if(type == 10)
16799 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16800 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16802 else
16804 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16805 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16807 CharacterDatabase.CommitTransaction();
16810 void Player::LeaveAllArenaTeams(uint64 guid)
16812 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));
16813 if(!result)
16814 return;
16818 Field *fields = result->Fetch();
16819 uint32 at_id = fields[0].GetUInt32();
16820 if(at_id != 0)
16822 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16823 if(at)
16824 at->DelMember(guid);
16826 } while (result->NextRow());
16828 delete result;
16831 void Player::SetRestBonus (float rest_bonus_new)
16833 // Prevent resting on max level
16834 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16835 rest_bonus_new = 0;
16837 if(rest_bonus_new < 0)
16838 rest_bonus_new = 0;
16840 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16842 if(rest_bonus_new > rest_bonus_max)
16843 m_rest_bonus = rest_bonus_max;
16844 else
16845 m_rest_bonus = rest_bonus_new;
16847 // update data for client
16848 if(m_rest_bonus>10)
16849 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16850 else if(m_rest_bonus<=1)
16851 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16853 //RestTickUpdate
16854 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16857 void Player::HandleStealthedUnitsDetection()
16859 std::list<Unit*> stealthedUnits;
16861 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16862 Cell cell(p);
16863 cell.data.Part.reserved = ALL_DISTRICT;
16864 cell.SetNoCreate();
16866 MaNGOS::AnyStealthedCheck u_check;
16867 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16869 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16870 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16872 CellLock<GridReadGuard> cell_lock(cell, p);
16873 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
16874 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
16876 WorldObject const* viewPoint = GetViewPoint();
16878 for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
16880 if((*i)==this)
16881 continue;
16883 bool hasAtClient = HaveAtClient((*i));
16884 bool hasDetected = (*i)->isVisibleForOrDetect(this, viewPoint, true);
16886 if (hasDetected)
16888 if(!hasAtClient)
16890 (*i)->SendCreateUpdateToPlayer(this);
16891 m_clientGUIDs.insert((*i)->GetGUID());
16893 #ifdef MANGOS_DEBUG
16894 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16895 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16896 #endif
16898 // target aura duration for caster show only if target exist at caster client
16899 // send data at target visibility change (adding to client)
16900 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16901 SendAurasForTarget(*i);
16904 else
16906 if(hasAtClient)
16908 (*i)->DestroyForPlayer(this);
16909 m_clientGUIDs.erase((*i)->GetGUID());
16915 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
16917 if(nodes.size() < 2)
16918 return false;
16920 // 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
16921 if(GetSession()->isLogingOut() || isInCombat())
16923 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16924 data << uint32(ERR_TAXIPLAYERBUSY);
16925 GetSession()->SendPacket(&data);
16926 return false;
16929 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16930 return false;
16932 // taximaster case
16933 if(npc)
16935 // not let cheating with start flight mounted
16936 if(IsMounted())
16938 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16939 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16940 GetSession()->SendPacket(&data);
16941 return false;
16944 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16946 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16947 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16948 GetSession()->SendPacket(&data);
16949 return false;
16952 // 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
16953 if(IsNonMeleeSpellCasted(false))
16955 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16956 data << uint32(ERR_TAXIPLAYERBUSY);
16957 GetSession()->SendPacket(&data);
16958 return false;
16961 // cast case or scripted call case
16962 else
16964 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
16966 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16967 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
16969 if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
16970 if (spell->m_spellInfo->Id != spellid)
16971 InterruptSpell(CURRENT_GENERIC_SPELL,false);
16973 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
16975 if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
16976 if (spell->m_spellInfo->Id != spellid)
16977 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
16980 uint32 sourcenode = nodes[0];
16982 // starting node too far away (cheat?)
16983 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16984 if (!node)
16986 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16987 data << uint32(ERR_TAXINOSUCHPATH);
16988 GetSession()->SendPacket(&data);
16989 return false;
16992 // check node starting pos data set case if provided
16993 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
16995 if (node->map_id != GetMapId() ||
16996 (node->x - GetPositionX())*(node->x - GetPositionX())+
16997 (node->y - GetPositionY())*(node->y - GetPositionY())+
16998 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16999 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
17001 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17002 data << uint32(ERR_TAXITOOFARAWAY);
17003 GetSession()->SendPacket(&data);
17004 return false;
17007 // node must have pos if taxi master case (npc != NULL)
17008 else if (npc)
17010 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17011 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17012 GetSession()->SendPacket(&data);
17013 return false;
17016 // Prepare to flight start now
17018 // stop combat at start taxi flight if any
17019 CombatStop();
17021 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17022 TradeCancel(true);
17024 // clean not finished taxi path if any
17025 m_taxi.ClearTaxiDestinations();
17027 // 0 element current node
17028 m_taxi.AddTaxiDestination(sourcenode);
17030 // fill destinations path tail
17031 uint32 sourcepath = 0;
17032 uint32 totalcost = 0;
17034 uint32 prevnode = sourcenode;
17035 uint32 lastnode = 0;
17037 for(uint32 i = 1; i < nodes.size(); ++i)
17039 uint32 path, cost;
17041 lastnode = nodes[i];
17042 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
17044 if(!path)
17046 m_taxi.ClearTaxiDestinations();
17047 return false;
17050 totalcost += cost;
17052 if(prevnode == sourcenode)
17053 sourcepath = path;
17055 m_taxi.AddTaxiDestination(lastnode);
17057 prevnode = lastnode;
17060 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
17061 uint32 mount_display_id = objmgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
17063 // in spell case allow 0 model
17064 if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
17066 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17067 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17068 GetSession()->SendPacket(&data);
17069 m_taxi.ClearTaxiDestinations();
17070 return false;
17073 uint32 money = GetMoney();
17075 if (npc)
17076 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17078 if(money < totalcost)
17080 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17081 data << uint32(ERR_TAXINOTENOUGHMONEY);
17082 GetSession()->SendPacket(&data);
17083 m_taxi.ClearTaxiDestinations();
17084 return false;
17087 //Checks and preparations done, DO FLIGHT
17088 ModifyMoney(-(int32)totalcost);
17089 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
17090 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
17092 // prevent stealth flight
17093 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17095 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17096 data << uint32(ERR_TAXIOK);
17097 GetSession()->SendPacket(&data);
17099 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17101 GetSession()->SendDoFlight(mount_display_id, sourcepath);
17103 return true;
17106 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
17108 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
17109 if(!entry)
17110 return false;
17112 std::vector<uint32> nodes;
17114 nodes.resize(2);
17115 nodes[0] = entry->from;
17116 nodes[1] = entry->to;
17118 return ActivateTaxiPathTo(nodes,NULL,spellid);
17121 void Player::ContinueTaxiFlight()
17123 uint32 sourceNode = m_taxi.GetTaxiSource();
17124 if (!sourceNode)
17125 return;
17127 sLog.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
17129 uint32 mountDisplayId = objmgr.GetTaxiMountDisplayId(sourceNode, GetTeam(),true);
17130 uint32 path = m_taxi.GetCurrentTaxiPath();
17132 // search appropriate start path node
17133 uint32 startNode = 0;
17135 TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
17137 float distPrev = MAP_SIZE*MAP_SIZE;
17138 float distNext =
17139 (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
17140 (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
17141 (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
17143 for(uint32 i = 1; i < nodeList.size(); ++i)
17145 TaxiPathNode const& node = nodeList[i];
17146 TaxiPathNode const& prevNode = nodeList[i-1];
17148 // skip nodes at another map
17149 if(node.mapid != GetMapId())
17150 continue;
17152 distPrev = distNext;
17154 distNext =
17155 (node.x-GetPositionX())*(node.x-GetPositionX())+
17156 (node.y-GetPositionY())*(node.y-GetPositionY())+
17157 (node.z-GetPositionZ())*(node.z-GetPositionZ());
17159 float distNodes =
17160 (node.x-prevNode.x)*(node.x-prevNode.x)+
17161 (node.y-prevNode.y)*(node.y-prevNode.y)+
17162 (node.z-prevNode.z)*(node.z-prevNode.z);
17164 if(distNext + distPrev < distNodes)
17166 startNode = i;
17167 break;
17171 GetSession()->SendDoFlight(mountDisplayId, path, startNode);
17174 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17176 // last check 2.0.10
17177 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17178 data << GetGUID();
17179 data << uint8(0x0); // flags (0x1, 0x2)
17180 time_t curTime = time(NULL);
17181 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17183 if (itr->second->state == PLAYERSPELL_REMOVED)
17184 continue;
17185 uint32 unSpellId = itr->first;
17186 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17187 if (!spellInfo)
17189 ASSERT(spellInfo);
17190 continue;
17193 // Not send cooldown for this spells
17194 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17195 continue;
17197 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17199 data << uint32(unSpellId);
17200 data << uint32(unTimeMs); // in m.secs
17201 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17204 GetSession()->SendPacket(&data);
17207 void Player::InitDataForForm(bool reapplyMods)
17209 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17210 if(ssEntry && ssEntry->attackSpeed)
17212 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17213 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17214 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17216 else
17217 SetRegularAttackTime();
17219 switch(m_form)
17221 case FORM_CAT:
17223 if(getPowerType()!=POWER_ENERGY)
17224 setPowerType(POWER_ENERGY);
17225 break;
17227 case FORM_BEAR:
17228 case FORM_DIREBEAR:
17230 if(getPowerType()!=POWER_RAGE)
17231 setPowerType(POWER_RAGE);
17232 break;
17234 default: // 0, for example
17236 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17237 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17238 setPowerType(Powers(cEntry->powerType));
17239 break;
17243 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17244 if (!reapplyMods)
17245 UpdateEquipSpellsAtFormChange();
17247 UpdateAttackPowerAndDamage();
17248 UpdateAttackPowerAndDamage(true);
17251 void Player::InitDisplayIds()
17253 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
17254 if(!info)
17256 sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
17257 return;
17260 uint8 gender = getGender();
17261 switch(gender)
17263 case GENDER_FEMALE:
17264 SetDisplayId(info->displayId_f );
17265 SetNativeDisplayId(info->displayId_f );
17266 break;
17267 case GENDER_MALE:
17268 SetDisplayId(info->displayId_m );
17269 SetNativeDisplayId(info->displayId_m );
17270 break;
17271 default:
17272 sLog.outError("Invalid gender %u for player",gender);
17273 return;
17277 // Return true is the bought item has a max count to force refresh of window by caller
17278 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot)
17280 // cheating attempt
17281 if (count < 1) count = 1;
17283 if (!isAlive())
17284 return false;
17286 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
17287 if (!pProto)
17289 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17290 return false;
17293 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
17294 if (!pCreature)
17296 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17297 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17298 return false;
17301 VendorItemData const* vItems = pCreature->GetVendorItems();
17302 if(!vItems || vItems->Empty())
17304 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17305 return false;
17308 size_t vendor_slot = vItems->FindItemSlot(item);
17309 if (vendor_slot >= vItems->GetItemCount())
17311 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17312 return false;
17315 VendorItem const* crItem = vItems->m_items[vendor_slot];
17317 // check current item amount if it limited
17318 if (crItem->maxcount != 0)
17320 if (pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17322 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17323 return false;
17327 if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17329 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17330 return false;
17333 if (crItem->ExtendedCost)
17335 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17336 if (!iece)
17338 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17339 return false;
17342 // honor points price
17343 if (GetHonorPoints() < (iece->reqhonorpoints * count))
17345 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17346 return false;
17349 // arena points price
17350 if (GetArenaPoints() < (iece->reqarenapoints * count))
17352 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17353 return false;
17356 // item base price
17357 for (uint8 i = 0; i < 5; ++i)
17359 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17361 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17362 return false;
17366 // check for personal arena rating requirement
17367 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17369 // probably not the proper equip err
17370 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17371 return false;
17375 uint32 price = pProto->BuyPrice * count;
17377 // reputation discount
17378 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17380 if (GetMoney() < price)
17382 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17383 return false;
17386 if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
17388 ItemPosCountVec dest;
17389 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17390 if (msg != EQUIP_ERR_OK)
17392 SendEquipError( msg, NULL, NULL );
17393 return false;
17396 ModifyMoney( -(int32)price );
17397 if (crItem->ExtendedCost) // case for new honor system
17399 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17400 if (iece->reqhonorpoints)
17401 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17402 if (iece->reqarenapoints)
17403 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17404 for (uint8 i = 0; i < 5; ++i)
17406 if (iece->reqitem[i])
17407 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17411 if (Item *it = StoreNewItem( dest, item, true ))
17413 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17415 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17416 data << uint64(pCreature->GetGUID());
17417 data << uint32(vendor_slot+1); // numbered from 1 at client
17418 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17419 data << uint32(count);
17420 GetSession()->SendPacket(&data);
17422 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17425 else if (IsEquipmentPos(bag, slot))
17427 if (pProto->BuyCount * count != 1)
17429 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17430 return false;
17433 uint16 dest;
17434 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17435 if (msg != EQUIP_ERR_OK)
17437 SendEquipError( msg, NULL, NULL );
17438 return false;
17441 ModifyMoney( -(int32)price );
17442 if (crItem->ExtendedCost) // case for new honor system
17444 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17445 if (iece->reqhonorpoints)
17446 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17447 if (iece->reqarenapoints)
17448 ModifyArenaPoints( - int32(iece->reqarenapoints));
17449 for (uint8 i = 0; i < 5; ++i)
17451 if(iece->reqitem[i])
17452 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17456 if (Item *it = EquipNewItem( dest, item, true ))
17458 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17460 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17461 data << uint64(pCreature->GetGUID());
17462 data << uint32(vendor_slot + 1); // numbered from 1 at client
17463 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17464 data << uint32(count);
17465 GetSession()->SendPacket(&data);
17467 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17469 AutoUnequipOffhandIfNeed();
17472 else
17474 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17475 return false;
17478 return crItem->maxcount != 0;
17481 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17483 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17484 // the personal rating of the arena team must match the required limit as well
17485 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17486 uint32 max_personal_rating = 0;
17487 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17489 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17491 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING);
17492 uint32 t_rating = at->GetRating();
17493 p_rating = p_rating < t_rating ? p_rating : t_rating;
17494 if(max_personal_rating < p_rating)
17495 max_personal_rating = p_rating;
17498 return max_personal_rating;
17501 void Player::UpdateHomebindTime(uint32 time)
17503 // GMs never get homebind timer online
17504 if (m_InstanceValid || isGameMaster())
17506 if(m_HomebindTimer) // instance valid, but timer not reset
17508 // hide reminder
17509 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17510 data << uint32(0);
17511 data << uint32(0);
17512 GetSession()->SendPacket(&data);
17514 // instance is valid, reset homebind timer
17515 m_HomebindTimer = 0;
17517 else if (m_HomebindTimer > 0)
17519 if (time >= m_HomebindTimer)
17521 // teleport to nearest graveyard
17522 RepopAtGraveyard();
17524 else
17525 m_HomebindTimer -= time;
17527 else
17529 // instance is invalid, start homebind timer
17530 m_HomebindTimer = 60000;
17531 // send message to player
17532 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17533 data << uint32(m_HomebindTimer);
17534 data << uint32(1);
17535 GetSession()->SendPacket(&data);
17536 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17540 void Player::UpdatePvP(bool state, bool ovrride)
17542 if(!state || ovrride)
17544 SetPvP(state);
17545 pvpInfo.endTimer = 0;
17547 else
17549 if(pvpInfo.endTimer != 0)
17550 pvpInfo.endTimer = time(NULL);
17551 else
17552 SetPvP(state);
17556 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17558 // init cooldown values
17559 uint32 cat = 0;
17560 int32 rec = -1;
17561 int32 catrec = -1;
17563 // some special item spells without correct cooldown in SpellInfo
17564 // cooldown information stored in item prototype
17565 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17567 if(itemId)
17569 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17571 for(int idx = 0; idx < 5; ++idx)
17573 if(proto->Spells[idx].SpellId == spellInfo->Id)
17575 cat = proto->Spells[idx].SpellCategory;
17576 rec = proto->Spells[idx].SpellCooldown;
17577 catrec = proto->Spells[idx].SpellCategoryCooldown;
17578 break;
17584 // if no cooldown found above then base at DBC data
17585 if(rec < 0 && catrec < 0)
17587 cat = spellInfo->Category;
17588 rec = spellInfo->RecoveryTime;
17589 catrec = spellInfo->CategoryRecoveryTime;
17592 time_t curTime = time(NULL);
17594 time_t catrecTime;
17595 time_t recTime;
17597 // overwrite time for selected category
17598 if(infinityCooldown)
17600 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17601 // but not allow ignore until reset or re-login
17602 catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
17603 recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
17605 else
17607 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17608 // prevent 0 cooldowns set by another way
17609 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17610 rec = GetAttackTime(RANGED_ATTACK);
17612 // Now we have cooldown data (if found any), time to apply mods
17613 if(rec > 0)
17614 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17616 if(catrec > 0)
17617 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17619 // replace negative cooldowns by 0
17620 if (rec < 0) rec = 0;
17621 if (catrec < 0) catrec = 0;
17623 // no cooldown after applying spell mods
17624 if( rec == 0 && catrec == 0)
17625 return;
17627 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17628 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17631 // self spell cooldown
17632 if(recTime > 0)
17633 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17635 // category spells
17636 if (cat && catrec > 0)
17638 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17639 if(i_scstore != sSpellCategoryStore.end())
17641 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17643 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17644 continue;
17646 AddSpellCooldown(*i_scset, itemId, catrecTime);
17652 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17654 SpellCooldown sc;
17655 sc.end = end_time;
17656 sc.itemid = itemid;
17657 m_spellCooldowns[spellid] = sc;
17660 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17662 // start cooldowns at server side, if any
17663 AddSpellAndCategoryCooldowns(spellInfo, itemId, spell);
17665 // Send activate cooldown timer (possible 0) at client side
17666 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17667 data << uint32(spellInfo->Id);
17668 data << uint64(GetGUID());
17669 SendDirectMessage(&data);
17672 void Player::UpdatePotionCooldown(Spell* spell)
17674 // no potion used i combat or still in combat
17675 if(!m_lastPotionId || isInCombat())
17676 return;
17678 // Call not from spell cast, send cooldown event for item spells if no in combat
17679 if(!spell)
17681 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17682 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17683 for(int idx = 0; idx < 5; ++idx)
17684 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17685 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17686 SendCooldownEvent(spellInfo,m_lastPotionId);
17688 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17689 else
17690 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17692 m_lastPotionId = 0;
17695 //slot to be excluded while counting
17696 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17698 if(!enchantmentcondition)
17699 return true;
17701 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17703 if(!Condition)
17704 return true;
17706 uint8 curcount[4] = {0, 0, 0, 0};
17708 //counting current equipped gem colors
17709 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17711 if(i == slot)
17712 continue;
17713 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17714 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17716 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17718 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17719 if(!enchant_id)
17720 continue;
17722 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17723 if(!enchantEntry)
17724 continue;
17726 uint32 gemid = enchantEntry->GemID;
17727 if(!gemid)
17728 continue;
17730 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17731 if(!gemProto)
17732 continue;
17734 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17735 if(!gemProperty)
17736 continue;
17738 uint8 GemColor = gemProperty->color;
17740 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17742 if(tmpcolormask & GemColor)
17743 ++curcount[b];
17749 bool activate = true;
17751 for(int i = 0; i < 5; ++i)
17753 if(!Condition->Color[i])
17754 continue;
17756 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17758 // if have <CompareColor> use them as count, else use <value> from Condition
17759 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17761 switch(Condition->Comparator[i])
17763 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17764 activate &= (_cur_gem < _cmp_gem) ? true : false;
17765 break;
17766 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17767 activate &= (_cur_gem > _cmp_gem) ? true : false;
17768 break;
17769 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17770 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17771 break;
17775 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");
17777 return activate;
17780 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17782 //cycle all equipped items
17783 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17785 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17786 if(slot == exceptslot)
17787 continue;
17789 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17791 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17792 continue;
17794 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17796 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17797 if(!enchant_id)
17798 continue;
17800 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17801 if(!enchantEntry)
17802 continue;
17804 uint32 condition = enchantEntry->EnchantmentCondition;
17805 if(condition)
17807 //was enchant active with/without item?
17808 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17809 //should it now be?
17810 if(wasactive != EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17812 // ignore item gem conditions
17813 //if state changed, (dis)apply enchant
17814 ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true);
17821 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17822 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17824 //cycle all equipped items
17825 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17827 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17828 if(slot == exceptslot)
17829 continue;
17831 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17833 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17834 continue;
17836 //cycle all (gem)enchants
17837 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17839 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17840 if(!enchant_id) //if no enchant go to next enchant(slot)
17841 continue;
17843 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17844 if(!enchantEntry)
17845 continue;
17847 //only metagems to be (de)activated, so only enchants with condition
17848 uint32 condition = enchantEntry->EnchantmentCondition;
17849 if(condition)
17850 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17855 void Player::SetBattleGroundEntryPoint()
17857 // Taxi path store
17858 if (!m_taxi.empty())
17860 m_bgData.mountSpell = 0;
17861 m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
17862 m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
17864 // On taxi we don't need check for dungeon
17865 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
17866 return;
17868 else
17870 m_bgData.ClearTaxiPath();
17872 // Mount spell id storing
17873 if (IsMounted())
17875 AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED);
17876 if (!auras.empty())
17877 m_bgData.mountSpell = (*auras.begin())->GetId();
17879 else
17880 m_bgData.mountSpell = 0;
17882 // If map is dungeon find linked graveyard
17883 if(GetMap()->IsDungeon())
17885 if (const WorldSafeLocsEntry* entry = objmgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
17887 m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
17888 return;
17890 else
17891 sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
17893 // If new entry point is not BG or arena set it
17894 else if (!GetMap()->IsBattleGroundOrArena())
17896 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
17897 return;
17901 // In error cases use homebind position
17902 m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
17905 void Player::LeaveBattleground(bool teleportToEntryPoint)
17907 if(BattleGround *bg = GetBattleGround())
17909 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17911 // call after remove to be sure that player resurrected for correct cast
17912 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17914 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17916 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
17917 if(IsBeingTeleportedFar())
17919 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
17920 return;
17923 CastSpell(this, 26013, true); // Deserter
17929 bool Player::CanJoinToBattleground() const
17931 // check Deserter debuff
17932 if(GetDummyAura(26013))
17933 return false;
17935 return true;
17938 bool Player::CanReportAfkDueToLimit()
17940 // a player can complain about 15 people per 5 minutes
17941 if(m_bgData.bgAfkReportedCount++ >= 15)
17942 return false;
17944 return true;
17947 ///This player has been blamed to be inactive in a battleground
17948 void Player::ReportedAfkBy(Player* reporter)
17950 BattleGround *bg = GetBattleGround();
17951 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17952 return;
17954 // check if player has 'Idle' or 'Inactive' debuff
17955 if(m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680, 0) && !HasAura(43681, 0) && reporter->CanReportAfkDueToLimit())
17957 m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
17958 // 3 players have to complain to apply debuff
17959 if(m_bgData.bgAfkReporter.size() >= 3)
17961 // cast 'Idle' spell
17962 CastSpell(this, 43680, true);
17963 m_bgData.bgAfkReporter.clear();
17968 WorldObject const* Player::GetViewPoint() const
17970 if(uint64 far_sight = GetFarSight())
17972 WorldObject const* viewPoint = GetMap()->GetWorldObject(far_sight);
17973 return viewPoint ? viewPoint : this; // always expected not NULL
17975 else
17976 return this;
17979 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17981 // gamemaster in GM mode see all, including ghosts
17982 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17983 return true;
17985 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17986 if (InBattleGround())
17988 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17989 return false;
17990 return true;
17993 // Live player see live player or dead player with not realized corpse
17994 if(pl->isAlive() || pl->m_deathTimer > 0)
17996 return isAlive() || m_deathTimer > 0;
17999 // Ghost see other friendly ghosts, that's for sure
18000 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
18001 return true;
18003 // Dead player see live players near own corpse
18004 if(isAlive())
18006 Corpse *corpse = pl->GetCorpse();
18007 if(corpse)
18009 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
18010 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
18011 return true;
18015 // and not see any other
18016 return false;
18019 bool Player::IsVisibleGloballyFor( Player* u ) const
18021 if(!u)
18022 return false;
18024 // Always can see self
18025 if (u==this)
18026 return true;
18028 // Visible units, always are visible for all players
18029 if (GetVisibility() == VISIBILITY_ON)
18030 return true;
18032 // GMs are visible for higher gms (or players are visible for gms)
18033 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
18034 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
18036 // non faction visibility non-breakable for non-GMs
18037 if (GetVisibility() == VISIBILITY_OFF)
18038 return false;
18040 // non-gm stealth/invisibility not hide from global player lists
18041 return true;
18044 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target)
18046 if(HaveAtClient(target))
18048 if(!target->isVisibleForInState(this, viewPoint, true))
18050 target->DestroyForPlayer(this);
18051 m_clientGUIDs.erase(target->GetGUID());
18053 #ifdef MANGOS_DEBUG
18054 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18055 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18056 #endif
18059 else
18061 if(target->isVisibleForInState(this, viewPoint, false))
18063 target->SendCreateUpdateToPlayer(this);
18064 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
18065 m_clientGUIDs.insert(target->GetGUID());
18067 #ifdef MANGOS_DEBUG
18068 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18069 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18070 #endif
18072 // target aura duration for caster show only if target exist at caster client
18073 // send data at target visibility change (adding to client)
18074 if(target!=this && target->isType(TYPEMASK_UNIT))
18075 SendAurasForTarget((Unit*)target);
18077 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
18078 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18083 template<class T>
18084 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
18086 s64.insert(target->GetGUID());
18089 template<>
18090 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
18092 if(!target->IsTransport())
18093 s64.insert(target->GetGUID());
18096 template<class T>
18097 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
18099 if(HaveAtClient(target))
18101 if(!target->isVisibleForInState(this,viewPoint,true))
18103 target->BuildOutOfRangeUpdateBlock(&data);
18104 m_clientGUIDs.erase(target->GetGUID());
18106 #ifdef MANGOS_DEBUG
18107 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18108 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));
18109 #endif
18112 else
18114 if(target->isVisibleForInState(this,viewPoint,false))
18116 visibleNow.insert(target);
18117 target->BuildCreateUpdateBlockForPlayer(&data, this);
18118 UpdateVisibilityOf_helper(m_clientGUIDs,target);
18120 #ifdef MANGOS_DEBUG
18121 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18122 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));
18123 #endif
18128 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18129 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18130 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18131 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18132 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18134 void Player::InitPrimaryProfessions()
18136 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
18139 void Player::SendComboPoints()
18141 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
18142 if (combotarget)
18144 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
18145 data.append(combotarget->GetPackGUID());
18146 data << uint8(m_comboPoints);
18147 GetSession()->SendPacket(&data);
18151 void Player::AddComboPoints(Unit* target, int8 count)
18153 if(!count)
18154 return;
18156 // without combo points lost (duration checked in aura)
18157 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18159 if(target->GetGUID() == m_comboTarget)
18161 m_comboPoints += count;
18163 else
18165 if(m_comboTarget)
18166 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
18167 target2->RemoveComboPointHolder(GetGUIDLow());
18169 m_comboTarget = target->GetGUID();
18170 m_comboPoints = count;
18172 target->AddComboPointHolder(GetGUIDLow());
18175 if (m_comboPoints > 5) m_comboPoints = 5;
18176 if (m_comboPoints < 0) m_comboPoints = 0;
18178 SendComboPoints();
18181 void Player::ClearComboPoints()
18183 if(!m_comboTarget)
18184 return;
18186 // without combopoints lost (duration checked in aura)
18187 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18189 m_comboPoints = 0;
18191 SendComboPoints();
18193 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18194 target->RemoveComboPointHolder(GetGUIDLow());
18196 m_comboTarget = 0;
18199 void Player::SetGroup(Group *group, int8 subgroup)
18201 if(group == NULL)
18202 m_group.unlink();
18203 else
18205 // never use SetGroup without a subgroup unless you specify NULL for group
18206 assert(subgroup >= 0);
18207 m_group.link(group, this);
18208 m_group.setSubGroup((uint8)subgroup);
18212 void Player::SendInitialPacketsBeforeAddToMap()
18214 GetSocial()->SendSocialList();
18216 // guild bank list wtf?
18218 // Homebind
18219 WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
18220 data << m_homebindX << m_homebindY << m_homebindZ;
18221 data << (uint32) m_homebindMapId;
18222 data << (uint32) m_homebindZoneId;
18223 GetSession()->SendPacket(&data);
18225 // SMSG_SET_PROFICIENCY
18226 // SMSG_SET_PCT_SPELL_MODIFIER
18227 // SMSG_SET_FLAT_SPELL_MODIFIER
18228 // SMSG_UPDATE_AURA_DURATION
18230 SendTalentsInfoData(false);
18232 // SMSG_INSTANCE_DIFFICULTY
18234 SendInitialSpells();
18236 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
18237 data << uint32(0); // count, for(count) uint32;
18238 GetSession()->SendPacket(&data);
18240 SendInitialActionButtons();
18241 m_reputationMgr.SendInitialReputations();
18242 // SMSG_INIT_WORLD_STATES
18243 m_achievementMgr.SendAllAchievementData();
18245 SendEquipmentSetList();
18247 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
18248 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18249 data << (float)0.01666667f; // game speed
18250 data << uint32(0); // added in 3.1.2
18251 GetSession()->SendPacket( &data );
18253 // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
18254 // SMSG_PET_GUIDS
18255 // SMSG_UPDATE_WORLD_STATE
18256 // SMSG_POWER_UPDATE
18258 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18259 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || HasAuraType(SPELL_AURA_FLY) || isInFlight())
18260 m_movementInfo.AddMovementFlag(MOVEMENTFLAG_FLYING2);
18262 m_mover = this;
18265 void Player::SendInitialPacketsAfterAddToMap()
18267 // update zone
18268 uint32 newzone, newarea;
18269 GetZoneAndAreaId(newzone,newarea);
18270 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
18272 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18273 data << uint32(0x00000000); // on blizz it increments periodically
18274 GetSession()->SendPacket(&data);
18276 CastSpell(this, 836, true); // LOGINEFFECT
18278 // set some aura effects that send packet to player client after add player to map
18279 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18280 // same auras state lost at far teleport, send it one more time in this case also
18281 static const AuraType auratypes[] =
18283 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18284 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18285 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18287 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18289 Unit::AuraList const& auraList = GetAurasByType(*itr);
18290 if(!auraList.empty())
18291 auraList.front()->ApplyModifier(true,true);
18294 if(HasAuraType(SPELL_AURA_MOD_STUN))
18295 SetMovement(MOVE_ROOT);
18297 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18298 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18300 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
18301 data2.append(GetPackGUID());
18302 data2 << (uint32)2;
18303 SendMessageToSet(&data2,true);
18306 SendAurasForTarget(this);
18307 SendEnchantmentDurations(); // must be after add to map
18308 SendItemDurations(); // must be after add to map
18311 void Player::SendUpdateToOutOfRangeGroupMembers()
18313 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18314 return;
18315 if(Group* group = GetGroup())
18316 group->UpdatePlayerOutOfRange(this);
18318 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18319 m_auraUpdateMask = 0;
18320 if(Pet *pet = GetPet())
18321 pet->ResetAuraUpdateMask();
18324 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18326 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18327 data << uint32(mapid);
18328 data << uint8(reason); // transfer abort reason
18329 switch(reason)
18331 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18332 case TRANSFER_ABORT_DIFFICULTY:
18333 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18334 data << uint8(arg);
18335 break;
18337 GetSession()->SendPacket(&data);
18340 void Player::SendInstanceResetWarning( uint32 mapid, Difficulty difficulty, uint32 time )
18342 // type of warning, based on the time remaining until reset
18343 uint32 type;
18344 if(time > 3600)
18345 type = RAID_INSTANCE_WELCOME;
18346 else if(time > 900 && time <= 3600)
18347 type = RAID_INSTANCE_WARNING_HOURS;
18348 else if(time > 300 && time <= 900)
18349 type = RAID_INSTANCE_WARNING_MIN;
18350 else
18351 type = RAID_INSTANCE_WARNING_MIN_SOON;
18353 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
18354 data << uint32(type);
18355 data << uint32(mapid);
18356 data << uint32(difficulty); // difficulty
18357 data << uint32(time);
18358 if(type == RAID_INSTANCE_WELCOME)
18360 data << uint8(0); // is your (1)
18361 data << uint8(0); // is extended (1), ignored if prev field is 0
18363 GetSession()->SendPacket(&data);
18366 void Player::ApplyEquipCooldown( Item * pItem )
18368 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
18370 _Spell const& spellData = pItem->GetProto()->Spells[i];
18372 // no spell
18373 if( !spellData.SpellId )
18374 continue;
18376 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18377 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18378 continue;
18380 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18382 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18383 data << pItem->GetGUID();
18384 data << uint32(spellData.SpellId);
18385 GetSession()->SendPacket(&data);
18389 void Player::resetSpells()
18391 // not need after this call
18392 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18393 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
18395 // make full copy of map (spells removed and marked as deleted at another spell remove
18396 // and we can't use original map for safe iterative with visit each spell at loop end
18397 PlayerSpellMap smap = GetSpellMap();
18399 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18400 removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
18402 learnDefaultSpells();
18403 learnQuestRewardedSpells();
18406 void Player::learnDefaultSpells()
18408 // learn default race/class spells
18409 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18410 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18412 uint32 tspell = *itr;
18413 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18414 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18415 addSpell(tspell,true,true,true,false);
18416 else // but send in normal spell in game learn case
18417 learnSpell(tspell,true);
18421 void Player::learnQuestRewardedSpells(Quest const* quest)
18423 uint32 spell_id = quest->GetRewSpellCast();
18425 // skip quests without rewarded spell
18426 if( !spell_id )
18427 return;
18429 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18430 if(!spellInfo)
18431 return;
18433 // check learned spells state
18434 bool found = false;
18435 for(int i=0; i < 3; ++i)
18437 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18439 found = true;
18440 break;
18444 // skip quests with not teaching spell or already known spell
18445 if(!found)
18446 return;
18448 // prevent learn non first rank unknown profession and second specialization for same profession)
18449 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18450 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18452 // not have first rank learned (unlearned prof?)
18453 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18454 if( !HasSpell(first_spell) )
18455 return;
18457 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18458 if(!learnedInfo)
18459 return;
18461 // specialization
18462 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18464 // search other specialization for same prof
18465 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18467 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18468 continue;
18470 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18471 if(!itrInfo)
18472 return;
18474 // compare only specializations
18475 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18476 continue;
18478 // compare same chain spells
18479 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18480 continue;
18482 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18483 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18484 return;
18489 CastSpell( this, spell_id, true);
18492 void Player::learnQuestRewardedSpells()
18494 // learn spells received from quest completing
18495 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18497 // skip no rewarded quests
18498 if(!itr->second.m_rewarded)
18499 continue;
18501 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18502 if( !quest )
18503 continue;
18505 learnQuestRewardedSpells(quest);
18509 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18511 uint32 raceMask = getRaceMask();
18512 uint32 classMask = getClassMask();
18513 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18515 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18516 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18517 continue;
18518 // Check race if set
18519 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18520 continue;
18521 // Check class if set
18522 if (pAbility->classmask && !(pAbility->classmask & classMask))
18523 continue;
18525 if (sSpellStore.LookupEntry(pAbility->spellId))
18527 // need unlearn spell
18528 if (skill_value < pAbility->req_skill_value)
18529 removeSpell(pAbility->spellId);
18530 // need learn
18531 else if (!IsInWorld())
18532 addSpell(pAbility->spellId,true,true,true,false);
18533 else
18534 learnSpell(pAbility->spellId,true);
18539 void Player::SendAurasForTarget(Unit *target)
18541 if(target->GetVisibleAuras()->empty()) // speedup things
18542 return;
18544 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18545 data.append(target->GetPackGUID());
18547 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18548 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18550 for(uint32 j = 0; j < 3; ++j)
18552 if(Aura *aura = target->GetAura(itr->second, j))
18554 data << uint8(aura->GetAuraSlot());
18555 data << uint32(aura->GetId());
18557 if(aura->GetId())
18559 uint8 auraFlags = aura->GetAuraFlags();
18560 // flags
18561 data << uint8(auraFlags);
18562 // level
18563 data << uint8(aura->GetAuraLevel());
18564 // charges
18565 if (aura->GetAuraCharges())
18566 data << uint8(aura->GetAuraCharges() * aura->GetStackAmount());
18567 else
18568 data << uint8(aura->GetStackAmount());
18570 if(!(auraFlags & AFLAG_NOT_CASTER))
18572 data << uint8(0); // packed GUID of someone (caster?)
18575 if(auraFlags & AFLAG_DURATION) // include aura duration
18577 data << uint32(aura->GetAuraMaxDuration());
18578 data << uint32(aura->GetAuraDuration());
18581 break;
18586 GetSession()->SendPacket(&data);
18589 void Player::SetDailyQuestStatus( uint32 quest_id )
18591 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18593 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18595 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18596 m_lastDailyQuestTime = time(NULL); // last daily quest time
18597 m_DailyQuestChanged = true;
18598 break;
18603 void Player::ResetDailyQuestStatus()
18605 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18606 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18608 // DB data deleted in caller
18609 m_DailyQuestChanged = false;
18610 m_lastDailyQuestTime = 0;
18613 BattleGround* Player::GetBattleGround() const
18615 if(GetBattleGroundId()==0)
18616 return NULL;
18618 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
18621 bool Player::InArena() const
18623 BattleGround *bg = GetBattleGround();
18624 if(!bg || !bg->isArena())
18625 return false;
18627 return true;
18630 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18632 // get a template bg instead of running one
18633 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18634 if(!bg)
18635 return false;
18637 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18638 return false;
18640 return true;
18643 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel() const
18645 // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 - 79, 80
18646 uint32 queue_id = ( getLevel() / 10) - 1;
18647 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18649 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18650 return QUEUE_ID_MAX_LEVEL_80;
18652 return BGQueueIdBasedOnLevel(queue_id);
18655 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18657 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18658 if(!vendor_faction || !vendor_faction->faction)
18659 return 1.0f;
18661 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18662 if(rank <= REP_NEUTRAL)
18663 return 1.0f;
18665 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18668 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18670 uint32 racemask = getRaceMask();
18671 uint32 classmask = getClassMask();
18673 SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
18674 if (bounds.first==bounds.second)
18675 return true;
18677 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
18679 // skip wrong race skills
18680 if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18681 continue;
18683 // skip wrong class skills
18684 if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18685 continue;
18687 return true;
18690 return false;
18693 bool Player::HasQuestForGO(int32 GOId) const
18695 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18697 uint32 questid = GetQuestSlotQuestId(i);
18698 if ( questid == 0 )
18699 continue;
18701 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18702 if(qs_itr == mQuestStatus.end())
18703 continue;
18705 QuestStatusData const& qs = qs_itr->second;
18707 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18709 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18710 if(!qinfo)
18711 continue;
18713 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18714 continue;
18716 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
18718 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18719 continue;
18721 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18722 return true;
18726 return false;
18729 void Player::UpdateForQuestWorldObjects()
18731 if(m_clientGUIDs.empty())
18732 return;
18734 UpdateData udata;
18735 WorldPacket packet;
18736 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18738 if(IS_GAMEOBJECT_GUID(*itr))
18740 GameObject *obj = GetMap()->GetGameObject(*itr);
18741 if(obj)
18742 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18744 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
18746 Creature *obj = GetMap()->GetCreatureOrPetOrVehicle(*itr);
18747 if(!obj)
18748 continue;
18750 // check if this unit requires quest specific flags
18751 if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
18752 continue;
18754 SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(obj->GetEntry());
18755 for(SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
18757 if(_itr->second.questStart || _itr->second.questEnd)
18759 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
18760 break;
18765 udata.BuildPacket(&packet);
18766 GetSession()->SendPacket(&packet);
18769 void Player::SummonIfPossible(bool agree)
18771 if(!agree)
18773 m_summon_expire = 0;
18774 return;
18777 // expire and auto declined
18778 if(m_summon_expire < time(NULL))
18779 return;
18781 // stop taxi flight at summon
18782 if(isInFlight())
18784 GetMotionMaster()->MovementExpired();
18785 m_taxi.ClearTaxiDestinations();
18788 // drop flag at summon
18789 // 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
18790 if(BattleGround *bg = GetBattleGround())
18791 bg->EventPlayerDroppedFlag(this);
18793 m_summon_expire = 0;
18795 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
18797 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18800 void Player::RemoveItemDurations( Item *item )
18802 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18804 if(*itr==item)
18806 m_itemDuration.erase(itr);
18807 break;
18812 void Player::AddItemDurations( Item *item )
18814 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18816 m_itemDuration.push_back(item);
18817 item->SendTimeUpdate(this);
18821 void Player::AutoUnequipOffhandIfNeed()
18823 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18824 if(!offItem)
18825 return;
18827 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18828 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18829 return;
18831 ItemPosCountVec off_dest;
18832 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18833 if( off_msg == EQUIP_ERR_OK )
18835 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18836 StoreItem( off_dest, offItem, true );
18838 else
18840 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18841 CharacterDatabase.BeginTransaction();
18842 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18843 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18844 CharacterDatabase.CommitTransaction();
18846 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18847 MailDraft(subject).AddItem(offItem).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
18851 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18853 if(spellInfo->EquippedItemClass < 0)
18854 return true;
18856 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18857 // for optimize check 2 used cases only
18858 switch(spellInfo->EquippedItemClass)
18860 case ITEM_CLASS_WEAPON:
18862 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18863 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18864 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18865 return true;
18866 break;
18868 case ITEM_CLASS_ARMOR:
18870 // tabard not have dependent spells
18871 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18872 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18873 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18874 return true;
18876 // shields can be equipped to offhand slot
18877 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18878 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18879 return true;
18881 // ranged slot can have some armor subclasses
18882 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18883 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18884 return true;
18886 break;
18888 default:
18889 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18890 break;
18893 return false;
18896 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18898 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18899 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18900 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18901 return true;
18903 // Check no reagent use mask
18904 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18905 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18906 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18907 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18908 return true;
18910 return false;
18913 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18915 AuraMap& auras = GetAuras();
18916 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
18918 Aura* aura = itr->second;
18920 // skip passive (passive item dependent spells work in another way) and not self applied auras
18921 SpellEntry const* spellInfo = aura->GetSpellProto();
18922 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18924 ++itr;
18925 continue;
18928 // skip if not item dependent or have alternative item
18929 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18931 ++itr;
18932 continue;
18935 // no alt item, remove aura, restart check
18936 RemoveAurasDueToSpell(aura->GetId());
18937 itr = auras.begin();
18940 // currently casted spells can be dependent from item
18941 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
18942 if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
18943 if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
18944 InterruptSpell(CurrentSpellTypes(i));
18947 uint32 Player::GetResurrectionSpellId()
18949 // search priceless resurrection possibilities
18950 uint32 prio = 0;
18951 uint32 spell_id = 0;
18952 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18953 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18955 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18956 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18958 switch((*itr)->GetId())
18960 case 20707: spell_id = 3026; break; // rank 1
18961 case 20762: spell_id = 20758; break; // rank 2
18962 case 20763: spell_id = 20759; break; // rank 3
18963 case 20764: spell_id = 20760; break; // rank 4
18964 case 20765: spell_id = 20761; break; // rank 5
18965 case 27239: spell_id = 27240; break; // rank 6
18966 case 47883: spell_id = 47882; break; // rank 7
18967 default:
18968 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
18969 continue;
18972 prio = 3;
18974 // Twisting Nether // prio: 2 (max)
18975 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18977 prio = 2;
18978 spell_id = 23700;
18982 // Reincarnation (passive spell) // prio: 1
18983 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18984 spell_id = 21169;
18986 return spell_id;
18989 // Used in triggers for check "Only to targets that grant experience or honor" req
18990 bool Player::isHonorOrXPTarget(Unit* pVictim)
18992 uint32 v_level = pVictim->getLevel();
18993 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18995 // Victim level less gray level
18996 if(v_level<=k_grey)
18997 return false;
18999 if(pVictim->GetTypeId() == TYPEID_UNIT)
19001 if (((Creature*)pVictim)->isTotem() ||
19002 ((Creature*)pVictim)->isPet() ||
19003 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
19004 return false;
19006 return true;
19009 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
19011 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
19013 // prepare data for near group iteration (PvP and !PvP cases)
19014 uint32 xp = 0;
19015 bool honored_kill = false;
19017 if(Group *pGroup = GetGroup())
19019 uint32 count = 0;
19020 uint32 sum_level = 0;
19021 Player* member_with_max_level = NULL;
19022 Player* not_gray_member_with_max_level = NULL;
19024 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
19026 if(member_with_max_level)
19028 /// not get Xp in PvP or no not gray players in group
19029 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
19031 /// skip in check PvP case (for speed, not used)
19032 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
19033 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
19034 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
19036 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19038 Player* pGroupGuy = itr->getSource();
19039 if(!pGroupGuy)
19040 continue;
19042 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
19043 continue; // member (alive or dead) or his corpse at req. distance
19045 // honor can be in PvP and !PvP (racial leader) cases (for alive)
19046 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
19047 honored_kill = true;
19049 // xp and reputation only in !PvP case
19050 if(!PvP)
19052 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
19054 // if is in dungeon then all receive full reputation at kill
19055 // rewarded any alive/dead/near_corpse group member
19056 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
19058 // XP updated only for alive group member
19059 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
19060 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
19062 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
19064 pGroupGuy->GiveXP(itr_xp, pVictim);
19065 if(Pet* pet = pGroupGuy->GetPet())
19066 pet->GivePetXP(itr_xp/2);
19069 // quest objectives updated only for alive group member or dead but with not released body
19070 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19072 // normal creature (not pet/etc) can be only in !PvP case
19073 if(pVictim->GetTypeId()==TYPEID_UNIT)
19074 pGroupGuy->KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19080 else // if (!pGroup)
19082 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
19084 // honor can be in PvP and !PvP (racial leader) cases
19085 if(RewardHonor(pVictim,1))
19086 honored_kill = true;
19088 // xp and reputation only in !PvP case
19089 if(!PvP)
19091 RewardReputation(pVictim,1);
19092 GiveXP(xp, pVictim);
19094 if(Pet* pet = GetPet())
19095 pet->GivePetXP(xp);
19097 // normal creature (not pet/etc) can be only in !PvP case
19098 if(pVictim->GetTypeId()==TYPEID_UNIT)
19099 KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19102 return xp || honored_kill;
19105 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
19107 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
19109 // prepare data for near group iteration
19110 if(Group *pGroup = GetGroup())
19112 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19114 Player* pGroupGuy = itr->getSource();
19115 if(!pGroupGuy)
19116 continue;
19118 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
19119 continue; // member (alive or dead) or his corpse at req. distance
19121 // quest objectives updated only for alive group member or dead but with not released body
19122 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19123 pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
19126 else // if (!pGroup)
19127 KilledMonsterCredit(creature_id, creature_guid);
19130 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
19132 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
19133 return true;
19135 if (isAlive())
19136 return false;
19138 Corpse* corpse = GetCorpse();
19139 if (!corpse)
19140 return false;
19142 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
19145 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
19147 Item* item = GetWeaponForAttack(attType,true);
19149 // unarmed only with base attack
19150 if(attType != BASE_ATTACK && !item)
19151 return 0;
19153 // weapon skill or (unarmed for base attack)
19154 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
19155 return GetBaseSkillValue(skill);
19158 void Player::ResurectUsingRequestData()
19160 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
19161 if(IS_PLAYER_GUID(m_resurrectGUID))
19162 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
19164 //we cannot resurrect player when we triggered far teleport
19165 //player will be resurrected upon teleportation
19166 if(IsBeingTeleportedFar())
19168 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
19169 return;
19172 ResurrectPlayer(0.0f,false);
19174 if(GetMaxHealth() > m_resurrectHealth)
19175 SetHealth( m_resurrectHealth );
19176 else
19177 SetHealth( GetMaxHealth() );
19179 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
19180 SetPower(POWER_MANA, m_resurrectMana );
19181 else
19182 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
19184 SetPower(POWER_RAGE, 0 );
19186 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
19188 SpawnCorpseBones();
19191 void Player::SetClientControl(Unit* target, uint8 allowMove)
19193 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
19194 data.append(target->GetPackGUID());
19195 data << uint8(allowMove);
19196 GetSession()->SendPacket(&data);
19199 void Player::UpdateZoneDependentAuras( uint32 newZone )
19201 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19202 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
19203 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19204 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
19205 if( !HasAura(itr->second->spellId,0) )
19206 CastSpell(this,itr->second->spellId,true);
19209 void Player::UpdateAreaDependentAuras( uint32 newArea )
19211 // remove auras from spells with area limitations
19212 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
19214 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19215 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
19216 RemoveAura(iter);
19217 else
19218 ++iter;
19221 // some auras applied at subzone enter
19222 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
19223 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19224 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
19225 if( !HasAura(itr->second->spellId,0) )
19226 CastSpell(this,itr->second->spellId,true);
19229 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
19231 if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
19232 (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
19234 return copseReclaimDelay[0];
19237 time_t now = time(NULL);
19238 // 0..2 full period
19239 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
19240 return copseReclaimDelay[count];
19243 void Player::UpdateCorpseReclaimDelay()
19245 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
19247 if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
19248 (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
19249 return;
19251 time_t now = time(NULL);
19252 if(now < m_deathExpireTime)
19254 // full and partly periods 1..3
19255 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
19256 if(count < MAX_DEATH_COUNT)
19257 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19258 else
19259 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19261 else
19262 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19265 void Player::SendCorpseReclaimDelay(bool load)
19267 Corpse* corpse = GetCorpse();
19268 if(!corpse)
19269 return;
19271 uint32 delay;
19272 if(load)
19274 if(corpse->GetGhostTime() > m_deathExpireTime)
19275 return;
19277 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19279 uint32 count;
19280 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19281 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19283 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19284 if(count>=MAX_DEATH_COUNT)
19285 count = MAX_DEATH_COUNT-1;
19287 else
19288 count=0;
19290 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19292 time_t now = time(NULL);
19293 if(now >= expected_time)
19294 return;
19296 delay = expected_time-now;
19298 else
19299 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19301 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19302 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19303 data << uint32(delay*IN_MILISECONDS);
19304 GetSession()->SendPacket( &data );
19307 Player* Player::GetNextRandomRaidMember(float radius)
19309 Group *pGroup = GetGroup();
19310 if(!pGroup)
19311 return NULL;
19313 std::vector<Player*> nearMembers;
19314 nearMembers.reserve(pGroup->GetMembersCount());
19316 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19318 Player* Target = itr->getSource();
19320 // IsHostileTo check duel and controlled by enemy
19321 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19322 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19323 nearMembers.push_back(Target);
19326 if (nearMembers.empty())
19327 return NULL;
19329 uint32 randTarget = urand(0,nearMembers.size()-1);
19330 return nearMembers[randTarget];
19333 PartyResult Player::CanUninviteFromGroup() const
19335 const Group* grp = GetGroup();
19336 if(!grp)
19337 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19339 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19340 return PARTY_RESULT_YOU_NOT_LEADER;
19342 if(InBattleGround())
19343 return PARTY_RESULT_INVITE_RESTRICTED;
19345 return PARTY_RESULT_OK;
19348 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
19350 //we must move references from m_group to m_originalGroup
19351 SetOriginalGroup(GetGroup(), GetSubGroup());
19353 m_group.unlink();
19354 m_group.link(group, this);
19355 m_group.setSubGroup((uint8)subgroup);
19358 void Player::RemoveFromBattleGroundRaid()
19360 //remove existing reference
19361 m_group.unlink();
19362 if( Group* group = GetOriginalGroup() )
19364 m_group.link(group, this);
19365 m_group.setSubGroup(GetOriginalSubGroup());
19367 SetOriginalGroup(NULL);
19370 void Player::SetOriginalGroup(Group *group, int8 subgroup)
19372 if( group == NULL )
19373 m_originalGroup.unlink();
19374 else
19376 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19377 assert(subgroup >= 0);
19378 m_originalGroup.link(group, this);
19379 m_originalGroup.setSubGroup((uint8)subgroup);
19383 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19385 LiquidData liquid_status;
19386 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
19387 if (!res)
19389 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
19390 // Small hack for enable breath in WMO
19391 if (IsInWater())
19392 m_MirrorTimerFlags|=UNDERWATER_INWATER;
19393 return;
19396 // All liquids type - check under water position
19397 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
19399 if ( res & LIQUID_MAP_UNDER_WATER)
19400 m_MirrorTimerFlags |= UNDERWATER_INWATER;
19401 else
19402 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
19405 // Allow travel in dark water on taxi or transport
19406 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
19407 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
19408 else
19409 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
19411 // in lava check, anywhere in lava level
19412 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
19414 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19415 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
19416 else
19417 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
19419 // in slime check, anywhere in slime level
19420 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
19422 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19423 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
19424 else
19425 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
19429 void Player::SetCanParry( bool value )
19431 if(m_canParry==value)
19432 return;
19434 m_canParry = value;
19435 UpdateParryPercentage();
19438 void Player::SetCanBlock( bool value )
19440 if(m_canBlock==value)
19441 return;
19443 m_canBlock = value;
19444 UpdateBlockPercentage();
19447 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19449 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19450 if(itr->pos == pos)
19451 return true;
19453 return false;
19456 bool Player::CanUseBattleGroundObject()
19458 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19459 // maybe gameobject code should handle that ForceReaction usage
19460 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19461 return ( //InBattleGround() && // in battleground - not need, check in other cases
19462 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19463 //player cannot use object when he is invulnerable (immune)
19464 !isTotalImmune() && // not totally immune
19465 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19466 !HasStealthAura() && // not stealthed
19467 !HasInvisibilityAura() && // not invisible
19468 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19469 isAlive() // live player
19473 bool Player::CanCaptureTowerPoint()
19475 return ( !HasStealthAura() && // not stealthed
19476 !HasInvisibilityAura() && // not invisible
19477 isAlive() // live player
19481 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19483 uint32 level = getLevel();
19485 if(level > GT_MAX_LEVEL)
19486 level = GT_MAX_LEVEL; // max level in this dbc
19488 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19489 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19490 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19492 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19493 return 0;
19495 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19497 if(!bsc) // shouldn't happen
19498 return 0xFFFFFFFF;
19500 float cost = 0;
19502 if(hairstyle != newhairstyle)
19503 cost += bsc->cost; // full price
19505 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19506 cost += bsc->cost * 0.5f; // +1/2 of price
19508 if(facialhair != newfacialhair)
19509 cost += bsc->cost * 0.75f; // +3/4 of price
19511 return uint32(cost);
19514 void Player::InitGlyphsForLevel()
19516 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19517 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19518 if(gs->Order)
19519 SetGlyphSlot(gs->Order - 1, gs->Id);
19521 uint32 level = getLevel();
19522 uint32 value = 0;
19524 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19525 if(level >= 15)
19526 value |= (0x01 | 0x02);
19527 if(level >= 30)
19528 value |= 0x08;
19529 if(level >= 50)
19530 value |= 0x04;
19531 if(level >= 70)
19532 value |= 0x10;
19533 if(level >= 80)
19534 value |= 0x20;
19536 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19539 void Player::EnterVehicle(Vehicle *vehicle)
19541 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19542 if(!ve)
19543 return;
19545 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19546 if(!veSeat)
19547 return;
19549 vehicle->SetCharmerGUID(GetGUID());
19550 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19551 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
19552 vehicle->setFaction(getFaction());
19554 SetCharm(vehicle); // charm
19555 SetFarSightGUID(vehicle->GetGUID()); // set view
19557 SetClientControl(vehicle, 1); // redirect controls to vehicle
19558 SetMover(vehicle);
19560 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19561 GetSession()->SendPacket(&data);
19563 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19564 data.append(GetPackGUID());
19565 data << uint32(0); // counter?
19566 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19567 data << uint16(0); // special flags
19568 data << uint32(getMSTime()); // time
19569 data << vehicle->GetPositionX(); // x
19570 data << vehicle->GetPositionY(); // y
19571 data << vehicle->GetPositionZ(); // z
19572 data << vehicle->GetOrientation(); // o
19573 // transport part, TODO: load/calculate seat offsets
19574 data << uint64(vehicle->GetGUID()); // transport guid
19575 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19576 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19577 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19578 data << float(0); // transport orientation
19579 data << uint32(getMSTime()); // transport time
19580 data << uint8(0); // seat
19581 // end of transport part
19582 data << uint32(0); // fall time
19583 GetSession()->SendPacket(&data);
19585 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
19586 data << uint64(vehicle->GetGUID());
19587 data << uint16(0);
19588 data << uint32(0);
19589 data << uint32(0x00000101);
19591 for(uint32 i = 0; i < 10; ++i)
19592 data << uint16(0) << uint8(0) << uint8(i+8);
19594 data << uint8(0);
19595 data << uint8(0);
19596 GetSession()->SendPacket(&data);
19599 void Player::ExitVehicle(Vehicle *vehicle)
19601 vehicle->SetCharmerGUID(0);
19602 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19603 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
19604 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19606 SetCharm(NULL);
19607 SetFarSightGUID(0);
19609 SetClientControl(vehicle, 0);
19610 SetMover(NULL);
19612 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19613 data.append(GetPackGUID());
19614 data << uint32(0); // counter?
19615 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19616 data << uint16(0x40); // special flags
19617 data << uint32(getMSTime()); // time
19618 data << vehicle->GetPositionX(); // x
19619 data << vehicle->GetPositionY(); // y
19620 data << vehicle->GetPositionZ(); // z
19621 data << vehicle->GetOrientation(); // o
19622 data << uint32(0); // fall time
19623 GetSession()->SendPacket(&data);
19625 RemovePetActionBar();
19627 // maybe called at dummy aura remove?
19628 // CastSpell(this, 45472, true); // Parachute
19631 bool Player::isTotalImmune()
19633 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19635 uint32 immuneMask = 0;
19636 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19638 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19639 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19640 return true;
19642 return false;
19645 bool Player::HasTitle(uint32 bitIndex)
19647 if (bitIndex > MAX_TITLE_INDEX)
19648 return false;
19650 uint32 fieldIndexOffset = bitIndex / 32;
19651 uint32 flag = 1 << (bitIndex % 32);
19652 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19655 void Player::SetTitle(CharTitlesEntry const* title, bool lost)
19657 uint32 fieldIndexOffset = title->bit_index / 32;
19658 uint32 flag = 1 << (title->bit_index % 32);
19660 if(lost)
19662 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
19663 return;
19665 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19667 else
19669 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
19670 return;
19672 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19675 WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
19676 data << uint32(title->bit_index);
19677 data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
19678 GetSession()->SendPacket(&data);
19681 void Player::ConvertRune(uint8 index, RuneType newType)
19683 SetCurrentRune(index, newType);
19685 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19686 data << uint8(index);
19687 data << uint8(newType);
19688 GetSession()->SendPacket(&data);
19691 void Player::ResyncRunes(uint8 count)
19693 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19694 for(uint32 i = 0; i < count; ++i)
19696 data << uint8(GetCurrentRune(i)); // rune type
19697 data << uint8(255 - ((GetRuneCooldown(i) / REGEN_TIME_FULL) * 51)); // passed cooldown time (0-255)
19699 GetSession()->SendPacket(&data);
19702 void Player::AddRunePower(uint8 index)
19704 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19705 data << uint32(1 << index); // mask (0x00-0x3F probably)
19706 GetSession()->SendPacket(&data);
19709 static RuneType runeSlotTypes[MAX_RUNES] = {
19710 /*0*/ RUNE_BLOOD,
19711 /*1*/ RUNE_BLOOD,
19712 /*2*/ RUNE_UNHOLY,
19713 /*3*/ RUNE_UNHOLY,
19714 /*4*/ RUNE_FROST,
19715 /*5*/ RUNE_FROST
19718 void Player::InitRunes()
19720 if(getClass() != CLASS_DEATH_KNIGHT)
19721 return;
19723 m_runes = new Runes;
19725 m_runes->runeState = 0;
19727 for(uint32 i = 0; i < MAX_RUNES; ++i)
19729 SetBaseRune(i, runeSlotTypes[i]); // init base types
19730 SetCurrentRune(i, runeSlotTypes[i]); // init current types
19731 SetRuneCooldown(i, 0); // reset cooldowns
19732 m_runes->SetRuneState(i);
19735 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19736 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19740 bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType ) const
19742 for(uint32 i = 0; i < MAX_RUNES; ++i)
19743 if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
19744 return false;
19746 return true;
19749 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19751 Loot loot;
19752 loot.FillLoot (loot_id,store,this,true);
19754 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19755 for(uint32 i = 0; i < max_slot; ++i)
19757 LootItem* lootItem = loot.LootItemInSlot(i,this);
19759 ItemPosCountVec dest;
19760 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19761 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19762 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19763 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19764 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19765 if(msg != EQUIP_ERR_OK)
19767 SendEquipError( msg, NULL, NULL );
19768 continue;
19771 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19772 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19776 uint32 Player::CalculateTalentsPoints() const
19778 uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
19780 if(getClass() != CLASS_DEATH_KNIGHT)
19781 return uint32(base_talent * sWorld.getRate(RATE_TALENT));
19783 uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
19784 talentPointsForLevel += m_questRewardTalentCount;
19786 if(talentPointsForLevel > base_talent)
19787 talentPointsForLevel = base_talent;
19789 return uint32(talentPointsForLevel * sWorld.getRate(RATE_TALENT));
19792 bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
19794 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
19795 uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
19796 return v_map != 571 || HasSpell(54197); // Cold Weather Flying
19799 struct DoPlayerLearnSpell
19801 DoPlayerLearnSpell(Player& _player) : player(_player) {}
19802 void operator() (uint32 spell_id) { player.learnSpell(spell_id,false); }
19803 Player& player;
19806 void Player::learnSpellHighRank(uint32 spellid)
19808 learnSpell(spellid,false);
19810 DoPlayerLearnSpell worker(*this);
19811 spellmgr.doForHighRanks(spellid,worker);
19814 void Player::_LoadSkills()
19816 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19818 // reset skill modifiers and set correct unlearn flags
19819 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
19821 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19823 // set correct unlearn bit
19824 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19825 if(!id) continue;
19827 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19828 if(!pSkill) continue;
19830 // enable unlearn button for primary professions only
19831 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19832 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19833 else
19834 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19836 // set fixed skill ranges
19837 switch(GetSkillRangeType(pSkill,false))
19839 case SKILL_RANGE_LANGUAGE: // 300..300
19840 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19841 break;
19842 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19843 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19844 break;
19845 default:
19846 break;
19849 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19850 learnSkillRewardedSpells(id, vskill);
19853 // special settings
19854 if(getClass()==CLASS_DEATH_KNIGHT)
19856 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19857 if(base_level < 1)
19858 base_level = 1;
19859 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19860 if(base_skill < 1)
19861 base_skill = 1; // skill mast be known and then > 0 in any case
19863 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19864 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19865 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19866 SetSkill(SKILL_AXES, base_skill,base_skill);
19867 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19868 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19869 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19870 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19871 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19872 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19873 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19874 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19875 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19876 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19877 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19878 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19882 uint32 Player::GetPhaseMaskForSpawn() const
19884 uint32 phase = PHASEMASK_NORMAL;
19885 if(!isGameMaster())
19886 phase = GetPhaseMask();
19887 else
19889 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19890 if(!phases.empty())
19891 phase = phases.front()->GetMiscValue();
19894 // some aura phases include 1 normal map in addition to phase itself
19895 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19896 return n_phase;
19898 return PHASEMASK_NORMAL;
19901 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19903 ItemPrototype const* pProto = pItem->GetProto();
19905 // proto based limitations
19906 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19907 return res;
19909 // check unique-equipped on gems
19910 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19912 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19913 if(!enchant_id)
19914 continue;
19915 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19916 if(!enchantEntry)
19917 continue;
19919 ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID);
19920 if(!pGem)
19921 continue;
19923 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19924 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19925 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19927 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19928 return res;
19931 return EQUIP_ERR_OK;
19934 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19936 // check unique-equipped on item
19937 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19939 // there is an equip limit on this item
19940 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19941 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19944 // check unique-equipped limit
19945 if (itemProto->ItemLimitCategory)
19947 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19948 if(!limitEntry)
19949 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19951 if(limit_count > limitEntry->maxCount)
19952 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19954 // there is an equip limit on this item
19955 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19956 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19959 return EQUIP_ERR_OK;
19962 void Player::HandleFall(MovementInfo const& movementInfo)
19964 // calculate total z distance of the fall
19965 float z_diff = m_lastFallZ - movementInfo.z;
19966 sLog.outDebug("zDiff = %f", z_diff);
19968 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19969 // 14.57 can be calculated by resolving damageperc formula below to 0
19970 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19971 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19972 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19974 //Safe fall, fall height reduction
19975 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19977 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19979 if(damageperc >0 )
19981 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19983 float height = movementInfo.z;
19984 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19986 if (damage > 0)
19988 //Prevent fall damage from being more than the player maximum health
19989 if (damage > GetMaxHealth())
19990 damage = GetMaxHealth();
19992 // Gust of Wind
19993 if (GetDummyAura(43621))
19994 damage = GetMaxHealth()/2;
19996 uint32 original_health = GetHealth();
19997 uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
19999 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
20000 if (isAlive() && final_damage < original_health)
20001 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
20004 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
20005 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);
20010 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
20012 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
20015 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
20017 uint32 CurTalentPoints = GetFreeTalentPoints();
20019 if(CurTalentPoints == 0)
20020 return;
20022 if (talentRank >= MAX_TALENT_RANK)
20023 return;
20025 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
20027 if(!talentInfo)
20028 return;
20030 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
20032 if(!talentTabInfo)
20033 return;
20035 // prevent learn talent for different class (cheating)
20036 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
20037 return;
20039 // find current max talent rank
20040 int32 curtalent_maxrank = 0;
20041 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20043 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20045 curtalent_maxrank = k + 1;
20046 break;
20050 // we already have same or higher talent rank learned
20051 if(curtalent_maxrank >= (talentRank + 1))
20052 return;
20054 // check if we have enough talent points
20055 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20056 return;
20058 // Check if it requires another talent
20059 if (talentInfo->DependsOn > 0)
20061 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20063 bool hasEnoughRank = false;
20064 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20066 if (depTalentInfo->RankID[i] != 0)
20067 if (HasSpell(depTalentInfo->RankID[i]))
20068 hasEnoughRank = true;
20070 if (!hasEnoughRank)
20071 return;
20075 // Find out how many points we have in this field
20076 uint32 spentPoints = 0;
20078 uint32 tTab = talentInfo->TalentTab;
20079 if (talentInfo->Row > 0)
20081 unsigned int numRows = sTalentStore.GetNumRows();
20082 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20084 // Someday, someone needs to revamp
20085 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20086 if (tmpTalent) // the way talents are tracked
20088 if (tmpTalent->TalentTab == tTab)
20090 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20092 if (tmpTalent->RankID[j] != 0)
20094 if (HasSpell(tmpTalent->RankID[j]))
20096 spentPoints += j + 1;
20105 // not have required min points spent in talent tree
20106 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
20107 return;
20109 // spell not set in talent.dbc
20110 uint32 spellid = talentInfo->RankID[talentRank];
20111 if( spellid == 0 )
20113 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20114 return;
20117 // already known
20118 if(HasSpell(spellid))
20119 return;
20121 // learn! (other talent ranks will unlearned at learning)
20122 learnSpell(spellid, false);
20123 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20125 // update free talent points
20126 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20129 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
20131 Pet *pet = GetPet();
20133 if(!pet)
20134 return;
20136 if(petGuid != pet->GetGUID())
20137 return;
20139 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
20141 if(CurTalentPoints == 0)
20142 return;
20144 if (talentRank >= MAX_PET_TALENT_RANK)
20145 return;
20147 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
20149 if(!talentInfo)
20150 return;
20152 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
20154 if(!talentTabInfo)
20155 return;
20157 CreatureInfo const *ci = pet->GetCreatureInfo();
20159 if(!ci)
20160 return;
20162 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20164 if(!pet_family)
20165 return;
20167 if(pet_family->petTalentType < 0) // not hunter pet
20168 return;
20170 // prevent learn talent for different family (cheating)
20171 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20172 return;
20174 // find current max talent rank
20175 int32 curtalent_maxrank = 0;
20176 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20178 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20180 curtalent_maxrank = k + 1;
20181 break;
20185 // we already have same or higher talent rank learned
20186 if(curtalent_maxrank >= (talentRank + 1))
20187 return;
20189 // check if we have enough talent points
20190 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20191 return;
20193 // Check if it requires another talent
20194 if (talentInfo->DependsOn > 0)
20196 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20198 bool hasEnoughRank = false;
20199 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20201 if (depTalentInfo->RankID[i] != 0)
20202 if (pet->HasSpell(depTalentInfo->RankID[i]))
20203 hasEnoughRank = true;
20205 if (!hasEnoughRank)
20206 return;
20210 // Find out how many points we have in this field
20211 uint32 spentPoints = 0;
20213 uint32 tTab = talentInfo->TalentTab;
20214 if (talentInfo->Row > 0)
20216 unsigned int numRows = sTalentStore.GetNumRows();
20217 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20219 // Someday, someone needs to revamp
20220 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20221 if (tmpTalent) // the way talents are tracked
20223 if (tmpTalent->TalentTab == tTab)
20225 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20227 if (tmpTalent->RankID[j] != 0)
20229 if (pet->HasSpell(tmpTalent->RankID[j]))
20231 spentPoints += j + 1;
20240 // not have required min points spent in talent tree
20241 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
20242 return;
20244 // spell not set in talent.dbc
20245 uint32 spellid = talentInfo->RankID[talentRank];
20246 if( spellid == 0 )
20248 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20249 return;
20252 // already known
20253 if(pet->HasSpell(spellid))
20254 return;
20256 // learn! (other talent ranks will unlearned at learning)
20257 pet->learnSpell(spellid);
20258 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20260 // update free talent points
20261 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20264 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
20266 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
20268 if(apply)
20269 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
20270 else
20271 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
20275 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
20277 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
20278 SetFallInformation(minfo.fallTime, minfo.z);
20281 void Player::UnsummonPetTemporaryIfAny()
20283 Pet* pet = GetPet();
20284 if(!pet)
20285 return;
20287 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
20289 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
20290 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
20293 RemovePet(pet, PET_SAVE_AS_CURRENT);
20296 void Player::ResummonPetTemporaryUnSummonedIfAny()
20298 if(!m_temporaryUnsummonedPetNumber)
20299 return;
20301 // not resummon in not appropriate state
20302 if(IsPetNeedBeTemporaryUnsummoned())
20303 return;
20305 if(GetPetGUID())
20306 return;
20308 Pet* NewPet = new Pet;
20309 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
20310 delete NewPet;
20312 m_temporaryUnsummonedPetNumber = 0;
20315 bool Player::canSeeSpellClickOn(Creature const *c) const
20317 if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
20318 return false;
20320 SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(c->GetEntry());
20321 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
20322 if(itr->second.IsFitToRequirements(this))
20323 return true;
20325 return false;
20328 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
20330 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
20331 *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
20332 *data << uint8(m_activeSpec); // talent group index (0 or 1)
20334 if(m_specsCount)
20336 // loop through all specs (only 1 for now)
20337 for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
20339 uint8 talentIdCount = 0;
20340 size_t pos = data->wpos();
20341 *data << uint8(talentIdCount); // [PH], talentIdCount
20343 // find class talent tabs (all players have 3 talent tabs)
20344 uint32 const* talentTabIds = GetTalentTabPages(getClass());
20346 for(uint32 i = 0; i < 3; ++i)
20348 uint32 talentTabId = talentTabIds[i];
20350 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20352 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20353 if(!talentInfo)
20354 continue;
20356 // skip another tab talents
20357 if(talentInfo->TalentTab != talentTabId)
20358 continue;
20360 // find max talent rank
20361 int32 curtalent_maxrank = -1;
20362 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20364 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20366 curtalent_maxrank = k;
20367 break;
20371 // not learned talent
20372 if(curtalent_maxrank < 0)
20373 continue;
20375 *data << uint32(talentInfo->TalentID); // Talent.dbc
20376 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20378 ++talentIdCount;
20382 data->put<uint8>(pos, talentIdCount); // put real count
20384 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
20386 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
20387 *data << uint16(GetGlyph(i)); // GlyphProperties.dbc
20392 void Player::BuildPetTalentsInfoData(WorldPacket *data)
20394 uint32 unspentTalentPoints = 0;
20395 size_t pointsPos = data->wpos();
20396 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
20398 uint8 talentIdCount = 0;
20399 size_t countPos = data->wpos();
20400 *data << uint8(talentIdCount); // [PH], talentIdCount
20402 Pet *pet = GetPet();
20403 if(!pet)
20404 return;
20406 unspentTalentPoints = pet->GetFreeTalentPoints();
20408 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
20410 CreatureInfo const *ci = pet->GetCreatureInfo();
20411 if(!ci)
20412 return;
20414 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20415 if(!pet_family || pet_family->petTalentType < 0)
20416 return;
20418 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
20420 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
20421 if(!talentTabInfo)
20422 continue;
20424 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20425 continue;
20427 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20429 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20430 if(!talentInfo)
20431 continue;
20433 // skip another tab talents
20434 if(talentInfo->TalentTab != talentTabId)
20435 continue;
20437 // find max talent rank
20438 int32 curtalent_maxrank = -1;
20439 for(int32 k = 4; k > -1; --k)
20441 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20443 curtalent_maxrank = k;
20444 break;
20448 // not learned talent
20449 if(curtalent_maxrank < 0)
20450 continue;
20452 *data << uint32(talentInfo->TalentID); // Talent.dbc
20453 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20455 ++talentIdCount;
20458 data->put<uint8>(countPos, talentIdCount); // put real count
20460 break;
20464 void Player::SendTalentsInfoData(bool pet)
20466 WorldPacket data(SMSG_TALENTS_INFO, 50);
20467 data << uint8(pet ? 1 : 0);
20468 if(pet)
20469 BuildPetTalentsInfoData(&data);
20470 else
20471 BuildPlayerTalentsInfoData(&data);
20472 GetSession()->SendPacket(&data);
20475 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
20477 uint32 slotUsedMask = 0;
20478 size_t slotUsedMaskPos = data->wpos();
20479 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
20481 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20483 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
20485 if(!item)
20486 continue;
20488 slotUsedMask |= (1 << i);
20490 *data << uint32(item->GetEntry()); // item entry
20492 uint16 enchantmentMask = 0;
20493 size_t enchantmentMaskPos = data->wpos();
20494 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
20496 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
20498 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
20500 if(!enchId)
20501 continue;
20503 enchantmentMask |= (1 << j);
20505 *data << uint16(enchId); // enchantmentId?
20508 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
20510 *data << uint16(0); // ?
20511 *data << uint8(0); // PGUID!
20512 *data << uint32(0); // seed?
20515 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
20518 void Player::SendEquipmentSetList()
20520 uint32 count = 0;
20521 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
20522 size_t count_pos = data.wpos();
20523 data << uint32(count); // count placeholder
20524 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20526 if(itr->second.state==EQUIPMENT_SET_DELETED)
20527 continue;
20528 data.appendPackGUID(itr->second.Guid);
20529 data << uint32(itr->first);
20530 data << itr->second.Name;
20531 data << itr->second.IconName;
20532 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20533 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
20535 ++count; // client have limit but it checked at loading and set
20537 data.put<uint32>(count_pos, count);
20538 GetSession()->SendPacket(&data);
20541 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
20543 if(eqset.Guid != 0)
20545 bool found = false;
20547 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20549 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
20551 found = true;
20552 break;
20556 if(!found) // something wrong...
20558 sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
20559 return;
20563 EquipmentSet& eqslot = m_EquipmentSets[index];
20565 EquipmentSetUpdateState old_state = eqslot.state;
20567 eqslot = eqset;
20569 if(eqset.Guid == 0)
20571 eqslot.Guid = objmgr.GenerateEquipmentSetGuid();
20573 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
20574 data << uint32(index);
20575 data.appendPackGUID(eqslot.Guid);
20576 GetSession()->SendPacket(&data);
20579 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
20582 void Player::_SaveEquipmentSets()
20584 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
20586 uint32 index = itr->first;
20587 EquipmentSet& eqset = itr->second;
20588 switch(eqset.state)
20590 case EQUIPMENT_SET_UNCHANGED:
20591 ++itr;
20592 break; // nothing do
20593 case EQUIPMENT_SET_CHANGED:
20594 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'",
20595 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],
20596 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);
20597 eqset.state = EQUIPMENT_SET_UNCHANGED;
20598 ++itr;
20599 break;
20600 case EQUIPMENT_SET_NEW:
20601 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')",
20602 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],
20603 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]);
20604 eqset.state = EQUIPMENT_SET_UNCHANGED;
20605 ++itr;
20606 break;
20607 case EQUIPMENT_SET_DELETED:
20608 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
20609 m_EquipmentSets.erase(itr++);
20610 break;
20615 void Player::_SaveBGData()
20617 CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
20618 if (m_bgData.bgInstanceID)
20620 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
20621 CharacterDatabase.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
20622 GetGUIDLow(), m_bgData.bgInstanceID, m_bgData.bgTeam, m_bgData.joinPos.coord_x, m_bgData.joinPos.coord_y, m_bgData.joinPos.coord_z,
20623 m_bgData.joinPos.orientation, m_bgData.joinPos.mapid, m_bgData.taxiPath[0], m_bgData.taxiPath[1], m_bgData.mountSpell);
20627 void Player::DeleteEquipmentSet(uint64 setGuid)
20629 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20631 if(itr->second.Guid == setGuid)
20633 if(itr->second.state == EQUIPMENT_SET_NEW)
20634 m_EquipmentSets.erase(itr);
20635 else
20636 itr->second.state = EQUIPMENT_SET_DELETED;
20637 break;
20642 void Player::ActivateSpec(uint32 specNum)
20644 if(GetActiveSpec() == specNum)
20645 return;
20647 resetTalents(true);
20650 void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
20652 m_atLoginFlags &= ~f;
20654 if(in_db_also)
20655 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
20658 void Player::SendClearCooldown( uint32 spell_id, Unit* target )
20660 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
20661 data << uint32(spell_id);
20662 data << uint64(target->GetGUID());
20663 SendDirectMessage(&data);
20666 void Player::BuildTeleportAckMsg( WorldPacket *data, float x, float y, float z, float ang ) const
20668 data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
20669 data->append(GetPackGUID());
20670 *data << uint32(0); // this value increments every time
20671 *data << uint32(m_movementInfo.GetMovementFlags()); // movement flags
20672 *data << uint16(0); // 2.3.0
20673 *data << uint32(getMSTime()); // time
20674 *data << x;
20675 *data << y;
20676 *data << z;
20677 *data << ang;
20678 *data << uint32(0);
20681 bool Player::HasMovementFlag( MovementFlags f ) const
20683 return m_movementInfo.HasMovementFlag(f);
20686 void Player::SetFarSightGUID( uint64 guid )
20688 if(GetFarSight() == guid)
20689 return;
20691 SetUInt64Value(PLAYER_FARSIGHT, guid);
20693 // need triggering load grids around new view point
20694 UpdateVisibilityForPlayer();
20697 void Player::UpdateVisibilityForPlayer()
20699 WorldObject const* viewPoint = GetViewPoint();
20700 Map* m = GetMap();
20702 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
20703 Cell cell(p);
20705 m->UpdatePlayerVisibility(this, cell, p);
20707 if (this != viewPoint)
20709 CellPair pView(MaNGOS::ComputeCellPair(viewPoint->GetPositionX(), viewPoint->GetPositionY()));
20710 Cell cellView(pView);
20712 m->UpdateObjectsVisibilityFor(this, cellView, pView);
20714 else
20715 m->UpdateObjectsVisibilityFor(this, cell, p);
20718 void Player::SendDuelCountdown(uint32 counter)
20720 WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
20721 data << uint32(counter); // seconds
20722 GetSession()->SendPacket(&data);